Error(s) in loading state_dict for model: Missing Key(s) in state_dict: "xxxx", Unexpected Key(s) in state_dict: "aa.xxxx"

2024. 3. 15. 14:09·Error
반응형

 문제

pretrained weight를 불러와 모델에 올릴 때 parameter name이 달라서 오류 발생

model = Model()

model.load_state_dict(torch.load('pretrained_weight.pth'))

 

오류 메시지

RuntimeError: Error(s) in loading state_dict for Model:
	Missing key(s) in state_dict: "backbone.conv1.weight", "backbone.bn1.weight", ... ,
   	Unexpected key(s) in state_dict: "module.backbone.conv1.weight", "module.backbone.bn1.weight", ...

 

 

해결

모델의 parameter name과 saved parameter name을 동일하게 변경

from collections import OrderedDict
new_state_dict = OrderedDict()

state_dict = torch.load('pretrained_weight.pth')

for k, v in state_dict.items():
    name = k[7:] # remove `module.`
    new_state_dict[name] = v

model.load_state_dict(new_state_dict)

 

저장된 parameter name의 'module.' 에 해당하는 부분을 삭제 하는 코드이다. 일반적으로 사용할 수 있는 코드는 아님.

반응형

'Error' 카테고리의 다른 글

cs231n [collectSubmission.sh/makepdf.py] FileNotFoundError: [Errno 2] No such file or directory: 'knn.pdf'  (0) 2024.12.12
RuntimeError: CUDA error: out of memoryCUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.For debugging consider passing CUDA_LAUNCH_BLOCKING=1.Compile with `TORCH_USE_CUDA_DSA` to enab..  (0) 2024.03.11
The remote host may not meet VS Code Server's prerequisites for glibc and libstdc++  (0) 2024.02.11
'Error' 카테고리의 다른 글
  • cs231n [collectSubmission.sh/makepdf.py] FileNotFoundError: [Errno 2] No such file or directory: 'knn.pdf'
  • RuntimeError: CUDA error: out of memoryCUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.For debugging consider passing CUDA_LAUNCH_BLOCKING=1.Compile with `TORCH_USE_CUDA_DSA` to enab..
  • The remote host may not meet VS Code Server's prerequisites for glibc and libstdc++
hangyuwon
hangyuwon
  • hangyuwon
    191
    hangyuwon
  • 전체
    오늘
    어제
  • 글쓰기 관리
    • 분류 전체보기 (38)
      • 기타 (1)
      • Stanford CS231n (19)
      • 논문 리뷰 (5)
      • Error (4)
      • 알고리즘 (2)
      • Linux (1)
      • 잡동사니 (2)
      • 딥러닝 (4)
  • 인기 글

  • 태그

    알고리즘
    error
    논문 리뷰
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
hangyuwon
Error(s) in loading state_dict for model: Missing Key(s) in state_dict: "xxxx", Unexpected Key(s) in state_dict: "aa.xxxx"
상단으로

티스토리툴바