Skip to content

Studio: save a training checkpoint when the container is stopped - #11044

Merged
danielhanchen merged 10 commits into
unslothai:mainfrom
NilayYadav:studio-graceful-stop
Sep 16, 2026
Merged

danielhanchen merged 10 commits into
unslothai:mainfrom
NilayYadav:studio-graceful-stop

Conversation

@NilayYadav

Copy link
Copy Markdown
Collaborator

Stopping the container while a fine-tune is running loses the whole run. docker stop sends SIGTERM, and the unsloth studio command only handled Ctrl+C, so the process died at once with no cleanup. Tested on the published image with a run at step 9: the training process was dead within a second, nothing was saved, and the run was left marked as running.

This makes SIGTERM take the same path as Ctrl+C, and that path now asks the training job to stop and save (the same thing the Stop button does) and waits for it before anything is killed. The wait happens before the web server starts shutting down, because a save that overlapped the server teardown still lost the checkpoint. The wait is capped by UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S, default 120 seconds.

On the Docker side, supervisord now waits that long before killing Studio, run.sh passes a matching --stop-timeout, and the Hub page tells users to run docker stop -t 150 since Docker's own default is 10 seconds.

Same test after the change: the checkpoint and adapter were written, the run was marked stopped and can be resumed, and the container exited in under 9 seconds.

Tests cover the stop and wait logic, the shutdown order, the SIGTERM handler, and the Docker config.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-16T09:38:27.201812Z 7c51214 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d56f184a91

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

1 similar comment
@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 41b1049964

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/run.py Resolved
@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: abc66766c5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/run.py Resolved
@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: abc66766c5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 0e373d3871

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the gap in studio/backend/run.py where _graceful_shutdown never asks the training job to stop and save, so a SIGTERM loses the run, and the stop-and-wait here happens before the server teardown. Will get this reviewed.

@Lyxot Lyxot self-assigned this Sep 16, 2026
…utdown docs

The shutdown save budget is capped by the training stop watchdog's own absolute timeout, UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S (default 600). Raising UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S past it only waits longer for a worker that is force-terminated anyway, so a 700 second save is still lost at 600. Document the ceiling next to the budget and forward the watchdog variable through docker/run.sh, whose environment allowlist had dropped it, so the two can be raised together.

A host shutdown was claimed to be covered as well. It is not: the daemon stops every container under its own --shutdown-timeout (15 seconds by default), not the per-container stop timeout.

Tests: replace the source-text assertions in the Docker stop-grace tests with behavioural ones. The launcher's derived wait is read back by sourcing studio_launch.sh under an EXIT trap in check-only mode, and run.sh's environment forwarding is asserted against the stubbed docker argv in both directions. The SIGTERM handler installation is now checked on the parsed tree, so commenting out either call site fails; before, commenting out both left it green. The two shutdown-wait tests now assert the terminal condition each one names rather than only an upper time bound. Drops the ordering test that compared substring positions inside run.py: the same ordering is asserted behaviourally by test_graceful_shutdown_saves_training.
@Lyxot

Lyxot commented Sep 16, 2026

Copy link
Copy Markdown
Collaborator

Pushed 5b65dd2a3e, a review pass on top of the branch. The shutdown design is unchanged; four things were wrong or unproven.

docker/run.sh now forwards UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S. The save is not bounded only by UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S — the training stop watchdog force-terminates a worker at its own absolute cap, UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S (default 600). So UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S=900 produced --stop-timeout 930, a Studio that waited 900 seconds, and a 700-second save still killed at 600. The two knobs now travel together through the launcher's env allowlist, which had only the first, and DOCKERHUB.md states the ceiling.

The host-shutdown claim was wrong. DOCKERHUB.md said the checkpoint also survives a host shutdown. It does not: on daemon shutdown Docker stops every container under dockerd's own --shutdown-timeout (15 seconds by default), not the per-container stop timeout. Replaced with an explicit carve-out.

Three tests asserted source text rather than behaviour.

  • The launcher's derived wait is now read back by sourcing studio_launch.sh under an EXIT trap in check-only mode, parametrised over unset/0/120/0600/08, instead of grepping for the exact $(( 10#$... + 30 )) line.
  • run.sh's env forwarding is now asserted against the stubbed docker argv, in both directions — present when the host sets a variable, absent when it does not.
  • test_the_server_asks_for_a_save_before_it_kills_the_worker compared substring positions inside run.py; it is dropped, since test_graceful_shutdown_saves_training already asserts the exact call order behaviourally.

Two tests did not assert what they claimed. test_both_server_wait_loops_install_the_handler matched source text, so commenting out both _graceful_shutdown_on_sigterm() call sites left it green; it is now an ast check requiring an executed call statement before each wait loop. The two shutdown-wait tests asserted only an upper time bound, so returning True immediately after the stop request passed both; they now assert the terminal condition each name claims — the worker is gone in one, the worker still lingers and is_run_finished() is true in the other.

Every added or changed assertion was mutation-checked: the production line it covers was reverted or weakened and exactly that test failed.

One thing deliberately not changed, for a maintainer to weigh: the shutdown budget and the watchdog cap are two independent deadlines over the same save, and correctness now depends on an operator keeping them ordered. Making that structural — the watchdog has no job during shutdown, since force_terminate() runs unconditionally right after the wait, so the shutdown path could suppress its absolute cap instead of racing it — changes a training-subsystem contract the Stop button also depends on. That belongs in its own change, not this one.

@Lyxot

Lyxot commented Sep 16, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5b65dd2a3e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

stop_for_shutdown returned as soon as the worker was gone, but the pump writes the run's terminal row afterwards and _complete_seen is set before that write lands. force_terminate joins the pump for 8 seconds, while the finalize is a metrics flush plus up to three finish_run attempts on connections with a 5 second busy timeout, so a contended SQLite can outlast it. The row is then left running, and the next startup's orphan sweep rewrites it to an error; the checkpoint and its output_dir survive, the stopped status and the final metrics do not.

The success paths now go through _await_run_record, which waits out the pump inside the remaining budget. Only a worker that has exited is waited on, because the pump keeps looping while one is alive; a run whose worker lingers past its save still falls back to the join, and the docstring records why closing that too belongs with terminal-state handling rather than here.
@Lyxot

Lyxot commented Sep 16, 2026

Copy link
Copy Markdown
Collaborator

Pushed caab8919e9, which closes the run-record wait Codex flagged: stop_for_shutdown now waits out the pump's terminal DB write inside the shutdown budget, instead of returning as soon as the worker was gone and leaving that write to force_terminate's 8 second join.

Two things worth correcting on that thread, both verified by executing the code rather than reading it. The consequence is a run row that reads error instead of stopped and loses its final metrics — cleanup_orphaned_runs preserves output_dir unless resume_blocked = 1, so the checkpoint stays on disk and the run stays resumable. And the fix is partial: a run whose worker lingers past its save still falls back to the join, because the pump cannot exit while the worker is alive and the existing state cannot tell a finalize that has not started from one that started and failed. Closing that needs a monotonic signal out of the finalize paths, which the pump, the stop watchdog and two error paths share — its own change, with its own tests. It is recorded in the _await_run_record docstring.

The window is narrower than before this branch either way: on the merge base a SIGTERM during training left the row stale every time, not only under DB contention.

All review threads are resolved.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: caab8919e9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

`_image_and_cmd` in the ROCm run.sh tests walks the `docker run` argv and skips two tokens for each option it knows carries a value, one for anything else starting with a dash. Adding `--stop-timeout` to run.sh left the flag in the first group by behaviour but the second by declaration, so the walk stopped on its value and reported `150` as the image name, failing five TestRunShRocm cases.
@Lyxot

Lyxot commented Sep 16, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 7c51214f2e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Lyxot

Lyxot commented Sep 16, 2026

Copy link
Copy Markdown
Collaborator

Pushed one more commit: fix(tests): parse --stop-timeout as a flag that takes a value.

A fork CI run on this branch merged onto current main turned up five failures in tests/python/test_docker_rocm.py::TestRunShRocm that this branch introduces:

FAILED tests/python/test_docker_rocm.py::TestRunShRocm::test_rocm_passes_the_device_nodes_and_numeric_gids_not_gpus
FAILED tests/python/test_docker_rocm.py::TestRunShRocm::test_the_wrapper_option_is_only_taken_from_the_front
FAILED tests/python/test_docker_rocm.py::TestRunShRocm::test_a_later_rocm_is_not_the_wrapper_option
FAILED tests/python/test_docker_rocm.py::TestRunShRocm::test_the_env_form_selects_rocm_too
FAILED tests/python/test_docker_rocm.py::TestRunShRocm::test_a_custom_image_is_kept

AssertionError: assert '150' == 'unsloth/unsloth-rocm:latest'

_image_and_cmd walks the recorded docker run argv to find the positional tail, skipping two tokens for each option in flags_with_value and one for anything else that starts with a dash. Adding --stop-timeout "$STOP_TIMEOUT" to run.sh put a value-carrying option in the second group, so the walk stopped on its value and reported 150 as the image. Adding --stop-timeout to that set restores all five: pytest tests/python/test_docker_rocm.py -q is 38 passed, and reverting the one-line change reproduces exactly those five failures.

