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




