Skip to content

Studio: fix training stuck at 100% when the worker will not exit - #7938

Merged
danielhanchen merged 17 commits into
mainfrom
studio-training-stuck-at-100
Aug 6, 2026
Merged

danielhanchen merged 17 commits into
mainfrom
studio-training-stuck-at-100

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 5, 2026 •

Copy link
Copy Markdown
Member

Fixes #7897.

The bug

A training run that finishes on its own has already done everything that matters by the time the worker emits its terminal event: the model, tokenizer and adapter config are on disk, is_completed is set and the DB row is finalized. But is_training_active() answers on worker liveness alone:

if self._proc is not None and self._proc.is_alive():
    return True

That check runs before the is_completed / _complete_seen ones below it. So if the worker emits complete and then wedges in GPU or interpreter teardown, /api/train/status keeps returning phase="training", is_training_running=true and the /api/train/progress SSE never falls out of while backend.is_training_active():, so it never sends its final complete frame. The progress bar sits at 100% indefinitely.

Pressing "Stop and Save" was the only way out because _start_stop_watchdog, which force-terminates a stuck worker, had a single call site: stop_training. The exported model was valid afterwards because it had been saved before the hang; the stop only reaped the zombie.

Reported on Windows 10 with an RX 7900 XTX on ROCm, and intermittent, which fits a lingering process exit after GPU teardown.

The fix

is_training_active() was answering two different questions with one number:

  1. is a run in progress (status, progress stream, stop)
  2. is the GPU still occupied by a training worker (admission guards for inference, image and video generation, diffusion start, transformers install, /train/start)

After a terminal event the answer to 1 is definitively no, while 2 stays yes until the process exits. So:

  • is_training_active() is unchanged, still liveness-based, and every one of the 15 admission call sites keeps its exact previous answer. A lingering worker still holds its VRAM and must keep blocking new GPU work.
  • New is_run_finished(), consulted by /api/train/status, the progress SSE and /api/train/stop through a getattr-guarded _run_finished helper. A run that reported terminal is reported terminal at once, with no grace and no kill involved.
  • The watchdog is now armed on any terminal event, not just a user stop, purely as a backstop so a wedged worker cannot hold the GPU forever. Its grace is a generous 120s (UNSLOTH_STUDIO_TRAINING_COMPLETE_EXIT_GRACE_S) precisely because it no longer gates the UI.
  • The MLX path is deliberately left alone. Its TensorBoard/W&B teardown stays in the trailing finally, after the terminal send. Flushing first looks tidier and an earlier revision of this PR did exactly that, but wandb_run.finish() routinely blocks for minutes and sometimes deadlocks, so putting it ahead of complete withholds the event the UI waits on and reproduces this same bug on Apple Silicon. The watchdog grace bounds the teardown instead.
  • _finalize_stopped_after_escalation keeps a completed run's status message instead of overwriting it with "Training stopped.". That message drives the UI banner.
  • _pump_loop snapshots _proc. The watchdog drops the handle as its last step, so reading the attribute twice could hit None and kill the pump thread with an AttributeError. Pre-existing, but arming on every run would have made it routine.
  • A terminal error or an unrecoverable download stall signals an in-flight stop watchdog. Arming again is a no-op while a watchdog already watches that worker, so without the signal it sat out the 600s save backstop with the GPU still held.
  • stop_training re-tests terminal under its own lock. The route's check and the backend's mutation are separate reads, so a run that finishes in between would latch _should_stop on a run that already saved. The status phase ladder tests that flag before is_completed, which reported a completed run as stopped for good.

Verification

70 tests across test_training_stop_watchdog.py and a new test_training_status_terminal.py, which drives the real /status, /progress SSE and /stop handlers against a worker that never exits. Every new behaviour fails on the unpatched code, the pump one with exactly the AttributeError: 'NoneType' object has no attribute 'is_alive' it predicts.

Beyond the unit tests, the change was exercised by a simulation suite covering the lifecycle state machine, real spawn subprocesses (normal exit, wedged, slow teardown, crash, hard crash), the [Linux, Windows, WSL, macOS] x [NVIDIA, AMD/ROCm, CPU-only] matrix, and concurrency races between the pump, the watchdog and reset. Two results are worth calling out:

  • With the watchdog disarmed entirely, the UI still unsticks. The fix does not depend on the kill.
  • A worker with a slow but legitimate teardown exits on its own with exitcode 0 and is never force-killed.

Run on real ubuntu-latest, windows-latest and macos-14 (Apple Silicon) runners, all green, with the UI unsticking in 0.07s to 0.12s on all three. The full backend suite was also run on this branch and on clean main: the failing-test set is identical, so nothing here regresses.

No frontend file is touched, so browser behaviour is unaffected. The TrainingStatus response shape is unchanged, the backend surface is additive (is_run_finished; the watchdog helpers only gained optional keyword arguments), and the new env var falls back to its default when absent, so existing installs are unaffected.

