from d2l import jax as d2l
from flax import linen as nn
import jax
from jax import numpy as jnpA neural network is a tree of parameters — the weight matrices and bias vectors gradient descent updates. Training is one thing you do with them; this deck covers the others.
A nested module is just a tree. Each module is a node; each parameter is a leaf:
net (Sequential)
├─ 0: Linear ├─ weight (8, 4)
│ └─ bias (8,)
├─ 1: ReLU (no params)
└─ 2: Linear ├─ weight (1, 8)
└─ bias (1,)
Two access patterns:
net[2].weight — direct.Frameworks give you both, plus serialization built on the same traversal.
Index into a Sequential like a list; each layer exposes its parameters as attributes:
{'kernel': Array([[ 0.39065108],
[-0.47905394],
[ 0.17323323],
[ 0.22871736],
[ 0.46032798],
[-0.22263312],
[ 0.19490093],
[-0.21752292]], dtype=float32),
'bias': Array([0.], dtype=float32)}
Two parameters per Linear layer — weight matrix and bias vector. The output object is a Parameter (PyTorch) or similar wrapper that carries the tensor + gradient + extra metadata.
.data (PyTorch) unwraps the parameter to a plain tensor for inspection:
(jaxlib._jax.ArrayImpl, Array([0.], dtype=float32))
.grad is the gradient buffer — populated by backward(), otherwise None. Useful for custom optimizers or diagnosing dead neurons:
For everything-at-once, use named_parameters(). It walks the whole tree and yields (name, param) pairs at the leaves — names use dotted paths through the nesting:
{'params': {'layers_0': {'bias': (8,), 'kernel': (4, 8)},
'layers_2': {'bias': (1,), 'kernel': (8, 1)}}}
This is the iterator optim.SGD(net.parameters(), …) consumes. It’s also what gets pickled when you save a checkpoint with state_dict(). Walk-tree-once, use many ways.
Reuse the same module instance at multiple positions in your architecture, and the framework treats them as one parameter set — same memory, gradients accumulate across uses.
Common cases:
# We need to give the shared layer a name so that we can refer to its
# parameters
shared = nn.Dense(8)
net = nn.Sequential([nn.Dense(8), nn.relu,
shared, nn.relu,
shared, nn.relu,
nn.Dense(1)])
params = net.init(d2l.get_key(), X)
# Check whether the parameters are different
print(len(params['params']) == 3)True
Modify net[2].weight and net[4].weight reflects the same change — they are the same tensor, not just equal.
net[i].weight, .bias, .grad.named_parameters() / state_dict() walks the whole tree.