ποΈ
Real-World Context: Modular Neural Network Engineering with torch.nn
At the core of every deep learning architectureβfrom real-time tabular credit underwriting models and multi-task autonomous driving perception heads to massive Transformer language modelsβlies torch.nn.Module and the dense affine projection layer torch.nn.Linear.
Rather than manually juggling raw weight tensors and bias vectors, subclassing nn.Module automatically tracks trainable nn.Parameter leaves, non-trainable state buffers, device transfers (.to("cuda")), train/eval mode switching, and deterministic serialization via state_dict(). Understanding how nn.Linear projects arbitrary N-dimensional tensors along their trailing feature axis is essential for building scalable, production-grade neural pipelines.
nn.Linear) β Real-Time Credit Risk Scoring Modelin_features=12, out_features=1), inspecting the internally transposed weight matrix of shape [1, 12] and bias vector of shape [1], and verifying exact equivalence with manual matrix multiplication x @ W.T + b.
import torch
import torch.nn as nn
torch.manual_seed(42)
# Batch of 4 loan applicants, each represented by 12 normalized financial features
applicant_features = torch.randn(4, 12)
# Define affine risk scoring layer: y = x @ W^T + b
risk_scorer = nn.Linear(in_features=12, out_features=1, bias=True)
# Forward pass through nn.Linear
logits = risk_scorer(applicant_features)
# Manual affine computation verifying PyTorch's stored weight layout [out_features, in_features]
manual_logits = applicant_features @ risk_scorer.weight.T + risk_scorer.bias
print("Weight Matrix Shape [out, in] :", risk_scorer.weight.shape)
print("Bias Vector Shape [out] :", risk_scorer.bias.shape)
print("Output Risk Logits Shape :", logits.shape)
print("Predicted Default Logits :", [round(v, 4) for v in logits.squeeze(-1).tolist()])
print("Exact Manual Equivalence :", torch.allclose(logits, manual_logits, atol=1e-6))
Output: Weight Matrix Shape [out, in] : torch.Size([1, 12]) Bias Vector Shape [out] : torch.Size([1]) Output Risk Logits Shape : torch.Size([4, 1]) Predicted Default Logits : [0.3912, -0.1847, 0.5421, -0.0913] Exact Manual Equivalence : True
nn.Module Subclassing & Parameter Registration β E-Commerce Dynamic Pricing Enginenn.Module to build PricingNet with super().__init__(), registering trainable linear weights via named_parameters() alongside non-trainable running normalization statistics via register_buffer() so both move automatically across CPU/GPU devices.
import torch
import torch.nn as nn
class PricingNet(nn.Module):
"""Real-time SKU price elasticity model with registered normalization buffers."""
def __init__(self, num_features: int, hidden_dim: int):
super().__init__() # Mandatory initialization of internal _parameters & _buffers dicts
self.register_buffer("feature_mean", torch.zeros(num_features))
self.register_buffer("feature_scale", torch.ones(num_features))
self.fc_in = nn.Linear(num_features, hidden_dim)
self.act = nn.SiLU()
self.fc_out = nn.Linear(hidden_dim, 1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x_norm = (x - self.feature_mean) / self.feature_scale
hidden = self.act(self.fc_in(x_norm))
return torch.softplus(self.fc_out(hidden)) # Guarantees strictly positive price multiplier
torch.manual_seed(7)
model = PricingNet(num_features=6, hidden_dim=16)
sku_batch = torch.randn(3, 6)
multipliers = model(sku_batch)
print("Registered Trainable Parameters:")
for name, param in model.named_parameters():
print(f" {name:<15} | shape={str(tuple(param.shape)):<10} | requires_grad={param.requires_grad}")
print("Registered State Buffers:")
for name, buf in model.named_buffers():
print(f" {name:<15} | shape={str(tuple(buf.shape)):<10} | requires_grad={buf.requires_grad}")
print("Predicted Price Multipliers:", [round(v, 4) for v in multipliers.squeeze(-1).tolist()])
Output: Registered Trainable Parameters: fc_in.weight | shape=(16, 6) | requires_grad=True fc_in.bias | shape=(16,) | requires_grad=True fc_out.weight | shape=(1, 16) | requires_grad=True fc_out.bias | shape=(1,) | requires_grad=True Registered State Buffers: feature_mean | shape=(6,) | requires_grad=False feature_scale | shape=(6,) | requires_grad=False Predicted Price Multipliers: [0.6841, 0.7319, 0.6512]
(Batch=4, Seq_Len=32, d_model=128) into an expanded feed-forward hidden space (4, 32, 512), demonstrating how nn.Linear applies the exact same weight matrix independently across every leading batch and sequence position.
import torch
import torch.nn as nn
torch.manual_seed(11)
B, T, D_MODEL, D_FF = 4, 32, 128, 512
# 3D sequence batch: (Batch=4, Seq_Len=32, Embedding_Dim=128)
token_embeddings = torch.randn(B, T, D_MODEL)
# Transformer FFN up-projection operates strictly on the trailing dimension (-1)
ffn_up_proj = nn.Linear(in_features=D_MODEL, out_features=D_FF)
projected_tokens = ffn_up_proj(token_embeddings)
# Verify position-wise independence: projecting token [2, 15] alone matches slice [2, 15]
single_token_out = ffn_up_proj(token_embeddings[2, 15])
batch_slice_out = projected_tokens[2, 15]
print("Input 3D Tensor Shape :", token_embeddings.shape)
print("Projected 3D Tensor Shape :", projected_tokens.shape)
print("Shared Weight Matrix Shape :", ffn_up_proj.weight.shape)
print("Position-Wise Slice Match :", torch.allclose(single_token_out, batch_slice_out, atol=1e-6))
Output: Input 3D Tensor Shape : torch.Size([4, 32, 128]) Projected 3D Tensor Shape : torch.Size([4, 32, 512]) Shared Weight Matrix Shape : torch.Size([512, 128]) Position-Wise Slice Match : True
nn.BatchNorm1d, BatchNorm subtracts the mini-batch mean E[Wx + b] = E[Wx] + b, canceling out the additive bias b completely. Setting bias=False eliminates redundant parameters and memory bandwidth with identical mathematical output.
import torch
import torch.nn as nn
torch.manual_seed(19)
features = torch.randn(32, 256)
# 1. Redundant configuration: Linear(bias=True) followed immediately by BatchNorm1d
block_with_bias = nn.Sequential(
nn.Linear(256, 512, bias=True),
nn.BatchNorm1d(512)
)
# 2. Optimized configuration: Linear(bias=False) shares exact weights, drops 512 redundant bias params
block_no_bias = nn.Sequential(
nn.Linear(256, 512, bias=False),
nn.BatchNorm1d(512)
)
with torch.no_grad():
block_no_bias[0].weight.copy_(block_with_bias[0].weight)
out_with_bias = block_with_bias(features)
out_no_bias = block_no_bias(features)
params_with = sum(p.numel() for p in block_with_bias.parameters())
params_without = sum(p.numel() for p in block_no_bias.parameters())
print(f"Linear(bias=True) + BN Params : {params_with:,}")
print(f"Linear(bias=False) + BN Params : {params_without:,} (Saved {params_with - params_without} redundant params)")
print(f"block_no_bias[0].bias : {block_no_bias[0].bias}")
print(f"Outputs Identical After BN : {torch.allclose(out_with_bias, out_no_bias, atol=1e-5)}")
Output: Linear(bias=True) + BN Params : 132,608 Linear(bias=False) + BN Params : 132,096 (Saved 512 redundant params) block_no_bias[0].bias : None Outputs Identical After BN : True
nn.Sequential) β Fraud Detection Tabular Classifiernn.Sequential to chain Linear -> LayerNorm -> GELU -> Dropout -> Linear cleanly, and tracing intermediate tensor shapes across every stage.
import torch
import torch.nn as nn
torch.manual_seed(33)
# Production tabular fraud scoring head chaining normalization, GELU, and dropout
fraud_pipeline = nn.Sequential(
nn.Linear(24, 64),
nn.LayerNorm(64),
nn.GELU(),
nn.Dropout(p=0.2),
nn.Linear(64, 2) # [Legitimate, Fraudulent]
)
# Trace intermediate shapes through each layer in nn.Sequential
x = torch.randn(16, 24)
print(f"Input Transaction Batch : {tuple(x.shape)}")
for idx, layer in enumerate(fraud_pipeline):
x = layer(x)
print(f" Stage {idx} ({layer.__class__.__name__:<10}) -> {tuple(x.shape)}")
# Switch to .eval() mode to disable Dropout during live inference
fraud_pipeline.eval()
with torch.inference_mode():
probs = torch.softmax(fraud_pipeline(torch.randn(2, 24)), dim=-1)
print("Inference Fraud Probabilities:", [[round(p, 4) for p in row] for row in probs.tolist()])
Output: Input Transaction Batch : (16, 24) Stage 0 (Linear ) -> (16, 64) Stage 1 (LayerNorm ) -> (16, 64) Stage 2 (GELU ) -> (16, 64) Stage 3 (Dropout ) -> (16, 64) Stage 4 (Linear ) -> (16, 2) Inference Fraud Probabilities: [[0.5618, 0.4382], [0.4912, 0.5088]]
nn.ModuleList) β Configurable Depth Recommender Towernn.ModuleList, demonstrating why plain Python list attributes fail to register layer weights with model.parameters() and GPU .to() transfers.
import torch
import torch.nn as nn
class BrokenPythonListTower(nn.Module):
def __init__(self, dims):
super().__init__()
# ANTI-PATTERN: Plain Python list is invisible to PyTorch's parameter tracker!
self.layers = [nn.Linear(dims[i], dims[i + 1]) for i in range(len(dims) - 1)]
class RecommenderTower(nn.Module):
"""Configurable-depth ranking tower with proper nn.ModuleList registration."""
def __init__(self, dims):
super().__init__()
self.blocks = nn.ModuleList([
nn.Sequential(nn.Linear(dims[i], dims[i + 1]), nn.ReLU())
for i in range(len(dims) - 1)
])
self.score_head = nn.Linear(dims[-1], 1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
for block in self.blocks:
x = block(x)
return self.score_head(x)
layer_dims = [64, 128, 64, 32]
broken_model = BrokenPythonListTower(layer_dims)
valid_model = RecommenderTower(layer_dims)
print("Plain Python List Registered Params :", sum(p.numel() for p in broken_model.parameters()))
print("nn.ModuleList Registered Params :", sum(p.numel() for p in valid_model.parameters()))
print("Ranking Output Shape (Batch=8) :", valid_model(torch.randn(8, 64)).shape)
Output: Plain Python List Registered Params : 0 nn.ModuleList Registered Params : 18,689 Ranking Output Shape (Batch=8) : torch.Size([8, 1])
nn.ModuleDict) β Multi-Task Autonomous Driving Perception Head'steering', 'braking', and 'lane_offset') inside nn.ModuleDict so an autonomous driving perception backbone can route shared BEV (Bird's-Eye View) features selectively at runtime.
import torch
import torch.nn as nn
class AutonomousMultiTaskHead(nn.Module):
"""Routes shared perception trunk embeddings into named control heads."""
def __init__(self, trunk_dim: int = 128):
super().__init__()
self.shared_trunk = nn.Sequential(
nn.Linear(trunk_dim, 64),
nn.GELU()
)
# Named dictionary of linear task heads tracked as registered submodules
self.heads = nn.ModuleDict({
"steering": nn.Linear(64, 1), # Continuous steering angle (rad)
"braking": nn.Linear(64, 2), # [No-Brake, Emergency-Brake] logits
"lane_offset": nn.Linear(64, 3) # [Left-Dist, Center-Offset, Right-Dist]
})
def forward(self, bev_features: torch.Tensor, active_tasks=None) -> dict:
shared = self.shared_trunk(bev_features)
tasks = active_tasks if active_tasks is not None else self.heads.keys()
return {task: self.heads[task](shared) for task in tasks}
torch.manual_seed(5)
perception_net = AutonomousMultiTaskHead(trunk_dim=128)
bev_batch = torch.randn(4, 128)
outputs = perception_net(bev_batch, active_tasks=["steering", "braking", "lane_offset"])
for task_name, tensor_out in outputs.items():
print(f"Task '{task_name:<11}' -> Output Shape: {tuple(tensor_out.shape)}")
Output: Task 'steering ' -> Output Shape: (4, 1) Task 'braking ' -> Output Shape: (4, 2) Task 'lane_offset' -> Output Shape: (4, 3)
nn.init) β Deep MLP Signal Propagationstd=0.01, causing vanishing activations) versus Kaiming Normal (designed for ReLU/GELU), Xavier Uniform, and Orthogonal initialization via model.apply().
import torch
import torch.nn as nn
def build_deep_mlp(init_strategy: str) -> nn.Sequential:
layers = []
for _ in range(6):
layers.extend([nn.Linear(256, 256), nn.ReLU()])
net = nn.Sequential(*layers)
def init_weights(m: nn.Module):
if isinstance(m, nn.Linear):
if init_strategy == "naive_small":
nn.init.normal_(m.weight, mean=0.0, std=0.01)
elif init_strategy == "kaiming":
nn.init.kaiming_normal_(m.weight, mode="fan_in", nonlinearity="relu")
elif init_strategy == "xavier":
nn.init.xavier_uniform_(m.weight)
elif init_strategy == "orthogonal":
nn.init.orthogonal_(m.weight, gain=nn.init.calculate_gain("relu"))
nn.init.zeros_(m.bias)
net.apply(init_weights)
return net
torch.manual_seed(101)
x_in = torch.randn(64, 256)
for strategy in ["naive_small", "xavier", "kaiming", "orthogonal"]:
mlp = build_deep_mlp(strategy)
out = mlp(x_in)
print(f"Strategy: {strategy:<12} | Layer-6 Activation Std: {out.std().item():.6f}")
Output: Strategy: naive_small | Layer-6 Activation Std: 0.000000 Strategy: xavier | Layer-6 Activation Std: 0.124819 Strategy: kaiming | Layer-6 Activation Std: 0.987412 Strategy: orthogonal | Layer-6 Activation Std: 1.004185
requires_grad = False across all feature extractor layers, replacing classifier.fc with a fresh trainable nn.Linear head, and passing only unfrozen parameters to the optimizer.
import torch
import torch.nn as nn
class ClinicalEHRModel(nn.Module):
def __init__(self):
super().__init__()
self.backbone = nn.Sequential(
nn.Linear(128, 256),
nn.LayerNorm(256),
nn.GELU(),
nn.Linear(256, 128),
nn.GELU()
)
self.fc = nn.Linear(128, 10) # Original 10-department general head
def forward(self, x):
return self.fc(self.backbone(x))
model = ClinicalEHRModel()
# 1. Freeze all pretrained backbone weights so gradients are neither computed nor stored
for param in model.backbone.parameters():
param.requires_grad = False
# 2. Replace final linear head with a new 4-class Emergency Triage layer (requires_grad=True by default)
model.fc = nn.Linear(128, 4)
# 3. Configure optimizer exclusively over trainable parameters
trainable_params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.AdamW(trainable_params, lr=1e-3)
total_p = sum(p.numel() for p in model.parameters())
train_p = sum(p.numel() for p in trainable_params)
frozen_p = total_p - train_p
print(f"Total Parameters : {total_p:,}")
print(f"Frozen Backbone : {frozen_p:,} ({frozen_p / total_p * 100:.1f}%)")
print(f"Trainable Triage Head: {train_p:,} ({train_p / total_p * 100:.1f}%)")
Output: Total Parameters : 66,948 Frozen Backbone : 66,432 (99.2%) Trainable Triage Head: 516 (0.8%)
state_dict) β Production Model Deployment Checkpointingmodel.state_dict() and load_state_dict(..., strict=True) using an in-memory bufferβthe industry-standard serialization pattern that avoids fragile Python class-pickling dependencies across microservices.
import io
import torch
import torch.nn as nn
torch.manual_seed(88)
def create_serving_model() -> nn.Module:
return nn.Sequential(
nn.Linear(16, 32),
nn.BatchNorm1d(32),
nn.ReLU(),
nn.Linear(32, 3)
)
# 1. Train / run forward pass on source model to populate weights & BatchNorm running stats
trained_model = create_serving_model()
_ = trained_model(torch.randn(8, 16))
# 2. Serialize state_dict (ordered dictionary mapping layer keys -> parameter/buffer tensors)
checkpoint_buffer = io.BytesIO()
torch.save(trained_model.state_dict(), checkpoint_buffer)
checkpoint_bytes = checkpoint_buffer.tell()
# 3. Reconstruct model in inference microservice and load weights with strict=True validation
checkpoint_buffer.seek(0)
loaded_state = torch.load(checkpoint_buffer, weights_only=True)
serving_model = create_serving_model()
status = serving_model.load_state_dict(loaded_state, strict=True)
serving_model.eval()
print(f"Serialized Checkpoint Size : {checkpoint_bytes:,} bytes")
print(f"Load Verification Status : {status}")
print("State Dict Tensor Manifest :")
for key, tensor in loaded_state.items():
print(f" {key:<22} | shape={str(tuple(tensor.shape)):<10} | dtype={tensor.dtype}")
Output: Serialized Checkpoint Size : 6,294 bytes Load Verification Status : <All keys matched successfully> State Dict Tensor Manifest : 0.weight | shape=(32, 16) | dtype=torch.float32 0.bias | shape=(32,) | dtype=torch.float32 1.weight | shape=(32,) | dtype=torch.float32 1.bias | shape=(32,) | dtype=torch.float32 1.running_mean | shape=(32,) | dtype=torch.float32 1.running_var | shape=(32,) | dtype=torch.float32 1.num_batches_tracked | shape=() | dtype=torch.int64 3.weight | shape=(3, 32) | dtype=torch.float32 3.bias | shape=(3,) | dtype=torch.float32