Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sort state_dict.keys() in _strip_prefix_if_present? #136

Open
isdanni opened this issue Sep 10, 2023 · 0 comments
Open

Sort state_dict.keys() in _strip_prefix_if_present? #136

isdanni opened this issue Sep 10, 2023 · 0 comments

Comments

@isdanni
Copy link

isdanni commented Sep 10, 2023

keys = sorted(state_dict.keys())

Was wondering why sorting the state_dict.keys() here when it is already a SortedDict? This will obviously change the order of the state_dict keys.

Example:

from collections import OrderedDict

state_dict = OrderedDict()
state_dict['module.body.stage1.0.0.weight'] = 0
state_dict['module.body.stage1.0.1.weight'] = 1
state_dict['module.body.stage1.0.1.bias'] = 2
state_dict['module.bboxes.0.conv1x1.weight'] = 3
state_dict['module.bboxes.0.conv1x1.bias'] = 4

keys_og = state_dict.keys()
"""
['module.body.stage1.0.0.weight', 'module.body.stage1.0.1.weight', 'module.body.stage1.0.1.bias', 'module.bboxes.0.conv1x1.weight', 'module.bboxes.0.conv1x1.bias']
"""
keys = sorted(state_dict.keys())
"""
['module.bboxes.0.conv1x1.bias', 'module.bboxes.0.conv1x1.weight', 'module.body.stage1.0.0.weight', 'module.body.stage1.0.1.bias', 'module.body.stage1.0.1.weight']
"""

prefix = "module."

for key in keys_og:
    if key.startswith(prefix):
        newkey = key[len(prefix) :]
        state_dict[newkey] = state_dict.pop(key)

"""
With sorting: 
OrderedDict([('bboxes.0.conv1x1.bias', 4), ('bboxes.0.conv1x1.weight', 3), ('body.stage1.0.0.weight', 0), ('body.stage1.0.1.bias', 2), ('body.stage1.0.1.weight', 1)])

Without sorting:
OrderedDict([('body.stage1.0.0.weight', 0), ('body.stage1.0.1.weight', 1), ('body.stage1.0.1.bias', 2), ('bboxes.0.conv1x1.weight', 3), ('bboxes.0.conv1x1.bias', 4)])
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant