skip to content

A Hugging Face Trainer fine-tune on a preemptible GPU is killed at step 3,200 - how do you make it resume where it stopped instead of restarting?

level: seniorimportance: should knowfreq 15%

answer

  1. more state than the weights
  2. checkpoint-N folders under output_dir
  3. optimizer, scheduler, RNG, trainer state
  4. SIGTERM-triggered saving
  5. a last-checkpoint copy on the Hub

basics

~10 s

Save full checkpoints to durable storage with save_strategy, save_steps and save_total_limit, then call trainer.train(resume_from_checkpoint=True) to reload the newest checkpoint's weights, optimizer, scheduler, RNG and step. enable_jit_checkpoint=True adds a save on SIGTERM.

solid answer

~40 s

Trainer writes `checkpoint-<step>` folders into `output_dir` every `save_steps` updates; each holds the weights (or only the adapter for a PEFT model), `optimizer.pt`, `scheduler.pt`, `rng_state.pth` and `trainer_state.json`. On restart I rebuild the same Trainer and call `trainer.train(resume_from_checkpoint=True)`, which takes the highest-numbered folder (or raises if there is none), restores that state and skips the batches already seen unless `ignore_data_skip=True`. For pre-emption I put `output_dir` on storage that outlives the VM, cap disk with `save_total_limit`, never set `save_only_model=True`, and in Transformers v5.18 turn on `enable_jit_checkpoint=True` so SIGTERM triggers a final save, with a grace period long enough for one step plus the save. `hub_strategy="checkpoint"` also uploads a `last-checkpoint` folder.

code

python · 21 lines
python
import os
from transformers import Trainer, TrainingArguments
from transformers.trainer_utils import get_last_checkpoint

args = TrainingArguments(
    output_dir="/mnt/durable/runs/sft-v3",  # survives the VM
    save_strategy="steps",
    save_steps=200,
    save_total_limit=3,
    enable_jit_checkpoint=True,             # checkpoint on SIGTERM
    push_to_hub=True,
    hub_model_id="your-org/sft-v3",
    hub_strategy="checkpoint",              # also uploads last-checkpoint/
    bf16=True,
)
trainer = Trainer(model=model, args=args, train_dataset=train_ds, processing_class=tokenizer)

last = get_last_checkpoint(args.output_dir) if os.path.isdir(args.output_dir) else None
if last and os.path.exists(os.path.join(last, "checkpoint-is-incomplete.txt")):
    raise SystemExit(f"{last} was cut off mid-save; resume from the previous checkpoint")
trainer.train(resume_from_checkpoint=last)  # None on the first run starts fresh

go deeper

for a junior

Recall that Trainer writes checkpoint-N folders into output_dir and that trainer.train(resume_from_checkpoint=True) continues from the newest one.

for a middle

Explain what a checkpoint holds beyond weights - optimizer, scheduler, RNG and trainer state - and why the data loader is fast-forwarded on resume.

for a senior

Design for pre-emption: durable output_dir, save cadence against lost work, enable_jit_checkpoint with a real grace period, and checking the newest folder before trusting it.

for a principal

Weigh checkpoint frequency and retention against storage and lost GPU hours, and decide whether Hub copies or shared storage are the team's recovery path.