Nothing else on the branch regressed: the docker/studio/supervisor selection fails the same 77 tests here as unmodified main does, identical sets, all of them local flock (util-linux) is missing gaps rather than anything from this branch.

Separately, and not from this branch: tests/studio/test_pwsh_calls_use_the_shared_runner.py::test_no_test_file_spawns_powershell_directly fails the same way on unmodified main, flagging python/test_uv_requirements_path_space.py for calling subprocess.run instead of the shared pwsh runner.

A fork CI run of this branch merged onto current main, compared against a control run of unmodified main through the same workflows, leaves this branch with no failure of its own: the branch run is 71 passed / 1 failed, and that one failure is the pwsh check above, which the control run fails too.

@Lyxot Lyxot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

SIGTERM now reaches the wait loop's shutdown path on the in-process CLI route that docker stop actually uses, and the shutdown asks a live run to stop and save instead of going straight to the kill. Both halves are covered by tests that fail when the production change is reverted.

Validated on this branch merged onto current main: a full CI run is 71 passed / 1 failed, and that single failure is test_pwsh_calls_use_the_shared_runner, which a control run of unmodified main through the same workflows fails identically. The docker/studio/supervisor selection fails the same set locally on this branch as on main.

The residual discussed in the thread above still stands and is documented in _await_run_record: a worker that lingers past its save, with SQLite contended beyond the force-terminate join, leaves the run reading error rather than stopped and drops the final metrics. The checkpoint and its output_dir survive and resume works, so this is a status-label loss, not a data loss.

@danielhanchen
danielhanchen merged commit 5176306 into unslothai:main Sep 16, 2026
34 of 72 checks passed
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…lothai#11044)

* Studio: stop and save a training run on SIGTERM before exiting, and give docker stop the time for it

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Docker run.sh: validate the stop budget and read it as decimal

* Studio: stop a managed account's run under its own account on shutdown

* Studio: stop and save a diffusion training run on shutdown too

* Studio: wait for the diffusion run record even after the worker exits

* Studio: forward the training stop watchdog budget, and correct the shutdown docs

The shutdown save budget is capped by the training stop watchdog's own absolute timeout, UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S (default 600). Raising UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S past it only waits longer for a worker that is force-terminated anyway, so a 700 second save is still lost at 600. Document the ceiling next to the budget and forward the watchdog variable through docker/run.sh, whose environment allowlist had dropped it, so the two can be raised together.

A host shutdown was claimed to be covered as well. It is not: the daemon stops every container under its own --shutdown-timeout (15 seconds by default), not the per-container stop timeout.

Tests: replace the source-text assertions in the Docker stop-grace tests with behavioural ones. The launcher's derived wait is read back by sourcing studio_launch.sh under an EXIT trap in check-only mode, and run.sh's environment forwarding is asserted against the stubbed docker argv in both directions. The SIGTERM handler installation is now checked on the parsed tree, so commenting out either call site fails; before, commenting out both left it green. The two shutdown-wait tests now assert the terminal condition each one names rather than only an upper time bound. Drops the ordering test that compared substring positions inside run.py: the same ordering is asserted behaviourally by test_graceful_shutdown_saves_training.

* Studio: wait for the training run record before the shutdown kill

stop_for_shutdown returned as soon as the worker was gone, but the pump writes the run's terminal row afterwards and _complete_seen is set before that write lands. force_terminate joins the pump for 8 seconds, while the finalize is a metrics flush plus up to three finish_run attempts on connections with a 5 second busy timeout, so a contended SQLite can outlast it. The row is then left running, and the next startup's orphan sweep rewrites it to an error; the checkpoint and its output_dir survive, the stopped status and the final metrics do not.

The success paths now go through _await_run_record, which waits out the pump inside the remaining budget. Only a worker that has exited is waited on, because the pump keeps looping while one is alive; a run whose worker lingers past its save still falls back to the join, and the docstring records why closing that too belongs with terminal-state handling rather than here.

* fix(tests): parse --stop-timeout as a flag that takes a value

`_image_and_cmd` in the ROCm run.sh tests walks the `docker run` argv and skips two tokens for each option it knows carries a value, one for anything else starting with a dash. Adding `--stop-timeout` to run.sh left the flag in the first group by behaviour but the second by declaration, so the walk stopped on its value and reported `150` as the image name, failing five TestRunShRocm cases.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Lyxot <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants