Buckets:
| import os | |
| import json | |
| import torch | |
| class ModelMerge(): | |
| def __init__(self, chunks_dir: str): | |
| self.chunks_dir = chunks_dir | |
| def _load_chunks(self): | |
| """ | |
| load model chunks | |
| """ | |
| chunks = {} | |
| for file_name in os.listdir(self.chunks_dir): | |
| if file_name.startswith("pytorch_model-") and file_name.endswith(".bin"): | |
| chunk_path = os.path.join(self.chunks_dir, file_name) | |
| chunk = torch.load(chunk_path, map_location="cpu") | |
| chunks[file_name] = chunk | |
| return chunks | |
| def _merge_state_dict(self, chunks, index_path): | |
| """ | |
| merge state dict according to index | |
| :param chunks: chunk dict | |
| :param index_path: path of index | |
| :return: merged model | |
| """ | |
| with open(index_path, "r") as f: | |
| index = json.load(f) | |
| merged_state_dict = {} | |
| for chunk_name, keys in index.items(): | |
| if chunk_name in chunks: | |
| chunk = chunks[chunk_name] | |
| for key in keys: | |
| merged_state_dict[key] = chunk[key] | |
| return merged_state_dict | |
| def _save_model(self, merged_state_dict, output_path): | |
| """ | |
| save the merged model | |
| :param merged_state_dict: merged model | |
| :param output_path | |
| """ | |
| torch.save(merged_state_dict, output_path) | |
| print(f"Merged model: {output_path}") | |
| def merge(self): | |
| """ | |
| Merge chunks & save the model | |
| """ | |
| # Load chunks | |
| print("Loading chunks...") | |
| chunks = self._load_chunks() | |
| # Merge chunks | |
| print("Merging chunks...") | |
| merged_state_dict = self._merge_state_dict(chunks, \ | |
| os.path.join(self.chunks_dir, "pytorch_model.bin.index.json")) | |
| # Save merged model | |
| print("Saving merged model...") | |
| self._save_model(merged_state_dict, os.path.join(self.chunks_dir, "pytorch_model.bin")) | |
| print("Done!") | |
| if __name__ == "__main__": | |
| tool = ModelMerge(chunks_dir="./") | |
| tool.merge() |
Xet Storage Details
- Size:
- 2.12 kB
- Xet hash:
- eb390f31a23ac078a863b71b8f90cc1531597b8107dc662caec1ca7bb88f33df
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.