Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:LaurentMazare Tch rs CModule Forward Ts

From Leeroopedia


Knowledge Sources
Domains Model_Inference, Interoperability
Last Updated 2026-02-08 14:00 GMT

Overview

Concrete tool for executing TorchScript model forward passes with tensor inputs provided by the tch wrappers module.

Description

CModule::forward_ts takes a slice of input tensors and executes the model's forward method through the libtorch TorchScript runtime. For models with non-tensor I/O, forward_is accepts IValue inputs and returns IValue outputs. The CModule also implements the Module trait, allowing Tensor::apply(&model) for convenience.

Usage

Use forward_ts for standard inference with tensor inputs. Pass inputs as a slice: &[image.unsqueeze(0)].

Code Reference

Source Location

  • Repository: tch-rs
  • File: src/wrappers/jit.rs
  • Lines: 481-486 (forward_ts), 490-498 (forward_is)

Signature

impl CModule {
    pub fn forward_ts<T: Borrow<Tensor>>(&self, ts: &[T]) -> Result<Tensor, TchError>
    pub fn forward_is<T: Borrow<IValue>>(&self, ts: &[T]) -> Result<IValue, TchError>
}

Import

use tch::CModule;

I/O Contract

Inputs

Name Type Required Description
ts &[T: Borrow<Tensor>] Yes Slice of input tensors for forward_ts

Outputs

Name Type Description
Result<Tensor> Tensor Model output logits (for forward_ts)

Usage Examples

use tch::{CModule, Kind, vision::imagenet};

let model = CModule::load("resnet18.pt")?;
let image = imagenet::load_image_and_resize224("photo.jpg")?;
let input = image.unsqueeze(0);

// Using forward_ts
let output = model.forward_ts(&[&input])?;
let probs = output.softmax(-1, Kind::Float);
let top5 = imagenet::top(&probs, 5);

// Or using Module trait via apply
let output = input.apply(&model);

Related Pages

Implements Principle

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment