模型权重文件
		常见的权重文件格式(如 .bin、.safetensors、.pt 等)的保存和加载方法:
| 文件类型 | 保存方法 | 加载方法 | 描述 | 
|---|---|---|---|
| .bin | torch.save(model.state_dict(), ‘model.bin’) | state_dict = torch.load(‘model.bin’, map_location=’cpu’)  model.load_state_dict(state_dict) | .bin文件通常存储state_dict,仅保存模型的权重。需要先加载state_dict,然后用model.load_state_dict加载到模型。 | 
| .pt /.pth | torch.save(model.state_dict(), ‘model.pth’) | state_dict = torch.load(‘model.pth’, map_location=’cpu’)  model.load_state_dict(state_dict) | .pt/.pth文件是 PyTorch 中常见的保存权重格式,保存的是模型的state_dict。加载方式和.bin文件相同。 | 
| .pt(完整模型) | torch.save(model, ‘model.pth’) | model = torch.load(‘model.pth’, map_location=’cpu’) | 保存的是整个模型对象(包括结构和权重)。加载时会直接返回模型,无需再用 load_state_dict。 | 
| .safetensors | from safetensors import save_file  save_file(tensors, ‘model.safetensors’) | from safetensors import load_file  state_dict = load_file(‘model.safetensors’) model.load_state_dict(state_dict) | .safetensors是一种新型格式,专门用于安全和高效地保存模型权重。保存和加载都需要safetensors库。 | 
| Hugging Face .bin | model.save_pretrained(‘path_to_model’) | from transformers import AutoModel  model = AutoModel.from_pretrained(‘path_to_model’) | Hugging Face 的 .bin通常用于保存预训练模型的权重,带有额外的配置文件(如config.json)。AutoModel会自动处理加载。 | 
| .h5(Keras/TensorFlow) | model.save_weights(‘model.h5’) | model.load_weights(‘model.h5’) | Keras 和 TensorFlow 使用 .h5文件格式保存模型权重。适用于 TensorFlow/Keras 环境。 | 
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 JrunDing!
 评论
