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 Nn Linear

From Leeroopedia


Knowledge Sources
Domains Deep_Learning, Neural_Network_Layers
Last Updated 2026-02-08 14:00 GMT

Overview

Concrete tool for creating fully-connected linear layers provided by the tch nn module.

Description

nn::linear creates a Linear struct containing a weight tensor of shape [out_dim, in_dim] and an optional bias tensor of shape [out_dim]. The parameters are registered into the VarStore via the provided path. The Linear struct implements the Module trait, computing xs.linear(&ws, bs) in its forward method.

Usage

Use this to create dense layers in feedforward networks, classification heads, or any fully-connected projection. Configure bias and initialization via LinearConfig.

Code Reference

Source Location

  • Repository: tch-rs
  • File: src/nn/linear.rs
  • Lines: 27-45

Signature

pub fn linear<'a, T: Borrow<Path<'a>>>(
    vs: T,
    in_dim: i64,
    out_dim: i64,
    c: LinearConfig,
) -> Linear

Import

use tch::nn;

I/O Contract

Inputs

Name Type Required Description
vs T: Borrow<Path> Yes VarStore path for parameter registration
in_dim i64 Yes Number of input features
out_dim i64 Yes Number of output features
c LinearConfig Yes Configuration: ws_init, bs_init, bias (use Default::default())

Outputs

Name Type Description
Linear nn::Linear Struct with ws: Tensor[out_dim, in_dim], bs: Option<Tensor[out_dim]>, implementing Module

Usage Examples

Basic Linear Layer

use tch::{nn, nn::Module, Device};

let vs = nn::VarStore::new(Device::Cpu);
let linear = nn::linear(vs.root() / "fc", 784, 10, Default::default());

let input = tch::Tensor::randn([32, 784], tch::kind::FLOAT_CPU);
let output = linear.forward(&input);  // shape: [32, 10]

Without Bias

use tch::nn::{self, LinearConfig};

let c = LinearConfig { bias: false, ..Default::default() };
let linear = nn::linear(vs.root() / "fc_no_bias", 4096, 32000, c);

Related Pages

Implements Principle

Page Connections

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