liveBook · Manning

Torch.nn.Module

As explained in Deep Learning with R, Third Edition

torch.nn.Module is PyTorch's base class for building objects that represent neural-network modules and manage their parameters.

torch.nn.Module packages a neural-network computation with its trainable state. Define Parameters in __init__(), implement the forward pass in forward(), and call the model on inputs rather than invoking forward() directly. section 3.4.2

A linear model

LinearModel(torch$nn$Module) %py_class% { `__init__` <- function(self) { super()$`__init__`() self$W <- torch$nn$Parameter(torch$rand(input_dim, output_dim)) self$b <- torch$nn$Parameter(torch$zeros(output_dim)) } forward <- function(self, inputs) { torch$matmul(inputs, self$W) + self$b } } model <- LinearModel() output <- model(torch_inputs)

The Module-based training workflow delegates parameter management and update mechanics to PyTorch:

  • Call model(inputs) instead of model$forward(inputs), allowing __call__() to redirect the call and add framework hooks. section 3.4.2

How Deep Learning with R, Third Edition covers it

How deep it goes
Defines subclass structure, invocation, optimizer integration, training steps, and gradient resetting, but not Module internals.
Examples
Demonstrates a linear classifier with weight and bias Parameters, matrix multiplication, loss backpropagation, SGD, and gradient clearing.
What it assumes
Assumes basic tensors and operations while teaching Parameters, gradients, Module structure, and optimizer use.
What you can do after
Build a trainable PyTorch model and operate its optimizer-driven training loop.
How it connects
Connects Parameters, forward propagation, automatic differentiation, optimizers, and compilation.

Also explained in

Compare how 5 books explain torch.nn.Module →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with R, Third Edition. The section links point to the parts of the book it draws on.