Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added safetensors support in from_pretrained() #62

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions src/transformers_neuronx/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import warnings

import torch
from safetensors import safe_open
from torch.nn.parameter import UninitializedParameter
from transformers import AutoConfig

Expand Down Expand Up @@ -137,16 +138,32 @@ class LowMemoryLazyLinear(torch.nn.LazyLinear, LowMemoryModule): ...

class PretrainedModel(LowMemoryModule):

@staticmethod
def _safeload(state_dict_path):
state_dict = {}
with safe_open(state_dict_path, framework="pt") as f:
for k in f.keys():
state_dict[k] = f.get_tensor(k)
return state_dict

@classmethod
def from_pretrained(cls, pretrained_model_path, *model_args, **kwargs):
config = AutoConfig.from_pretrained(pretrained_model_path)
model = cls(config, *model_args, **kwargs)
state_dict_path = os.path.join(pretrained_model_path, 'pytorch_model.bin')
if os.path.isdir(state_dict_path):
state_dict_safetensor_path = os.path.join(pretrained_model_path, 'model.safetensors')

if os.path.isfile(state_dict_safetensor_path):
state_dict = PretrainedModel._safeload(state_dict_safetensor_path)
model.load_state_dict_low_memory(state_dict)
elif os.path.isdir(state_dict_path):
model.load_state_dict_dir(state_dict_path)
else:
elif os.path.isfile(state_dict_path):
state_dict = torch.load(state_dict_path)
model.load_state_dict_low_memory(state_dict)
else:
raise FileNotFoundError(f"Can not find model.safetensors or pytorch_model.bin in {pretrained_model_path}")

return model


Expand All @@ -160,4 +177,4 @@ def load_state_dict_dir(self, state_dict_dir):
self.chkpt_model.load_state_dict_dir(state_dict_dir)

def load_state_dict_low_memory(self, state_dict):
self.chkpt_model.load_state_dict_low_memory(state_dict)
self.chkpt_model.load_state_dict_low_memory(state_dict)