## Why weights alone are not a resume A fine-tune's progress lives in more than its weights. An AdamW-style optimizer keeps running moment estimates for every trainable parameter, the learning-rate scheduler knows how far along its curve it is, the order in which data is shuffled depends on random-number-generator state, and the run's global step, epoch and log history sit in a small state file. Reloading only the weights with `from_pretrained` and calling `train()` again starts the optimizer cold, replays the schedule from the beginning and shows the model data it has already seen. A **resume** restores all of it. ## What a checkpoint folder holds Trainer writes a folder named `checkpoint-<global step>` inside `output_dir` at every save. | File | What it restores | |---|---| | `model.safetensors` (or shards) | Model weights; a PEFT model writes only `adapter_model.safetensors` and `adapter_config.json` | | `optimizer.pt` | Optimizer state, such as AdamW's moment estimates | | `scheduler.pt` | The learning-rate scheduler's position | | `rng_state.pth` | Python, NumPy, torch and CUDA generator states (`rng_state_<rank>.pth` per process when distributed) | | `trainer_state.json` | Global step, epoch, log history, best metric so far | | `training_args.bin` | The arguments the run used | ## How resuming works 1. Re-create the same model, `TrainingArguments`, datasets and `Trainer` as the interrupted run. 2. Call `trainer.train(resume_from_checkpoint=True)`. Trainer lists the `checkpoint-*` folders in `output_dir` and takes the **highest step number**; if there is none, it raises `ValueError`. A string path such as `"runs/sft/checkpoint-3000"` picks one explicitly, and `None` starts fresh. 3. Trainer reloads weights, optimizer, scheduler and RNG states and `trainer_state.json`, then **fast-forwards the data** past the batches already consumed, so the continuation matches an uninterrupted run. 4. `ignore_data_skip=True` skips that fast-forward: a quicker restart, but the run no longer matches. The `resume_from_checkpoint` field on `TrainingArguments` is **not read by Trainer itself**; it exists for training scripts. The argument that counts is the one passed to `train()`. ## Surviving pre-emption - **Put `output_dir` on storage that outlives the machine.** A pre-empted VM's local disk goes with it. - **Choose the cadence deliberately.** With `save_strategy="steps"` you can lose up to `save_steps` updates; `save_total_limit` caps how many folders stay on disk. - **Turn on `enable_jit_checkpoint=True`.** On SIGTERM, Trainer lets the current step finish, writes a checkpoint and stops. The orchestrator's grace period must cover the longest step, the save and a 3-second wait; the Transformers docs note that Kubernetes' default of 30 seconds is usually too short. - **Watch for half-written folders.** A JIT save writes `checkpoint-is-incomplete.txt` when it starts and deletes it when it finishes. Trainer does not check for that file, and `resume_from_checkpoint=True` simply takes the highest number, so inspect the newest folder and pass the previous one explicitly if the marker is still there. - **Never set `save_only_model=True` on a run you may resume.** It drops optimizer, scheduler and RNG state; the docs say the optimizer then restarts from scratch. ## Off-box copies through the Hub With `push_to_hub=True` and `hub_model_id`, `hub_strategy` decides what is uploaded. | `hub_strategy` | What reaches the Hub | |---|---| | `"end"` | The final model when `save_model()` is called | | `"every_save"` (default) | The model at each save, pushed asynchronously; checkpoint folders are not uploaded | | `"checkpoint"` | As `every_save`, plus the latest checkpoint in a `last-checkpoint` folder | | `"all_checkpoints"` | Every checkpoint folder under its own name | The docstring resumes from that copy with `trainer.train(resume_from_checkpoint="last-checkpoint")`. That string is a local path, so on a fresh machine you download the repo's `last-checkpoint` folder into the working directory first. While a push is still running, Trainer skips the next one unless `hub_always_push=True`. ## What must stay the same between the two runs The resume restores state into whatever Trainer you rebuilt, so the rebuilt run has to match the interrupted one: - **The same dataset, in the same order before shuffling.** The fast-forward skips a count of batches; if the data changed, it skips the wrong rows. - **The same batch arguments.** `per_device_train_batch_size`, `gradient_accumulation_steps` and the device count decide how many rows each skipped step stood for. - **The same model and adapter configuration.** Optimizer state is per parameter, so a different set of trainable parameters cannot take the saved state. - **The same `output_dir`** when you rely on `resume_from_checkpoint=True`, because that is where the newest folder is looked up. ## A version note Transformers v5 removed `overwrite_output_dir`. The migration guide says it had no effect on Trainer and points to `resume_from_checkpoint` instead, so a v4 script that passed it must drop the argument and decide explicitly whether to start fresh or resume.

  • The newest checkpoint folder was cut off mid-save by the kill. What does resume_from_checkpoint=True do with it?
    It takes it anyway: Trainer picks the highest step number and does not look for the `checkpoint-is-incomplete.txt` marker a JIT save leaves behind. Loading then fails, or raises "Can't find a valid checkpoint" if the weights are missing. Check the newest folder yourself and pass the previous checkpoint's path explicitly.
  • Why does save_only_model=True defeat a resume even though the weights are on disk?
    It writes weights only, without the optimizer, scheduler and RNG state files. Trainer's docs say a resume from such a checkpoint restarts the optimizer from scratch, so AdamW's moment estimates and the schedule position are gone and the run is no longer a continuation. Use it only when the checkpoint is meant for inference.
  • Your v4 script passed overwrite_output_dir=True to start clean. What do you do in Transformers v5?
    Delete the argument: v5 removed it from `TrainingArguments`, and the migration guide says it never affected Trainer. Starting fresh means a new `output_dir` or calling `train()` without `resume_from_checkpoint`; continuing means passing `resume_from_checkpoint=True` or a checkpoint path to `train()`.

A checkpoint is a full save-game, not a screenshot: the weights show where you were, but carrying on needs the inventory (optimizer), the clock (scheduler) and the dice (random state) too.

  • Reloading the saved weights with from_pretrained is the same as resuming the run.
  • resume_from_checkpoint=True automatically skips a checkpoint that was only half written.
  • save_only_model=True still lets Trainer resume with the optimizer state intact.
  • The default hub_strategy uploads every checkpoint folder to the Hub.
  • Setting resume_from_checkpoint in TrainingArguments is enough for Trainer to resume.

Assumes Transformers v5.18: overwrite_output_dir was removed in v5, and enable_jit_checkpoint is a TrainingArguments field at this release.