import torch
def convert_state_dict(old_state_dict, name_mapping):
"""
Convert a PyTorch state_dict with old naming conventions to new naming conventions.
Parameters:
- old_state_dict (dict): The original state dict with old naming conventions.
- name_mapping (dict): A dictionary where keys are old names and values are new names.
Returns:
- new_state_dict (dict): A state dict with updated names.
"""
new_state_dict = {}
for old_name, value in old_state_dict.items():
# Use get() to fall back to the original name if not found in name_mapping
new_name = name_mapping.get(old_name, old_name)
new_state_dict[new_name] = value
return new_state_dict
# Example usage
old_state_dict = {
"fc1.weight": torch.rand(64, 256),
"fc1.bias": torch.rand(64),
"conv1.weight": torch.rand(64, 3, 3, 3),
# Add other parameters
}
# Define a mapping from old parameter names to new names
name_mapping = {
"fc1.weight": "layer1.weight",
"fc1.bias": "layer1.bias",
"conv1.weight": "conv_layer1.weight",
# Add other mappings as necessary
}
new_state_dict = convert_state_dict(old_state_dict, name_mapping)
# Display new state dict
for key in new_state_dict:
print(key)