File size: 2,893 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
"""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']