File size: 1,818 Bytes
7b6f2cc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | """Integrity-checked frozen-prefix cache reusable across decoder architecture ablations."""
import hashlib,json,os
from pathlib import Path
from safetensors.torch import load_file,save_file
def identity(row,base_sha256,first_layer,implementation_sha256):
return dict(format_version=1,row_sha256=hashlib.sha256(json.dumps(row,sort_keys=True,ensure_ascii=False).encode()).hexdigest(),base_sha256=base_sha256,first_layer=first_layer,implementation_sha256=implementation_sha256)
def key(config):return hashlib.sha256(json.dumps(config,sort_keys=True).encode()).hexdigest()
def load(directory,config):
stem=Path(directory)/key(config);metadata=stem.with_suffix('.json');tensor=stem.with_suffix('.safetensors')
if not metadata.exists():return None
saved=json.loads(metadata.read_text())
if saved['identity']!=config:raise ValueError('Prefix-cache identity differs')
if hashlib.sha256(tensor.read_bytes()).hexdigest()!=saved['tensor_sha256']:raise ValueError('Prefix-cache tensor checksum mismatch')
result=load_file(str(tensor));result.setdefault('mask',None);return result
def save(directory,config,cache):
directory=Path(directory);directory.mkdir(parents=True,exist_ok=True);stem=directory/key(config);tensor=stem.with_suffix('.safetensors')
temporary=tensor.with_suffix('.part');save_file({k:v.contiguous() for k,v in cache.items() if k in ['hidden','mask','labels'] and v is not None},str(temporary))
with temporary.open('rb') as f:os.fsync(f.fileno())
os.replace(temporary,tensor)
metadata=dict(identity=config,tensor_sha256=hashlib.sha256(tensor.read_bytes()).hexdigest())
temporary=stem.with_suffix('.next.json')
with temporary.open('w') as f:json.dump(metadata,f,indent=2);f.flush();os.fsync(f.fileno())
os.replace(temporary,stem.with_suffix('.json'))
|