nur-dev's picture
Add reviewer-requested controlled and sensor mechanism tests
e7a0400 verified
Raw History Blame Contribute Delete
1.66 kB
"""Lossless non-executable Safetensors + JSON tensor-tree serialization."""
from pathlib import Path
import json,math
import torch
from safetensors.torch import save_file,load_file
def save_tree(value, base):
base=Path(base);tensors={}
def walk(x):
if torch.is_tensor(x):
key=f't{len(tensors):06d}';tensors[key]=x.detach().contiguous().cpu().clone();return {'tensor':key}
if isinstance(x,dict):return {'dict':[[walk(k),walk(v)] for k,v in x.items()]}
if isinstance(x,(tuple,list)):return {'tuple' if isinstance(x,tuple) else 'list':[walk(v) for v in x]}
if isinstance(x,float) and not math.isfinite(x):return {'float':str(x)}
assert x is None or isinstance(x,(str,int,float,bool)),type(x)
return x
tree=walk(value);base.parent.mkdir(parents=True,exist_ok=True)
save_file(tensors,str(base.with_suffix('.safetensors')),metadata={'format':'lossless-tree-v1','checkpoint':'no-executable-pickle'})
base.with_suffix('.json').write_text(json.dumps(tree,separators=(',',':'),allow_nan=False)+'\n')
def load_tree(base, device):
base=Path(base).with_suffix('');tensors=load_file(str(base.with_suffix('.safetensors')),device=device)
def walk(x):
if not isinstance(x,dict):return x
if 'tensor' in x:return tensors[x['tensor']]
if 'dict' in x:return {walk(k):walk(v) for k,v in x['dict']}
if 'tuple' in x:return tuple(walk(v) for v in x['tuple'])
if 'list' in x:return [walk(v) for v in x['list']]
if 'float' in x:return float(x['float'])
raise ValueError(x)
return walk(json.loads(base.with_suffix('.json').read_text()))