Note

The log attached to the issue captures a successful session, so the hang itself is not in it. The root cause is from reading the code path the report describes, not a live repro of a wedged ROCm teardown.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@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: eb28e08f33

ℹ️ 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/routes/training.py Outdated
if backend._cancel_requested:
# Cancel (save=False) requested — force-terminate to reset immediately.
logger.info("Force-terminating subprocess for immediate reset (cancel path)")
if backend._cancel_requested or _run_finished(backend):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Defer reset until DB finalization is complete

When a terminal event has made _run_finished(backend) true but the pump is still creating/finalizing the run row, this branch lets Reset proceed immediately. force_terminate() only waits a bounded 8s for the pump; if SQLite/storage is still blocked, the reset then clears progress and histories while the pump can later snapshot those cleared values (or skip finalization after a new start changes current_job_id), leaving the just-completed run with lost final step/loss/history. Gate this path on the terminal DB finalize being claimed/finished, or preserve a terminal snapshot before clearing runtime state.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not reproducible against the code as written. _finalize_run_in_db snapshots run_id, final_step, final_loss, duration and loss_history inside with self._lock: and claims _run_finalized there, before any DB I/O (training.py, the block above _flush_metrics_to_db); the retry loop then operates purely on that snapshot, so a later _update_progress cannot reach the write. I did reproduce the shape you describe, but only against a stub that snapshotted after the block, which is not what the real code does. The remaining window is between the complete handler releasing the lock and the finalize taking it, and force_terminate joins the worker (5s) before the pump, so the pump has that whole join to reach its snapshot. The reset branch is removed in 9b02694 regardless.

danielhanchen and others added 5 commits August 5, 2026 16:06
A run that finishes on its own emits its terminal event, saves the model and
finalizes the DB row, but is_training_active() reports on worker liveness alone.
If the worker then wedges in GPU/interpreter teardown, /status keeps saying
"training" and the /progress SSE never sends its final "complete", so the bar
sits at 100% forever. Only "Stop and Save" unstuck it, because the escalation
watchdog was armed solely by stop_training.

Arm the same watchdog when the pump sees a terminal event, on its own longer
grace, and keep a completed run's status message through the escalation instead
of relabelling it "Training stopped.". Also snapshot _proc in the pump loop: the
watchdog drops the handle as its last step, and reading it twice raised
AttributeError and silently killed the pump thread.
Reaping a wedged worker unwedged the UI, but it made the UI depend on a kill, and a
post-run wandb sync can legitimately run for minutes after the terminal event. Cutting
that short to unstick a progress bar is the wrong trade.

Split the two questions is_training_active() was answering. It stays exactly as it was,
liveness-based, for the GPU admission guards, since a lingering worker still holds its
VRAM. Status and the progress SSE now also consult a new is_run_finished(), so a run that
reported terminal shows as completed at once instead of after a grace. The watchdog stays
as a backstop that reclaims the GPU, on a longer 120s grace it no longer gates the UI on.

Reset now reaps a finished-but-lingering worker rather than returning 409, so returning
to configuration right after a run works instead of failing for the length of the grace.
…his router

The progress and status routes read the backend defensively via getattr because
stand-in backends get passed in, and calling is_run_finished() directly broke six
existing progress-stream tests with AttributeError. Route the three call sites
through a _run_finished helper that falls back to the old liveness-only behaviour
when the method is absent.
@danielhanchen
danielhanchen force-pushed the studio-training-stuck-at-100 branch from eb28e08 to 2181de8 Compare August 5, 2026 16:09
danielhanchen and others added 3 commits August 6, 2026 01:10
Stop was the one run-state surface still keyed on raw worker liveness, so a Stop
landing in the 3s status-poll window right after a run finished latched _should_stop
and overwrote the finished banner with "Stopping training and saving checkpoint...".
Nothing clears that afterwards, so a saved run reported as stopped for good. Read it
the same way /status and the progress SSE do.

Revert the reset branch that reaped a finished-but-lingering worker. It was justified
by returning to configuration being blocked after a run, but the only caller of
/api/train/reset is the start overlay, which mounts solely while starting, preparing,
or waiting for the first step, and reaches reset only after a cancel. A completed run
never renders it, so the path it fixed is unreachable and reset keeps its old behaviour.

Flush the MLX tracking teardown before every terminal send. The parent arms its exit
watchdog on the terminal event, so the TensorBoard close and wandb finish that ran in
the trailing finally could be force-terminated mid-flush. Both closes are idempotent
and the helper is now guarded, so the trailing call is a no-op.

@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: cf16a019ac

ℹ️ 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".


is_active = backend.is_training_active()
# A run still tearing down is not training: report terminal without waiting on exit.
is_active = backend.is_training_active() and not _run_finished(backend)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Separate terminal display state from resource availability

When a completed or failed worker remains alive during the configured 120-second teardown grace, this reports is_training_running=false even though the backend deliberately still considers the worker active because it may hold VRAM. The frontend uses that field to enable Configure (studio-page.tsx:193) and terminal export actions (progress-section.tsx:154-158), but a new training start is then rejected by the live-process guard in TrainingBackend.start_training() (training.py:863-865), and other GPU admission guards likewise still refuse work. Expose a separate resource-busy/admission state, or keep those actions disabled until the worker is reaped, so the newly terminal-looking UI does not offer operations the backend rejects.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Deliberate, and I think the alternative is worse. Keeping those actions disabled until the worker is reaped is the pre-PR behaviour, which is exactly the hang being fixed: the UI stays locked for as long as the worker wedges, which is unbounded. The window is normally about 2s (the worker exits on its own) and is bounded by the grace only in the wedge case, versus forever today. A start attempt inside it is refused with a clear message that surfaces as a toast, so nothing is lost and a retry works. The other option, a separate resource-busy field, means a new response field plus frontend work; this PR deliberately keeps the TrainingStatus shape unchanged so existing installs are unaffected. Worth doing as its own change if you want the Start button to reflect admission state, but not as part of this fix.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
danielhanchen and others added 2 commits August 6, 2026 01:27
An unrecoverable download stall sets progress.error directly and returns from
_handle_event before the terminal-event arming, so it made is_run_finished() true
without a backstop. terminate() is only a request, so a worker that ignores it kept
the GPU while the UI had already moved on and every later start hit the live-proc
guard. Arm the same watchdog there. The recoverable Xet path still respawns untouched.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen
danielhanchen force-pushed the studio-training-stuck-at-100 branch from 87276c5 to 41f917d Compare August 6, 2026 01:50
A stop already watching this proc makes the terminal-event arming a no-op, so a run
that then failed with an error rather than completing left _complete_seen unset and
the existing watcher waited out the whole save backstop, 600s by default, with the
GPU and every admission guard still blocked. A terminal error has nothing left to
save either, so set _complete_seen there and let the watcher drop to its grace.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two follow-ups on the stuck-at-100% fix.

The MLX path was flushing TensorBoard and W&B before each "complete" send so
the new exit watchdog could not cut a sync short. That is backwards:
wandb_run.finish() routinely blocks for minutes and can deadlock, so putting
it in front of the send withholds the very event the UI waits on, which is the
hang this change exists to end. Teardown moves back into the finally, after the
send, and the watchdog's grace bounds it instead.

An unrecoverable download stall also failed to signal a stop watchdog already
watching the same worker, since arming again is a no-op for a live watcher.
Without the terminal signal it sat out the 600s save backstop with the GPU
still held. It now sets the same flag the error path does.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 6, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The route's terminal check and the backend's stop are separate reads, so the pump
can finish the run in between. The stop then latches _should_stop on a run that
already saved, and /status tests trainer_stopped before is_completed, so the run
reports as "stopped" with a "Stopping training..." banner nothing clears, while
the DB row says completed.

The pump publishes terminal state under the backend lock, so the re-test belongs
in the same locked block as the mutation it guards. Scoped to save=True: the
cancel branch has its own terminal guard and has already mutated by that point.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 1b397fcbcd

ℹ️ 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 added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 95b9d8eb90

ℹ️ 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
danielhanchen merged commit fa40b0b into main Aug 6, 2026
50 of 51 checks passed
@danielhanchen
danielhanchen deleted the studio-training-stuck-at-100 branch August 6, 2026 06:45
danielhanchen added a commit to Sneakr/unsloth that referenced this pull request Aug 6, 2026
Two files conflicted, both against unslothai#7938 (training stuck at 100% when the worker
will not exit). unslothai#7938 patched the stop, status and progress-SSE routes inline;
this branch had already refactored the same routes into helpers, so the fix is
ported into the refactor rather than either side taken whole.

core/training/training.py: took unslothai#7938's terminal status_message handling.

routes/training.py: kept the refactored structure and reintroduced the
terminal-awareness through one _run_active helper, used by stop, /status and
both progress-SSE liveness reads. The two GPU admission guards deliberately keep
using is_training_active(), per unslothai#7938: a worker still winding down is still
holding its VRAM.

Two things the textual merge could not see:

_run_finished_locked came in reading self._start_in_progress. main has both that
flag and _spawn_in_progress; this branch replaced the former with the spawn
reservation, so the merged code raised AttributeError and took all 10 stop
watchdog tests with it. It now tests _spawn_in_progress and _new_job_spawn_id,
the same pair is_training_active() tests.

_training_status_identity called backend.status_start_request() unguarded while
getattr-guarding every other backend read, so unslothai#7938's stand-in backend test
500'd the status route. Guarded like the rest.

test_training_status_terminal.py and test_training_stop_watchdog.py updated for
this branch's stop_training(expected_job_id=) signature and spawn reservation.

67 tests across both of unslothai#7938's files pass.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Unsloth Studio Desktop Stuck @ 100% when training completes.

1 participant