(input_dir: str)
| 80 | |
| 81 | |
| 82 | def 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 | |
| 118 | def get_mapped_key(key: str, mapping_dict: Dict[str, str]) -> str: |
no test coverage detected