I ran some additional measurements on my side:
The header/size check is a useful first filter for a torn Safetensors file. #4595 requests automatic fallback to an older usable checkpoint; PR #4597 now also addresses staged saves, retention, numbering and rank agreement.
I compared the PR head 8b456a7 with its base bd0703e using small CPU fixtures in one process and two local Gloo processes. Both source checkouts reported 1.17.0.dev0. On November 29, 2026, the PR was open and unmerged; the latest GitHub release I found was 1.16.0. These measurements refer to the identified commits, not a released fix.
| Case |
Base |
PR #4597 head |
| Newest model file truncated |
Load raises |
Falls back to old |
| Newest model file truncated on rank 1 only |
Rank 0 loads new; rank 1 raises |
Both restore old |
| Registered object’s loader raises late |
Error after some state has changed |
Restored state and next step match explicit-old controls |
Replacement save fails with total_limit=1 |
Old checkpoint removed |
Old checkpoint retained; staging directory ignored |
| Existing final-named newest checkpoint has only RNG file missing |
Returns with incomplete state |
Still returns with incomplete state |
The last case is especially interesting in relation to the proposed preflight check. With just rank 1’s RNG file removed, both ranks returned from load_state() on the PR head. Accelerator.step was 2 on rank 0 and 0 on rank 1, instead of 2 on both. The models, optimizer states and scheduler states initially matched their normal-new controls, but after one further training step the measured state on neither rank matched the complete-checkpoint continuation.
The remaining case concerns an already existing final-named checkpoint. For recovery now, preserve earlier generations, inspect the files cheaply and explicitly load a known-good checkpoint into fresh compatible training objects. For exact continuation, check required resume state, not just the model file; for distributed training, agree on generation and restoration outcome.
1. What the file check does and does not establish
The reported header length of 152 bytes and file size of 98 bytes make this an inexpensive failure to detect. The first eight bytes of a Safetensors file are a little-endian unsigned header length. The header alone in this example requires at least 160 bytes including the prefix. The file cannot contain it; there is no need to allocate model tensors to reject that candidate.
The format specification and metadata parsing guide explain data_offsets: relative to the data buffer after the header, not the start of the file. Maximum end offset alone does not validate dtype, shape, layout or the absence of holes. Use bounded reads and the official parser rather than allocate a buffer based on an arbitrary header length.
Structural validity, integrity against a trusted digest, completeness of all required files and successful restoration are separate. A valid tensor file can contain wrong values; one valid shard cannot certify a full checkpoint. I have not rerun the Desk’s exact checker; the tests below use Accelerate’s actual save/load paths. A practical scanner could report the first decisive failure (for example, declared header extends beyond EOF) rather than a single unexplained invalid flag. For files that pass the cheap check, let the official loader establish format compatibility; do not infer a complete generation from its model file alone.
2. From automatic fallback to a save commit point
#4595, following #4549, reproduces the original failure on 1.16.0 / Torch 2.15.0+cpu / Windows. Explicit old works, while automatic load selects the truncated newest model file. The reporter’s workaround tries older generations with fresh objects.
| Commit |
Main change |
dede2c4 |
Try generations newest-first when loading raises |
1f99dca |
Stage new saves; prune only after publication |
9b0bbe8 |
Restore the automatic naming counter |
610dc86 |
Restore numbering also for explicit load within project’s checkpoint directory |
8b456a7 |
Coordinate common generation and load success across ranks |
The fixed implementation and regression tests cover several of these changes. I did not run the full upstream suite.
My fixture was a Linear(4, 2), AdamW, StepLR, a registered counter object and seeded Python/NumPy/Torch RNGs. The base saved generations 0 and 1 at training steps 1 and 2. I copied those same complete checkpoints for each load case, starting a fresh process/job with fresh training objects. Normal automatic load of the new generation and explicit load of the old one were controls for both revisions.
I compared model/optimizer/scheduler, CPU RNG hashes, Accelerator.step, registered counter and one random-input training step (loss and updated state). The fixture increments step explicitly.
The healthy controls match the saved states; head fallback matches explicit old, including the next step. I also reproduced the initial torn-file failure on the 1.15.0 and 1.16.0 release sources in earlier local single-process tests (ordinary Linear model, no optimizer or scheduler registered). The larger base/head comparison is separate, with the additional training components and fresh-process controls described here. After either complete generation loads, the head’s naming counter is 2. The base’s asymmetric failure skips the next collective step on all ranks via test instrumentation, not a base-library guarantee.
3. An additional case: readable weights, missing resume state
I removed only random_states_0.pkl from a complete base-generated checkpoint_1, leaving its other files and complete checkpoint_0 untouched. This is a legacy final-named directory test, not a failed staged save.
| One-process case on head |
Load result |
Step |
Custom value |
Model/optimizer/scheduler |
Python/NumPy/Torch RNG |
| Explicit old |
Returns |
1 |
1 |
Old |
Old |
| Normal automatic new |
Returns |
2 |
2 |
New |
New |
| Torn new |
Returns |
1 |
1 |
Matches old |
Matches old |
| RNG-only missing new |
Returns |
0 |
2 |
Matches new |
Differs from normal new |
Base behaves the same in the missing-RNG case. On head, the naming counter is 2, as for normal new; the registered counter and other measured training components match new, not old.
load_accelerator_state reads the per-process RNG file, takes the saved step if present and restores RNG states inside a try block. The exception handler logs at INFO without propagating. The base block is unchanged. The outer fallback loop sees no exception here, though logging may expose the omission.
A corrupt state failing midway through restoration could behave differently. Stateful dataloader file existence is another conditional restoration boundary; I did not test it.
| One-process continuation on head |
Loss |
| Explicit old |
0.17328761518001556 |
| Normal automatic new |
0.15689043700695038 |
| Missing RNG |
0.3714062571525574 |
The next-state difference is a diagnostic, not a training-quality result. Staging prevents certain interrupted new saves from acquiring final names, but cannot certify existing ones. Exact continuation could require RNG/progress restoration; permissive recovery can remain a separate policy.
4. What agreement across ranks means
The #4597 review reported rank-local fallback choosing different generations. The measured head exchanges available indices, tries common generations newest-first and collects local success flags, coordinating by index rather than absolute path.
My two-process test used CPU/Gloo on one machine, with independent project directories for each rank and simulated local-main writers (LOCAL_RANK=0, LOCAL_WORLD_SIZE=1 per worker). It is not a real two-node run. Only the rank 1 copy of the new checkpoint was modified in the fault cases. The head behaved as follows:
| Newest checkpoint modification |
Both return? |
Steps, r0/r1 |
Custom values, r0/r1 |
Next step vs control |
| None |
Yes |
2 / 2 |
2 / 2 |
Matches new |
| Rank 1 weight file truncated |
Yes |
1 / 1 |
1 / 1 |
Both match old |
| Rank 1 registered object raises |
Yes |
1 / 1 |
1 / 1 |
Both match old |
| Rank 1 RNG file missing |
Yes |
2 / 0 |
2 / 2 |
Neither matches normal new or old |
Removing only rank 1’s random_states_1.pkl gives successful returns on both revisions. Rank 0 initially matches normal new; rank 1 differs in all three RNG hashes and step, but not model/optimizer/scheduler/custom value. The next step counters are 3/1 instead of 3/3.
The next per-rank losses were 0.1578902155160904 / 0.29326915740966797, versus 0.1578902155160904 on both ranks in normal new. Rank 0’s loss alone does not reveal the omission; after the synchronized update both recorded states differ from normal new. The thrown-exception cases nevertheless recover correctly.
Check common generation, component identity, required-state restoration and next operation separately. Rank-specific RNG and shards need not be byte-identical: compare against each rank’s reference. A post-load vote cannot help if a rank fails before reaching a load-time collective. That is an untested concern, not an observed hang. No actual multi-node, GPU, FSDP, DeepSpeed or XLA test here.
5. A failed load can have changed the working state
A load is not read-only. The checkpointing implementation applies model, optimizer, scheduler and other state in sequence. I injected a late exception in a registered object’s loader after it assigned the new value and recorded the attempt. The base raises after state has changed; on the head, both 1p and 2p fallback restored the measured old state and next step. The diagnostic history [2, 1] rather than [1] is not serialized and is not rolled back. That is distinct from a mixed model/optimizer state, which I did not observe after successful fallback.
Read-only preflight is cheap for detectable file problems. Retry on existing objects can be appropriate when their restoration contract supports it. A fresh process per candidate is another option for stronger isolation of arbitrary application hooks, at the cost of reconstructing the training objects. The original reporter suggested fresh objects; the fixture’s positive result does not establish transactional rollback of every hook.
6. Choosing the intended resume contract
The checkpointing guide assumes compatible scripts. Expected files depend on the prepared/registered objects, backend and intended use:
| Purpose |
State required |
Missing state |
| Weights only |
Model/config |
Other components may be irrelevant |
| Deliberate warm start |
Selected state and reset policy |
Make reset explicit |
| Training continuation |
Model, optimizer, scheduler, progress, required scaler/custom state |
Reject or acknowledge omission |
| Exact continuation |
Also relevant RNG and data position |
Prefer a complete candidate |
| Distributed continuation |
Appropriate state per rank |
Agree collectively |
A read-only checker could compare files with an expected-component list when known; a save-generated manifest could identify required files and run identity. If required state is missing, try a complete earlier generation or stop. If optional, report and proceed under that policy. A strict opt-in restore or preflight report is a proposal, not an existing flag. For the fixture here a report could distinguish model file structurally OK from rank 1 RNG file absent and remaining required state not yet tested. A generation-level manifest should come from the writer’s actual contract rather than be reconstructed solely from the files found after a failure; otherwise the very file that went missing can disappear from the expected set. No manifest scheme is needed just to demonstrate the current problem.
Keep the trust boundary separate: prefix/size inspection need not deserialize Python objects. Other training-state files can use pickle-based serialization; see torch.load. A Safetensors model does not make the whole checkpoint safe to load from an untrusted source.
7. Save publication, retention, numbering and storage boundaries
Related #4436 describes deletion of the retained generation before a replacement save succeeds. My one-process fixture saved one complete checkpoint with total_limit=1, performed another step and injected an OSError at the RNG-state write of the replacement, before the custom object was saved.
| Observation |
Base |
Head |
| Replacement save |
Raises injected OSError |
Raises injected OSError |
Old checkpoint_0 |
Deleted |
Preserved |
| Leftover replacement |
checkpoint_1 |
.checkpoint_1.tmp |
| Automatic load after failed save |
Custom checkpoint count error |
Loads old; step/custom 1, naming counter 1 |
The head already stages, waits for writers, publishes and then prunes. This preserves the old generation in the injected exception case, at the cost of temporarily retaining both. Same-filesystem rename is a publication boundary, not proof of power-loss durability (fsync(2) also covers directory entries). No process-kill, storage-failure or remote filesystem test here.
As in #4502, automatic naming must not reuse an existing folder after fallback: highest existing index + 1 (2 here) is independent of restored training step (1). The head also handles explicit loads inside its own checkpoint namespace. I did not repeat the full restart/retention suite.
Windows #4454 is a related naming issue involving digits in parent paths. Numeric generation selection using the basename is distinct from training progress. I did not run that Windows repro.
8. A small reproducible CPU check
The main results were collected November 29 in Colab CPU: Python 3.13.18, PyTorch 2.14.1+cpu, NumPy 2.4.6, Safetensors 0.8.0, Linux x86-64, with Gloo. The code was imported from commit-specific source archives, not installed release wheels. The imported file hashes for accelerator.py were:
- Base:
4c8c0e96d68a0e66737c7254bd5c83a7893ab33002f7992c7c478f6e1d382e77
- Head:
800c97af964816c3fc72351b034da65682c43bcfa775425f63ce46a6e657f51b
Both imported checkpointing.py files had SHA-256 865a1489f8ab4e63d94a2b4c990ab8ffd360cc36331a854b0cc3d805ca604110. The distinction matters because both revisions have the same development version string. No model download is needed.
This smaller checkpoint-only example creates its own temporary synthetic fixtures. Never inject faults into real checkpoints. Obtain the fixed source trees, for example:
git init accelerate-base
git -C accelerate-base fetch --depth 1 https://github.com/huggingface/accelerate.git bd0703e3390ebb2b4eb1db5a0f1283f8edbc6091
git -C accelerate-base checkout --detach FETCH_HEAD
git -C accelerate-base rev-parse HEAD
git init accelerate-candidate
git -C accelerate-candidate fetch --depth 1 https://github.com/four1er/accelerate.git 8b456a7883ed9df04edc0d265e762c560b83c389
git -C accelerate-candidate checkout --detach FETCH_HEAD
git -C accelerate-candidate rev-parse HEAD
Verify both commits; use a compatible CPU Torch environment with Accelerate dependencies available. Save as checkpoint_worker.py:
import argparse, hashlib, json, os, random, sys
from pathlib import Path
p = argparse.ArgumentParser()
p.add_argument('task', choices=['save','load'])
p.add_argument('--root', type=Path, required=True)
p.add_argument('--case', default='')
p.add_argument('--source', type=Path, required=True)
p.add_argument('--version', default='')
args = p.parse_args()
# Two processes with separate project directories emulate node-local checkpoint stores.
if args.task in ('save','load') and int(os.environ.get('WORLD_SIZE','1')) > 1:
os.environ['LOCAL_RANK'] = '0'
os.environ['LOCAL_WORLD_SIZE'] = '1'
sys.path.insert(0, str(args.source.resolve()))
import torch, accelerate, numpy as np, safetensors
from accelerate import Accelerator
from accelerate.utils import ProjectConfiguration, set_seed
assert Path(accelerate.__file__).resolve().is_relative_to(args.source.resolve()), accelerate.__file__
if args.version:
assert accelerate.__version__ == args.version, accelerate.__version__
rank = int(os.environ.get('RANK','0'))
world = int(os.environ.get('WORLD_SIZE','1'))
args.root.mkdir(parents=True, exist_ok=True)
output = args.root / f'{args.task}_{args.case or "default"}_rank{rank}.jsonl'
def report(**data):
with output.open('a', encoding='utf-8') as f:
f.write(json.dumps(data, sort_keys=True, allow_nan=False)+'\n')
def sha(path): return hashlib.sha256(path.read_bytes()).hexdigest()
report(kind='environment', rank=rank, world=world, python=sys.version, torch=torch.__version__,
accelerate=accelerate.__version__, module=accelerate.__file__, safetensors=safetensors.__version__,
numpy=np.__version__, files={f:sha(Path(accelerate.__file__).parent/f) for f in ('accelerator.py','data_loader.py','checkpointing.py','logging.py')})
class State:
def __init__(self): self.value=-1; self.attempts=[]; self.fail_new=False
def state_dict(self): return {'value':self.value}
def load_state_dict(self,d):
self.value=d['value']; self.attempts.append(self.value)
# Intentional late failure fixture. Attempts are diagnostic side effects, not serialized state.
if self.fail_new and self.value==2: raise RuntimeError('intentional late custom load failure')
def ckpt_setup(root,limit=None):
set_seed(987)
a=Accelerator(cpu=True,project_config=ProjectConfiguration(project_dir=str(root),automatic_checkpoint_naming=True,total_limit=limit,save_on_each_node=(world>1)))
assert (a.num_processes, a.process_index) == (world, rank)
m=torch.nn.Linear(4,2); opt=torch.optim.AdamW(m.parameters(),lr=.01); sch=torch.optim.lr_scheduler.StepLR(opt,1,gamma=.8)
m,opt,sch=a.prepare(m,opt,sch); obj=State(); a.register_for_checkpointing(obj)
return a,m,opt,sch,obj
def snapshot(a,m,opt,sch,obj):
def tree(x):
if isinstance(x,torch.Tensor): return {'shape':list(x.shape),'dtype':str(x.dtype),'values':x.detach().cpu().tolist()}
if isinstance(x,dict): return {str(k):tree(v) for k,v in x.items()}
if isinstance(x,(list,tuple)): return [tree(v) for v in x]
return x
return {'model':tree(a.unwrap_model(m).state_dict()),'optimizer':tree(opt.state_dict()),'scheduler':tree(sch.state_dict()),
'rng_torch':hashlib.sha256(torch.get_rng_state().numpy().tobytes()).hexdigest(),
'rng_python':hashlib.sha256(repr(random.getstate()).encode()).hexdigest(),
'rng_numpy':hashlib.sha256(repr(np.random.get_state()).encode()).hexdigest(), 'step':a.step,'custom_value':obj.value}
def train(a,m,opt,sch):
x=torch.randn(4,4); loss=m(x).square().mean(); a.backward(loss); opt.step(); sch.step(); opt.zero_grad(); a.step+=1
return loss.detach().item()
def checkpoint_probe():
project=args.root/f'rank{rank}'
a,m,opt,sch,obj=ckpt_setup(project)
if args.task=='save':
for i in (1,2):
train(a,m,opt,sch); obj.value=i
path=a.save_state(); report(kind='saved',generation=i-1,path=str(path),state=snapshot(a,m,opt,sch,obj))
a.end_training(); return
obj.fail_new=args.case=='late' or (args.case=='late_rank1' and rank==1)
set_seed(321+rank); before=snapshot(a,m,opt,sch,obj)
try:
a.load_state(str(project/'checkpoints/checkpoint_0') if args.case=='explicit_old' else None)
report(kind='loaded',case=args.case,before=before,state=snapshot(a,m,opt,sch,obj),attempts=obj.attempts,iteration=a.project_configuration.iteration)
# A successful load on only some ranks must not enter a collective training step.
ok=True
except Exception as e:
report(kind='load_error',case=args.case,error_type=type(e).__name__,error=str(e),state=snapshot(a,m,opt,sch,obj),attempts=obj.attempts)
ok=False
oks=[ok]
if world>1:
oks=[None]*world; torch.distributed.all_gather_object(oks,ok)
if all(oks):
loss=train(a,m,opt,sch); report(kind='next_step',case=args.case,loss=loss,state=snapshot(a,m,opt,sch,obj))
else: report(kind='next_step_skipped',rank_success=oks)
a.end_training()
checkpoint_probe()
Save as compare_checkpoints.py beside it:
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
base, head = (Path(p).resolve() for p in sys.argv[1:3])
world = int(sys.argv[3]) if len(sys.argv) > 3 else 1
assert world in (1, 2)
worker = Path(__file__).resolve().with_name('checkpoint_worker.py')
env = os.environ.copy()
for k in ('RANK', 'LOCAL_RANK', 'WORLD_SIZE', 'LOCAL_WORLD_SIZE', 'MASTER_ADDR',
'MASTER_PORT', 'ACCELERATE_MIXED_PRECISION', 'ACCELERATE_USE_DEEPSPEED',
'ACCELERATE_USE_FSDP', 'ACCELERATE_USE_MEGATRON_LM'):
env.pop(k, None)
env.update(ACCELERATE_USE_CPU='true', CUDA_VISIBLE_DEVICES='',
OMP_NUM_THREADS='1', MKL_NUM_THREADS='1')
def run(source, root, task, case=''):
cmd = [sys.executable]
if world == 2:
cmd += ['-m', 'torch.distributed.run', '--standalone', '--nproc-per-node=2']
cmd += [str(worker), task, '--root', str(root), '--source', str(source)]
if case:
cmd += ['--case', case]
subprocess.run(cmd, env=env, check=True, timeout=120)
return [[json.loads(line) for line in
(root / f'{task}_{case or "default"}_rank{r}.jsonl').read_text().splitlines()]
for r in range(world)]
def get(rows, kind):
return next((row for row in rows if row['kind'] == kind), None)
with tempfile.TemporaryDirectory(prefix='resume_check_') as tmp:
root = Path(tmp)
fixture = root / 'fixture'
saved = run(base, fixture, 'save')
for label, source in [('base', base), ('head', head)]:
obs = {}
for case in ('explicit_old', 'normal', 'torn', 'missing_rng', 'late'):
work = root / f'{label}_{case}'
shutil.copytree(fixture, work)
r = world - 1
newest = work / f'rank{r}' / 'checkpoints/checkpoint_1'
if case == 'torn':
path = newest / 'model.safetensors'
with path.open('r+b') as f:
f.truncate(path.stat().st_size // 2)
elif case == 'missing_rng':
(newest / f'random_states_{r}.pkl').unlink()
load_case = 'late_rank1' if case == 'late' and world == 2 else case
obs[case] = run(source, work, 'load', load_case)
for r in range(world):
# Healthy controls must match the original saved state.
reference = [row['state'] for row in saved[r] if row['kind'] == 'saved']
for case, generation in [('explicit_old', 0), ('normal', 1)]:
assert get(obs[case][r], 'loaded')['state'] == reference[generation]
for case in obs:
rows = obs[case][r]
loaded = get(rows, 'loaded')
error = get(rows, 'load_error')
event = loaded or error
assert event is not None
state = event['state']
new = get(obs['normal'][r], 'loaded')['state']
old = get(obs['explicit_old'][r], 'loaded')['state']
nxt = get(rows, 'next_step')
def next_matches(control):
ref = get(obs[control][r], 'next_step')
return bool(nxt and ref and nxt['state'] == ref['state']
and nxt['loss'] == ref['loss'])
print(json.dumps(dict(label=label, case=case, rank=r,
environment=get(rows, 'environment'),
loaded=loaded is not None, error=error and error['error_type'],
step=state['step'], custom_value=state['custom_value'],
iteration=event.get('iteration'), attempts=event['attempts'],
differs_from_new=[k for k in new if state[k] != new[k]],
restored_matches_old=bool(loaded and state == old),
next_step=nxt and nxt['state']['step'], loss=nxt and nxt['loss'],
next_matches_old=next_matches('explicit_old'),
next_matches_new=next_matches('normal'))), flush=True)
Run the single-process comparison, then optionally the two-process Gloo comparison:
python compare_checkpoints.py accelerate-base/src accelerate-candidate/src 1
python compare_checkpoints.py accelerate-base/src accelerate-candidate/src 2
The short script covers load comparisons, not the separate staged-save fault injection. Its output is diagnostic JSON; successful process exit only means the harness completed, since load exceptions are recorded as observations. Inspect restored_matches_old, next_matches_old, differs_from_new, step and next_matches_new. The healthy controls must match saved state. In two processes only rank 1 is faulted. A distinct fresh-process seed lets us check Python/NumPy restoration even when those RNGs are identical across generations.
The edited code was exercised with 1.16.0 source on both sides (CPU 1/2p; Python 3.13.5, Torch 2.10.0+cpu, NumPy 2.3.5, Safetensors 0.7.0), not re-run on the fixed PR. The main measurements use the larger original runner; the Git acquisition commands are an untested alternative to its source archives.
9. From a successful load to a training continuation
For stronger guarantees, compare uninterrupted and split runs, first at restored state, then next random draws, batch IDs, loss/update and (if relevant) the next epoch or second resume. The data stream was not tested here. For a shuffled or stateful loader a tiny range of sample IDs is often more informative than a large loss curve: compare the expected remainder of the current epoch and the next epoch separately. Then save again after some resumed batches and compare the second resume if repeated interruptions matter. Related but distinct mechanisms:
- Accelerate #4330 reports shuffle-order mismatch with
load_state() plus skip_first_batches() and separate behavior for default and seedable samplers. That is a sampler/epoch reconstruction problem, not the torn-file selection mechanism.
- Datasets #8295 fixed a streaming state reference that could stay stale after the first resume. The regression compares an uninterrupted stream with two consecutive restores, rather than just checking that one load succeeds.
- TorchData #1561 reports a shared sampler/loader generator boundary in which the remaining sequence can differ after restoration, with separate-generator controls. Again, it is a different mechanism.
resumecheck likewise compares trajectories; I did not run it. Exact equality here is fixture-specific; gradient accumulation, worker prefetch and world-size changes are separate conditions.
10. Related implementations and the scope of the result
- SCR separates completion, candidate selection and collective success; not a drop-in
load_state() implementation.
- PyTorch DCP has its own distributed state/storage contracts, not a universal Safetensors file layout.
- Transformers Trainer #35580 introduced staging; after reports of incomplete saves with DeepSpeed, #36112 reverted it and a related change. This is a reason to check backend-specific writer semantics, not evidence of the same fault in #4597.
- Lightning #689 stages a single file; committing a multi-file generation has a different boundary.
The measurements cover only fixed CPU revisions, small fixtures and specified local faults, not production failure frequency or all backends. Keep file validation, publication, retention, rank agreement and required-state restoration separate. The last can complement #4597 without negating its measured improvements.