File size: 7,394 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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | """Immutable tile revisions and atomic whole-training checkpoints."""
import hashlib,json,os,random,shutil,tempfile,time
from pathlib import Path
import torch
from safetensors.torch import save_file,load_file
from weights.identity import file_sha256
def sync_directory(path):
fd=os.open(path,os.O_RDONLY)
try:os.fsync(fd)
finally:os.close(fd)
def atomic_json(path,value):
path=Path(path);path.parent.mkdir(parents=True,exist_ok=True);tmp=path.with_name(path.name+'.next')
with tmp.open('w') as f:json.dump(value,f,indent=2);f.flush();os.fsync(f.fileno())
tmp.replace(path);sync_directory(path.parent)
def safe_child(directory,name):
if not isinstance(name,str) or Path(name).name!=name or name in ['.','..']:raise ValueError('Invalid checkpoint filename')
return Path(directory)/name
class TileStore:
def __init__(self,root,catalog=None):self.root=Path(root);self.root.mkdir(parents=True,exist_ok=True);self.catalog=dict(catalog or {})
def weights(self,record):
file=safe_child(self.root,record['weights'])
if file_sha256(file)!=record['weights_sha256']:raise ValueError('Tile weight checksum failure')
return load_file(str(file))
def optimizer(self,record):
file=safe_child(self.root,record['optimizer'])
if file_sha256(file)!=record['optimizer_sha256']:raise ValueError('Tile optimizer checksum failure')
return torch.load(file,map_location='cpu',weights_only=True)
def commit(self,coordinate,tile,optimizer):
records={}
for kind in ['weights','optimizer']:
suffix='.safetensors' if kind=='weights' else '.pt';fd,name=tempfile.mkstemp(prefix='.tile-',suffix=suffix,dir=self.root);os.close(fd);temp=Path(name)
if kind=='weights':save_file({k:v.detach().contiguous() for k,v in tile.state_dict().items()},str(temp))
else:torch.save(optimizer.state_dict(),temp)
with temp.open('rb') as f:os.fsync(f.fileno())
digest=file_sha256(temp);dest=self.root/(digest+suffix)
if dest.exists():temp.unlink()
else:temp.replace(dest)
records[kind]=dest.name;records[kind+'_sha256']=digest
sync_directory(self.root);record=dict(coordinate,**records);self.catalog[coordinate['key']]=record;return record
def save_snapshot(run,bank,bank_optimizer,sampler,step,identity,store,runtime):
run=Path(run);directory=run/'recovery';directory.mkdir(parents=True,exist_ok=True);target=directory/f'step-{step:08d}'
if target.exists():
try:verify_snapshot(target,identity)
except (OSError,ValueError,KeyError):
# A fallback can reach the step number of a damaged newer snapshot.
# Preserve it for inspection and publish the newly completed state.
damaged=run/'damaged-recovery';damaged.mkdir(exist_ok=True)
target.rename(damaged/(target.name+'-'+str(time.time_ns())))
sync_directory(damaged);sync_directory(directory)
else:
atomic_json(run/'LATEST.json',dict(checkpoint=target.name,manifest_sha256=file_sha256(target/'manifest.json')))
return target
temp=Path(tempfile.mkdtemp(prefix='.snapshot-',dir=directory))
try:
bank.save(temp/'focus',identity)
torch.save(dict(bank_optimizer=bank_optimizer.state_dict(),sampler=sampler.state_dict(),torch_rng=torch.get_rng_state(),python_rng=random.getstate()),temp/'trainer.pt')
public=dict(step=step,tile_catalog=store.catalog,**runtime);(temp/'runtime.json').write_text(json.dumps(public,indent=2)+'\n')
manifest=dict(format_version=1,identity=identity,step=step,sha256={str(file.relative_to(temp)):file_sha256(file) for file in temp.rglob('*') if file.is_file()})
(temp/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
for file in temp.rglob('*'):
if file.is_file():
with file.open('rb') as f:os.fsync(f.fileno())
sync_directory(temp/'focus');sync_directory(temp);temp.rename(target);sync_directory(directory)
atomic_json(run/'LATEST.json',dict(checkpoint=target.name,manifest_sha256=file_sha256(target/'manifest.json')))
return target
except BaseException:shutil.rmtree(temp);raise
def verify_snapshot(path,expected_identity=None):
path=Path(path);manifest=json.loads((path/'manifest.json').read_text())
if manifest.get('format_version')!=1:raise ValueError('Unsupported snapshot format')
if expected_identity is not None and manifest['identity']!=expected_identity:raise RuntimeError('Training identity/configuration changed; explicit migration required')
for name,digest in manifest['sha256'].items():
relative=Path(name)
if relative.is_absolute() or '..' in relative.parts:raise ValueError('Invalid snapshot path')
if file_sha256(path/relative)!=digest:raise ValueError('Snapshot checksum failure: '+name)
runtime=json.loads((path/'runtime.json').read_text())
if runtime['step']!=manifest['step']:raise ValueError('Snapshot step mismatch')
store=TileStore(path.parent.parent/'blobs',runtime['tile_catalog'])
for record in store.catalog.values():
store.weights(record)
if file_sha256(safe_child(store.root,record['optimizer']))!=record['optimizer_sha256']:raise ValueError('Tile optimizer checksum failure')
return manifest,runtime,store
def latest_valid(run,identity):
failures=[]
for path in sorted((Path(run)/'recovery').glob('step-*'),reverse=True):
try:
manifest,runtime,store=verify_snapshot(path,identity);return path,runtime,store,failures
except (OSError,ValueError,KeyError) as error:failures.append(dict(checkpoint=path.name,error=str(error)))
raise RuntimeError('No valid recoverable checkpoint: '+json.dumps(failures))
def restore_training(path,bank,optimizer,sampler):
bank.load_state_dict(load_file(str(Path(path)/'focus/adapter.safetensors')),strict=True)
state=torch.load(Path(path)/'trainer.pt',map_location='cpu',weights_only=True);optimizer.load_state_dict(state['bank_optimizer']);sampler.load_state_dict(state['sampler']);torch.set_rng_state(state['torch_rng']);random.setstate(state['python_rng'])
def prune_recovery(run,store,keep=3):
"""Call only inside the trainer after a durable snapshot, with no concurrent writer."""
run=Path(run);snapshots=sorted((run/'recovery').glob('step-*'),reverse=True)
retained={p.name for p in snapshots[:keep]}|{'step-00000000'}
for pointer in ['BEST.json','LATEST.json']:
if (run/pointer).exists():retained.add(json.loads((run/pointer).read_text())['checkpoint'])
live={r[k] for r in store.catalog.values() for k in ['weights','optimizer']}
for path in snapshots:
if path.name in retained:
runtime=json.loads((path/'runtime.json').read_text())
live.update(r[k] for r in runtime['tile_catalog'].values() for k in ['weights','optimizer'])
for path in snapshots:
if path.name not in retained:shutil.rmtree(path)
removed=0
for path in store.root.iterdir():
if path.is_file() and path.suffix in ['.pt','.safetensors'] and len(path.stem)==64 and path.name not in live:
path.unlink();removed+=1
sync_directory(run/'recovery');sync_directory(store.root)
return dict(retained_snapshots=sorted(retained),removed_blobs=removed)
|