Implementation:LaurentMazare Tch rs ModuleT Forward T
| Knowledge Sources | |
|---|---|
| Domains | Deep_Learning, Model_Inference |
| Last Updated | 2026-02-08 14:00 GMT |
Overview
Concrete tool for executing a training-aware forward pass through a neural network provided by the tch nn module.
Description
The ModuleT::forward_t trait method and its helper Tensor::apply_t execute a forward pass with explicit training/evaluation mode control. The Module trait has a blanket implementation of ModuleT that ignores the train flag. The batch_accuracy_for_logits method on ModuleT provides a convenience utility for computing accuracy over batched evaluation.
Usage
Use forward_t(&input, false) or input.apply_t(&model, false) for inference. Use forward_t(&input, true) during training when the model contains dropout or batch normalization layers.
Code Reference
Source Location
- Repository: tch-rs
- File: src/nn/module.rs
- Lines: 14 (trait definition), 50-52 (apply_t helper)
Signature
pub trait ModuleT: std::fmt::Debug + Send {
fn forward_t(&self, xs: &Tensor, train: bool) -> Tensor;
}
// Helper on Tensor
impl Tensor {
pub fn apply_t<M: ModuleT>(&self, m: &M, train: bool) -> Tensor;
}
Import
use tch::nn::ModuleT;
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| xs | &Tensor | Yes | Input tensor (e.g., [batch, 3, 224, 224] for images) |
| train | bool | Yes | true for training mode, false for evaluation/inference |
Outputs
| Name | Type | Description |
|---|---|---|
| Tensor | Tensor | Model output (logits), typically [batch, num_classes] |
Usage Examples
use tch::nn::ModuleT;
// Direct method call
let logits = model.forward_t(&input, false);
// Via Tensor helper
let logits = input.apply_t(&model, false);
// Batch evaluation
let accuracy = model.batch_accuracy_for_logits(
&test_images, &test_labels, device, 256
);