📘
Extract and Inspect State Dict
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:
- The function
state_dict_test()starts by seeding withtorch.manual_seed(42)to ensure reproducibility. - It then creates an
nn.Sequentialmodel with two named modules:"fc1"(nn.Linear(4, 8)) and"fc2"(nn.Linear(8, 2)), resulting in four parameter tensors:fc1.weight,fc1.bias,fc2.weight, andfc2.bias. - The state dictionary is extracted using
model.state_dict(), which returns an OrderedDict containing these four parameter tensors, leading to the list of keys:['fc1.weight', 'fc1.bias', 'fc2.weight', 'fc2.bias']. - The shapes of
fc1.weightandfc2.biasare determined by thenn.Linearlayers:fc1.weighthas shape [8,4] (8 outputs, 4 inputs) andfc2.biashas shape [2] (2 outputs), resulting in the output dictionary with the specified values.
Constraints:
- Use model.state_dict()
- Inspect keys and shapes
- Use named modules
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.