v9.1.1
Menu

Extract and Inspect State Dict

easyFREEModel SerializationPyTorch Advanced

Problem Statement

Extract a model's state dictionary and inspect its contents.

Background

model.state_dict() returns an OrderedDict mapping parameter names to tensors. This is the standard way to save and inspect model weights.

Your Task

The starter code creates a model with named layers. Extract the model's state dictionary to inspect its parameter names and shapes.

The inspection code (listing keys, shapes) is pre-filled.

Output Format

Returns a dictionary with "keys", "num_params", "fc1_weight_shape", and "fc2_bias_shape".

Example

Input
None
Output
{'keys': ['fc1.weight', 'fc1.bias', 'fc2.weight', 'fc2.bias'], 'num_params': 4, 'fc1_weight_shape': [8, 4], 'fc2_bias_shape': [2]}
Reasoning
  • Input: the function takes no arguments. It builds a two-layer network: fc1 maps 4 features to 8, then fc2 maps 8 features to 2.
  • Math: a fully connected layer from ninn_{in} to noutn_{out} features computes y=Wx+by = Wx + b, with W∈Rnout×ninW \in \mathbb{R}^{n_{out} \times n_{in}} and b∈Rnoutb \in \mathbb{R}^{n_{out}}. So fc1 holds an 8×48 \times 4 weight and an 8-vector bias, and fc2 holds a 2×82 \times 8 weight and a 2-vector bias.
  • Keys: each learnable tensor is named layer name, a dot, then its role. In the order the layers were added, that gives ['fc1.weight', 'fc1.bias', 'fc2.weight', 'fc2.bias'].
  • Output: num_params is 4 because it counts tensors, not scalars. The scalar count would be 32+8+16+2=5832 + 8 + 16 + 2 = 58. fc1_weight_shape is [8, 4] and fc2_bias_shape is [2].
  • Notice: the weight shape is (outputs, inputs), not (inputs, outputs), which is why fc1 reads [8, 4] and not [4,8][4, 8]. The random seed changes only the values inside the tensors. The names and shapes stay the same.

Constraints

  • Use model.state_dict()
  • Inspect keys and shapes
  • Use named modules

Learn this in

More from PyTorch Advanced

solution.py

Test results

Sign in to run your code against the test cases.