7 routes42 sections324 units

Unit 2.3 · about 4 h

179 / 324

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.

  • explain
  • implement

You can now

  • 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 registration
  • Functional versus module APIs
  • Explicit initialization and state_dict semantics

Study, in this order

3 steps

  1. Build the Neural Network: class, layers, parameters
    PyTorch - 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, initialization
    PyTorch - 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_)

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

  3. Extending `torch.nn`: the module recommendation and the `Linear` example
    PyTorch - 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)

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

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_.

Reproduce closed-book

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.

Traps

  • 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.

Practice

Learn PyTorch 01: nn.Module with Parameters, then save and reload (tasks 2 and 5)

Exercises, task 2 (nn.Module subclass with nn.Parameter weight and bias, state_dict check) and task 5 (save state_dict, reload into a new instance, verify predictions match)

Implement in your own script. The prediction check must compare outputs, not just file existence.

Self-test

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

  2. Why does load_state_dict need a constructed model first?

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

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

Completion criterion

Stop when

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

Mark passed, then open 2.4 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

  • PyTorch - Learn the Basics
    PyTorchprimarycourse
    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 reproducibility
    PyTorchrequiredreference
    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 exercises
    Daniel Bourkerequiredpractice
    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 foundations
    Howard Huang, Luca Antiga, Eli Stevens and Thomas Viehmann (Manning)supportimplementation
    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 drills
    NeetCodeoptionalpractice
    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/Resuming
    PyTorchreferencereference
    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 PyTorch
    Aurelien Geron (O'Reilly, 2025)supporttheory
    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.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels