"""Atomic, integrity-checked recovery checkpoints; only load trusted local runs.""" import hashlib,json,os,random,shutil,tempfile from pathlib import Path import torch from safetensors.torch import load_file,save_file def sha256(path): h=hashlib.sha256() with Path(path).open('rb') as stream: while chunk:=stream.read(8*1024*1024): h.update(chunk) return h.hexdigest() def save_checkpoint(model,optimizer,path,step,metadata): path=Path(path) path.parent.mkdir(parents=True,exist_ok=True) if path.exists(): raise FileExistsError(path) temp=Path(tempfile.mkdtemp(prefix='.'+path.name+'-',dir=path.parent)) try: save_file({k:v.detach().cpu().contiguous() for k,v in model.state_dict().items()},str(temp/'model.safetensors')) state={'step':step,'optimizer':optimizer.state_dict(),'python_rng':random.getstate(), 'torch_rng':torch.get_rng_state(),'cuda_rng':torch.cuda.get_rng_state_all() if torch.cuda.is_available() else []} torch.save(state,temp/'trainer.pt') manifest={'format_version':1,'step':step,'metadata':metadata, 'sha256':{name:sha256(temp/name) for name in ('model.safetensors','trainer.pt')}} (temp/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') for file in temp.iterdir(): with file.open('rb') as stream:os.fsync(stream.fileno()) directory_fd=os.open(temp,os.O_RDONLY) try:os.fsync(directory_fd) finally:os.close(directory_fd) os.rename(temp,path) parent_fd=os.open(path.parent,os.O_RDONLY) try:os.fsync(parent_fd) finally:os.close(parent_fd) except BaseException: shutil.rmtree(temp) raise def restore_checkpoint(model,optimizer,path,expected_metadata): path=Path(path) manifest=json.loads((path/'manifest.json').read_text()) if manifest.get('format_version')!=1: raise ValueError('Unsupported checkpoint format') if manifest['metadata']!=expected_metadata: raise ValueError('Checkpoint data/model/training configuration differs') for name in ('model.safetensors','trainer.pt'): if sha256(path/name)!=manifest['sha256'][name]: raise ValueError('Checkpoint integrity failure: '+name) state=torch.load(path/'trainer.pt',map_location='cpu',weights_only=True) if state['step']!=manifest['step']: raise ValueError('Checkpoint step mismatch') if len(state['cuda_rng']) != (torch.cuda.device_count() if torch.cuda.is_available() else 0): raise ValueError('Resume requires the same CUDA device count') model.load_state_dict(load_file(str(path/'model.safetensors')),strict=True) optimizer.load_state_dict(state['optimizer']) random.setstate(state['python_rng']); torch.set_rng_state(state['torch_rng']) if state['cuda_rng']: torch.cuda.set_rng_state_all(state['cuda_rng']) return state['step']