MCPcopy Create free account
hub / github.com/pytorch/executorch / load_checkpoint_from_pytorch_model

Function load_checkpoint_from_pytorch_model

examples/models/checkpoint.py:82–115  ·  view source on GitHub ↗
(input_dir: str)

Source from the content-addressed store, hash-verified

80
81
82def load_checkpoint_from_pytorch_model(input_dir: str) -> Dict:
83 index_path = os.path.join(input_dir, "pytorch_model.bin.index.json")
84 if os.path.exists(index_path):
85 # Sharded checkpoint.
86 with open(index_path, "r") as f:
87 index = json.load(f)
88 weight_map = index["weight_map"]
89 checkpoint_shards = sorted(set(weight_map.values()))
90
91 # Load all the shards into memory
92 shard_to_weights = {}
93 for shard in checkpoint_shards:
94 shard_to_weights[shard] = torch.load(
95 os.path.join(input_dir, shard),
96 weights_only=True,
97 map_location=torch.device("cpu"),
98 )
99
100 # Merge tensors into consolidated state dict.
101 merged_state_dict = {}
102 for weight_name, shard in weight_map.items():
103 tensor = shard_to_weights[shard][weight_name]
104 merged_state_dict[weight_name] = tensor
105 return merged_state_dict
106
107 # Single checkpoint
108 model_path = os.path.join(input_dir, "pytorch_model.bin")
109 if os.path.exists(model_path):
110 state_dict = torch.load(
111 model_path, weights_only=True, map_location=torch.device("cpu")
112 )
113 return state_dict
114
115 raise FileNotFoundError(f"Could not find pytorch_model checkpoint in {input_dir}")
116
117
118def get_mapped_key(key: str, mapping_dict: Dict[str, str]) -> str:

Callers 3

load_checkpointFunction · 0.90
load_checkpointFunction · 0.90
convert_weightsFunction · 0.90

Calls 4

valuesMethod · 0.80
deviceMethod · 0.80
itemsMethod · 0.80
loadMethod · 0.45

Tested by

no test coverage detected