MCPcopy Create free account
hub / github.com/modelscope/modelscope / _load_checkpoint

Function _load_checkpoint

modelscope/utils/checkpoint.py:278–485  ·  view source on GitHub ↗
(
        model,
        state_dict,
        load_state_fn,
        ignore_mismatched_sizes,
        _fast_init,
    )

Source from the content-addressed store, hash-verified

276 return error_msgs
277
278 def _load_checkpoint(
279 model,
280 state_dict,
281 load_state_fn,
282 ignore_mismatched_sizes,
283 _fast_init,
284 ):
285 # Retrieve missing & unexpected_keys
286 model_state_dict = model.state_dict()
287 expected_keys = list(model_state_dict.keys())
288 keys_from_pretrained = list(state_dict.keys())
289
290 prefix = model.base_model_prefix
291
292 # during loading stage, base model prefix is complicated, should consider remove or add
293 if len(prefix) > 0:
294 # nlp: encoder, decoder
295 pretrained_has_prefix_module = any(
296 s.startswith(prefix) for s in keys_from_pretrained)
297 model_expects_prefix_module = any(
298 s.startswith(prefix) for s in expected_keys)
299 else:
300 # nlp:encoder-decoder, cv:backbone-head,
301 pretrained_has_prefix_module = False
302 model_expects_prefix_module = False
303
304 remove_prefix_from_model = not pretrained_has_prefix_module and model_expects_prefix_module
305 add_prefix_to_model = pretrained_has_prefix_module and not model_expects_prefix_module
306
307 if remove_prefix_from_model:
308 expected_keys_not_base_model_prefixed = [
309 s for s in expected_keys if not s.startswith(prefix)
310 ]
311 expected_keys = [
312 '.'.join(s.split('.')[1:]) if s.startswith(prefix) else s
313 for s in expected_keys
314 ]
315 elif add_prefix_to_model:
316 # backbone only
317 expected_keys = ['.'.join([prefix, s]) for s in expected_keys]
318 expected_keys_not_base_model_prefixed = []
319
320 missing_keys = list(set(expected_keys) - set(keys_from_pretrained))
321 unexpected_keys = list(set(keys_from_pretrained) - set(expected_keys))
322
323 # during loading stage head prefix is simple, add or not add
324 prefix_heads = model.head_prefix
325 expected_head_keys_without_head_prefix = []
326 missing_head_keys = []
327 unexpected_head_keys = []
328 pretrained_has_prefix_head = dict()
329 head_prefix_keys = dict()
330
331 # only for case of head mismatched with state-dict
332 if len(prefix_heads) > 0 and len(unexpected_keys) > 0:
333 if isinstance(prefix_heads, str):
334 prefix_heads = [prefix_heads]
335

Callers 1

Calls 10

_find_mismatched_keysFunction · 0.85
infoMethod · 0.80
state_dictMethod · 0.45
keysMethod · 0.45
extendMethod · 0.45
searchMethod · 0.45
_init_weightsMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…