Unit 3 of 8 · about 4 hours · explain, implement

Modules, parameters, buffers and initialization

Parameters, buffers and init are the state you own for the rest of the stage. Confusing them turns every later resume, transfer and device bug into a mystery.

You'll be able to

  • Assemble nested modules and read ownership from dotted names in named_parameters.
  • Separate Parameters, persistent buffers and non-persistent buffers, and predict exactly which names appear in state_dict.
  • Replace default initialization explicitly, and reload saved state into a fresh instance.

Covers

nn.Module, Parameter, buffers and nested registrationFunctional versus module APIsExplicit initialization and state_dict semantics
1

Read

In this order, only the parts listed

0 of 3 done

  1. Build the Neural Network: class, layers, parametersPyTorch - Learn the Basics

    Define the Class (nn.Module subclass, forward, never call model.forward() directly); Model Layers (Flatten, Linear, ReLU, Sequential, Softmax); Model Parameters (named_parameters with dotted names)

  2. Modules note: nesting, state, buffers, initializationPyTorch - Autograd mechanics, serialization and reproducibility

    A Simple Custom Module; Modules as Building Blocks (children, recursion, ModuleList and ModuleDict, to(), apply() with xavier init); Module State (parameters, persistent and non-persistent buffers, StatefulModule key list); Module Initialization (skip_init with orthogonal_)

    Skip Module Hooks and Advanced Features; they belong to later profiling and distributed work.

  3. Extending torch.nn: the module recommendation and the Linear examplePyTorch - Autograd mechanics, serialization and reproducibility

    Extending torch.nn intro (modules for stateful layers, functional form for parameter-less ops); Adding a Module (nn.Parameter, register_parameter, register_buffer, nn.init.uniform_ comments)

    Read only the Adding a Module part here; the autograd Function part belongs to the custom-autograd unit.

2

Focus on

  • Assigning nn.Parameter registers; assigning a plain Tensor does not. Registration is what parameters(), .to() and optimizers see.
  • Persistent buffers ship in state_dict, non-persistent ones do not, but .to() moves both.
  • state_dict maps dotted names to tensors only. Reloading needs a matching live instance first; mismatched names fail unless explicitly allowed.
  • Default init runs at construction. To study init, skip it with skip_init and apply one nn.init function yourself, as the Modules note does with orthogonal_.
Common mistakes · 3
  • Expecting a plain-Tensor attribute to train. Only Parameters and their submodules appear in parameters().
  • Saving the model object instead of its state_dict. Pickle then binds the file to the class definition; state_dict plus code reloads cleanly.
  • Copying the Extending example uniform(-0.1, 0.1) init into real work. It ignores fan-in; use a fan-aware nn.init function or skip_init plus your own.
3

Try it yourself

Closed-book, before checking anything

Closed-book, write a two-layer Net with a Linear submodule, a persistent running-mean buffer and a ParameterList. Predict the state_dict keys, save, reload into a fresh instance, and assert the buffer matches.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Which names appear in StatefulModule state_dict, and which entries are absent?Answer

    param1, param2, buffer1, the param_list and param_dict entries, linear.weight and linear.bias appear. The non-persistent buffer2 and the reserved None entries param3 and buffer3 are absent.

  2. 2.Why does load_state_dict need a constructed model first?Answer

    The dict holds tensors under names, not the module graph. The instance supplies the structure the names attach to.

  3. 3.A BatchNorm layer updates statistics in train mode and freezes them in eval mode. Where do those statistics live?Answer

    In persistent buffers. They are saved in state_dict and moved by .to(), but never given to the optimizer.

  4. 4.What does module.apply(init_weights) give you that a loop over named_parameters does not?Answer

    apply calls the function on every submodule and then on the module itself, so one function with an isinstance check can initialize each layer type its own way. A named_parameters loop sees only names and tensors, not the layer each one belongs to.

5

Practice

You're done when

Your predicted key list matches the printed state_dict before you print it, and the reloaded instance reproduces predictions exactly.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 5 more in the section
  • PyTorch - Learn the BasicsPyTorch · primary

    Complete Tensors, Datasets and DataLoaders, Transforms, Build Model, Autograd, Optimization, and Save and Load Model. Rebuild each essential example in a small src package instead of retaining a tutorial notebook.

  • PyTorch - Autograd mechanics, serialization and reproducibilityPyTorch · required

    Read Autograd mechanics, Serialization semantics and Reproducibility. Test leaf behavior, saved tensors, grad modes, state dictionaries and the exact tolerance promised by one interrupted and resumed run.

Also in this section

  • Learn PyTorch - selected framework exercisesDaniel Bourke · required

    Complete exercise 00, tasks 1-5 in 01, tasks 1-7 in 02, tasks 5-13 in 03, tasks 1-3 in 05, and exercises 1-2 in 07. Recreate solutions independently and verify behavior against current official docs.

  • Deep Learning with PyTorch, 2nd edition - framework foundationsHoward Huang, Luca Antiga, Eli Stevens and Thomas Viehmann (Manning) · support

    Read Sections 3.8-3.9 and 5.5 when tensor storage, strides or autograd need a second explanation, with the Chapter 3 and 5 companion notebooks for runnable cells. Inspect the Chapter 4 and 7 code only for a diagnosed data-representation or loading gap.

  • NeetCode ML - PyTorch closing drillsNeetCode · optional

    After the module gate, solve Pytorch Basics, Layer Normalization, Batch Normalization and RMS Normalization cold. Explain shapes, state and train-evaluation behavior aloud. These do not replace the package and resume test.

  • PyTorch Automatic Mixed Precision recipe - Saving/ResumingPyTorch · reference

    Read the Saving/Resuming section: save scaler.state_dict() with the model and optimizer state, at the start of an iteration or after scaler.update(), and how to resume with or without AMP.

  • Hands-On Machine Learning with Scikit-Learn and PyTorchAurelien Geron (O'Reilly, 2025) · support

    Read Chapter 10, Implementing Mini-Batch Gradient Descent Using DataLoaders and Model Evaluation, for the train and evaluate loops and how batch metrics must be aggregated.