Repository navigation
Description
Describe the bug
Summary. save_checkpoint writes each rank's files with torch.save directly to their final names inside <save_dir>/<tag>/, one rank at a time, even when that tag already holds a complete checkpoint. A crash during such a save leaves a tag whose files come from two different saves, which load_checkpoint restores without error. With the default tags (global_step<N>) this happens after a rollback with load_checkpoint(load_dir, tag=<older>) in the same directory: the next save reuses the abandoned run's tag.
We would like save_checkpoint not to rewrite a committed tag in place, or at least to warn when it is about to (see "Suggested change" under Additional context). Saving the retrained run to a new save_dir, or under explicit unique tags, avoids the in-place rewrite today; it does not make the save itself crash-safe.
This needs a save under a tag that already holds a committed checkpoint in the same directory, and a crash during that save. With the default tags that happens after an explicit-tag rollback, because run B's global_step<N> tags repeat run A's; it also applies to a re-save under a fixed tag. Saves under fresh tags do not rewrite a committed checkpoint and are not affected by this issue. The getting-started tutorial shows the explicit-tag load (model_engine.load_checkpoint(args.load_dir, args.ckpt_id)); its save uses an explicit ckpt_id and a separate save_dir, so the tutorial itself does not hit this.
- Silent, mixed state: a crash while run B re-saves
global_step<N>can leave rank 0's model states and some ranks' ZeRO shards from run B and the other shards from run A. The nextload_checkpoint(save_dir)succeeds and training continues from that mix. - Loud: a crash while a file is being rewritten leaves it truncated (
EOFError: Ran out of input) until an operator intervenes.
Separate note, not part of this bug. load_checkpoint(tag=...) does not touch latest, so after a rollback a crash before run B's first completed save leaves latest naming run A's newest tag, and a restart from latest continues run A. That follows from load_checkpoint being read-only; a sentence in the checkpointing docs, or an option to record the rollback, would help.
To Reproduce
Standalone script (2 CPU ranks, gloo, ZeRO stage 1), in the collapsible block below:
DS_ACCELERATOR=cpu python deepspeed_rollback_resave.py
Each save records which run wrote it, in client_state (rank 0's model states file) and in the base optimizer's param_groups[0] (each rank's ZeRO shard). Rank 1 sleeps 5 s before writing its ZeRO shard in run B (test-only, so the race is deterministic).
deepspeed_rollback_resave.py
"""After load_checkpoint(tag=<older>), the next save rewrites the abandoned run's tag in place.
DS_ACCELERATOR=cpu python deepspeed_rollback_resave.py
Two CPU ranks (gloo, ZeRO stage 1), default tags (global_step<N>). Run A saves global_step1 and
global_step2. Run B rolls back with load_checkpoint(tag="global_step1"), trains one step and
saves, which reuses the tag global_step2. Rank 1 sleeps 5 s before writing its ZeRO shard
(test-only, so the race is deterministic), and the job is killed with SIGKILL once rank 0 has
rewritten `latest`. Run 3 calls load_checkpoint(save_dir) and reports, on each rank, which run
wrote the model states file (client_state) and which run wrote that rank's own ZeRO shard.
"""
import datetime
import os
import signal
import socket
import subprocess
import sys
import tempfile
import time
def worker(phase, rank, port, ckpt):
os.environ.update(RANK=rank, LOCAL_RANK=rank, WORLD_SIZE="2", MASTER_ADDR="127.0.0.1",
MASTER_PORT=port)
import deepspeed
import torch
deepspeed.init_distributed(dist_backend="gloo", timeout=datetime.timedelta(seconds=60))
torch.manual_seed(0)
model = torch.nn.Sequential(torch.nn.Linear(16, 32), torch.nn.ReLU(), torch.nn.Linear(32, 4))
cfg = {"train_batch_size": 2, "train_micro_batch_size_per_gpu": 1,
"zero_optimization": {"stage": 1}, "zero_allow_untested_optimizer": True,
"steps_per_print": 10**9}
engine, *_ = deepspeed.initialize(model=model, optimizer=torch.optim.Adam(model.parameters()),
config=cfg)
def train_and_save(run):
engine.backward(engine(torch.randn(1, 16)).pow(2).sum())
engine.step()
engine.optimizer.optimizer.param_groups[0]["run"] = run # stored in this rank's ZeRO shard
engine.save_checkpoint(ckpt, client_state={"run": run}) # stored in mp_rank_00_model_states.pt
if phase == "A":
train_and_save("A")
train_and_save("A")
elif phase == "B":
engine.load_checkpoint(ckpt, tag="global_step1")
if rank == "1":
original = engine._save_zero_checkpoint
def slow(*args, **kwargs):
time.sleep(5)
return original(*args, **kwargs)
engine._save_zero_checkpoint = slow
train_and_save("B")
else:
path, client = engine.load_checkpoint(ckpt)
shard = engine.optimizer.optimizer.param_groups[0].get("run")
print(f"rank {rank}: loaded {os.path.basename(os.path.dirname(path))} without error; "
f"model states from run {client['run']}, own ZeRO shard from run {shard}", flush=True)
def run(phase, ckpt, kill_when_latest_rewritten=False):
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
port = str(s.getsockname()[1])
latest = os.path.join(ckpt, "latest")
before = os.stat(latest).st_mtime_ns if os.path.exists(latest) else None
procs = [subprocess.Popen([sys.executable, __file__, "worker", phase, str(r), port, ckpt])
for r in range(2)]
while kill_when_latest_rewritten and any(p.poll() is None for p in procs):
if os.stat(latest).st_mtime_ns != before:
for p in procs:
p.send_signal(signal.SIGKILL)
print(f"job killed once rank 0 rewrote `latest` ({open(latest).read()})", flush=True)
break
time.sleep(0.001)
return [p.wait() for p in procs]
if __name__ == "__main__":
if sys.argv[1:2] == ["worker"]:
worker(*sys.argv[2:])
sys.exit(0)
ckpt = tempfile.mkdtemp()
print("run A exit codes:", run("A", ckpt), sorted(os.listdir(ckpt)), flush=True)
print("run B exit codes:", run("B", ckpt, kill_when_latest_rewritten=True), flush=True)
print("restart exit codes:", run("C", ckpt), flush=True)Output (DeepSpeed 0.19.9, other log lines removed):
run A exit codes: [0, 0] ['global_step1', 'global_step2', 'latest', 'zero_to_fp32.py', 'zero_to_torch.py']
job killed once rank 0 rewrote `latest` (global_step2)
run B exit codes: [-9, -9]
rank 0: loaded global_step2 without error; model states from run B, own ZeRO shard from run B
rank 1: loaded global_step2 without error; model states from run B, own ZeRO shard from run A
restart exit codes: [0, 0]
Rank 1's fp32 master weights and optimizer moments now come from run A (step 2 of the abandoned run), the rest from run B. The 5 s sleep makes the window deterministic. Without it, a SIGKILL that lands while the files are being rewritten can leave global_step2 unloadable (a truncated file) or a mix that loads without error; a kill after every rank has finished its files loads run B.
Expected behavior
- Expected: a crash while run B re-saves
global_step2leaves run A'sglobal_step2, run B's completeglobal_step2, or a tag thatload_checkpointrefuses. - Actual:
global_step2can hold files from both runs and loads without error.
ds_report output
ds_report (DeepSpeed 0.19.9, CPU)
--------------------------------------------------
DeepSpeed C++/CUDA extension op report
--------------------------------------------------
NOTE: Ops not installed will be just-in-time (JIT) compiled at
runtime if needed. Op compatibility means that your system
meet the required dependencies to JIT install the op.
--------------------------------------------------
JIT compiled ops requires ninja
ninja .................. [OKAY]
--------------------------------------------------
op name ................ installed .. compatible
--------------------------------------------------
deepspeed_not_implemented [NO] ....... [OKAY]
[WARNING] async_io requires the dev libaio .so object and headers but these were not found.
[WARNING] async_io: please install the libaio-dev package with apt
[WARNING] If libaio is already installed (perhaps from source), try setting the CFLAGS and LDFLAGS environment variables to where it can be found.
async_io ............... [NO] ....... [NO]
deepspeed_ccl_comm ..... [NO] ....... [OKAY]
deepspeed_shm_comm ..... [NO] ....... [OKAY]
cpu_adagrad ............ [NO] ....... [OKAY]
cpu_adam ............... [NO] ....... [OKAY]
cpu_lion ............... [NO] ....... [OKAY]
fused_adam ............. [NO] ....... [OKAY]
pin_memory ............. [NO] ....... [OKAY]
--------------------------------------------------
DeepSpeed general environment info:
torch install path ............... ['/usr/local/lib/python3.12/site-packages/torch']
torch version .................... 2.15.0+cpu
deepspeed install path ........... ['/usr/local/lib/python3.12/site-packages/deepspeed']
deepspeed info ................... 0.19.9, unknown, unknown
deepspeed wheel compiled w. ...... torch 0.0
shared memory (/dev/shm) size .... 64.00 MB
[WARNING] /dev/shm size might be too small, if running in docker increase to at least --shm-size='1gb'
Screenshots
N/A
System info
- OS: Linux (aarch64), in a container; CPU only
- GPU count and types: none (
DS_ACCELERATOR=cpu); 2 CPU ranks, gloo - Interconnects: none (one host)
- Python version: 3.12.16
- Other: DeepSpeed 0.19.9 (latest release), torch 2.15.0+cpu, ZeRO stage 1, local file system.
- Checked on
masterat6f96b4a(2026-11-09): the default tag isglobal_step{self.global_steps}, and nothing checks whether<save_dir>/<tag>already exists. - Rechecked on 2026-11-12: 0.19.9 and
masterat988b2e3(2026-11-12): reproduces. Inengine.pythe only change since6f96b4ais an unrelated ZeRO option, which moves the linked checkpoint code 4 lines down.
- Checked on
Launcher context
The script starts each rank as a plain Python subprocess with RANK, LOCAL_RANK, WORLD_SIZE and MASTER_ADDR set (no launcher).
Docker context
No project image: python:3.12-slim with the CPU torch wheel and pip install deepspeed==0.19.9 (DS_BUILD_OPS=0).
Additional context
Root cause
save_checkpointderives the default tag from the restoredglobal_steps(engine.py#L4963-L4964; L4915-L4916 in 0.19.9), so after a rollback the next tags are the abandoned run's tags, and nothing checks whether<save_dir>/<tag>already holds a checkpoint. Each rank then writes its files withtorch.savedirectly to their final names inside the existing directory (truncate, then write), so during the save the directory holds a mix.- When the rollback is one checkpoint back, as in the script, run A's
latestalready names the tag run B re-saves, so the mixed directory is what a restart loads even iflatestis never rewritten. For a deeper rollback,latestnames it once rank 0 rewriteslatest(engine.py#L5021-L5023; L4973-L4975 in 0.19.9), which it does after its own files and before the final barrier (L5025; L4977 in 0.19.9), without waiting for the other ranks.
Suggested change
We understand that checkpoint writes are meant to go to empty folders: a maintainer noted on PR #4707 that "checkpoint writes are usually directed to empty folders to avoid this kind of data loss". Saving the retrained run to a new save_dir avoids the in-place rewrite. With the default tags, though, a rollback in the same directory reaches it without any warning. (a) or (b) removes the silent case; (c) is the minimum:
- (a) Write the tag into a staging directory in the same parent and swap it in after all ranks have finished, moving any existing directory aside first (a directory rename cannot replace a non-empty directory on POSIX, and object stores and
use_node_local_storageneed their own handling), so a crash leaves a missing or old tag, never a mixed one. - (b) Record a per-save id in every file of a tag and have
load_checkpointrefuse a tag whose files disagree, which makes a mix loud however it arose. - (c) At minimum, warn when
save_checkpointis about to write into a tag directory that already contains checkpoint files.
Whether to refuse by default is a compatibility decision for the maintainers: intentional re-saves under fixed tags (for example "best") exist, and recovery after a crash re-saves into an incomplete tag.
Related issues
We found no prior report of this.
- #8952 (open): converting into an existing output directory does not retire the previous output, so a loader can read the old checkpoint. A different code path (conversion), but the same pattern of writing into a directory that still holds older files.
- #8499 (open) / PR #8501 (open): ZeRO-3 ignores the checkpoint tag when
load_optimizer_states=False; a different problem in tag handling.
Searches (run on 2026-11-10)
GitHub issue and pull request search, which gh search issues also uses: repo:deepspeedai/DeepSpeed with overwrite checkpoint same tag (28 results), load_checkpoint tag rollback (1), save_latest (6), checkpoint partial crash resume (1), checkpoint atomic (7). Web search: DeepSpeed load_checkpoint older tag rollback save_checkpoint overwrites existing tag directory crash mixed shards (found the checkpointing docs, #1749, and the maintainer comment on PR #4707 quoted above, which matches the first suggested change; none about this).
How this was found
We found this with a crash-injection tool that kills every rank with SIGKILL just before or just after each file operation of a checkpoint save, restarts the job and checks, through per-rank markers like the ones in the script, which run each restored piece came from. The standalone script above reproduces it without that tool.
AI assistance
This report, its reproduction script and the analysis were prepared with an AI coding agent. I ran the reproduction on the versions listed above and checked the analysis and the cited code.
Activity