Repository navigation
Studio: fix training stuck at 100% when the worker will not exit - #7938
Conversation
There was a problem hiding this comment.
💡 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".
| 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): |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
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.
eb28e08 to
2181de8
Compare
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.
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
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.
87276c5 to
41f917d
Compare
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.
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.
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.
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
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.
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_completedis set and the DB row is finalized. Butis_training_active()answers on worker liveness alone:That check runs before the
is_completed/_complete_seenones below it. So if the worker emitscompleteand then wedges in GPU or interpreter teardown,/api/train/statuskeeps returningphase="training", is_training_running=trueand the/api/train/progressSSE never falls out ofwhile backend.is_training_active():, so it never sends its finalcompleteframe. 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:/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.is_run_finished(), consulted by/api/train/status, the progress SSE and/api/train/stopthrough a getattr-guarded_run_finishedhelper. A run that reported terminal is reported terminal at once, with no grace and no kill involved.UNSLOTH_STUDIO_TRAINING_COMPLETE_EXIT_GRACE_S) precisely because it no longer gates the UI.finally, after the terminal send. Flushing first looks tidier and an earlier revision of this PR did exactly that, butwandb_run.finish()routinely blocks for minutes and sometimes deadlocks, so putting it ahead ofcompletewithholds the event the UI waits on and reproduces this same bug on Apple Silicon. The watchdog grace bounds the teardown instead._finalize_stopped_after_escalationkeeps a completed run's status message instead of overwriting it with "Training stopped.". That message drives the UI banner._pump_loopsnapshots_proc. The watchdog drops the handle as its last step, so reading the attribute twice could hitNoneand kill the pump thread with anAttributeError. Pre-existing, but arming on every run would have made it routine.stop_trainingre-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_stopon a run that already saved. The status phase ladder tests that flag beforeis_completed, which reported a completed run as stopped for good.Verification
70 tests across
test_training_stop_watchdog.pyand a newtest_training_status_terminal.py, which drives the real/status,/progressSSE and/stophandlers against a worker that never exits. Every new behaviour fails on the unpatched code, the pump one with exactly theAttributeError: '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:Run on real
ubuntu-latest,windows-latestandmacos-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 cleanmain: the failing-test set is identical, so nothing here regresses.No frontend file is touched, so browser behaviour is unaffected. The
TrainingStatusresponse 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.