Repository navigation
Studio: keep third-party progress bars and raw trainer prints out of the structured log - #8311
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e1ad1a1662
ℹ️ 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".
| ) | ||
|
|
||
| # Silence third-party tqdm bars; they carry no signal and corrupt JSON records. | ||
| quiet_third_party_progress_bars() |
There was a problem hiding this comment.
Preserve Hub upload progress in export workers
This call runs in every process using LogConfig, including core/export/worker.py, where stdout/stderr is deliberately forwarded to the export dialog after _handle_export opens the log gate. Consequently huggingface_hub.disable_progress_bars() also suppresses the only live file/byte progress from HfApi.upload_folder and the various push_to_hub* paths during potentially long exports; the replacement events mentioned here cover inference downloads/model loads, not export uploads. Scope this suppression away from the export worker or provide equivalent structured upload progress there.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, the export worker is the one process whose stdout is a user-facing progress stream. It calls allow_progress_bars() and setup_logging(quiet_progress_bars = False), and the default is now tagged with UNSLOTH_STUDIO_PROGRESS_BARS_DEFAULTED so an operator-set value is still respected there.
| return | ||
|
|
||
| try: | ||
| from huggingface_hub.utils import disable_progress_bars |
There was a problem hiding this comment.
Avoid importing Hub before activating the Transformers sidecar
In the training, inference, and export subprocesses, LogConfig.setup_logging() runs before activate_transformers_for_subprocess(), so this import caches the base environment's huggingface_hub before the selected sidecar is prepended to sys.path. The activation function assumes no ML packages have been imported and does not purge modules; on supported Python 3.9, for example, the base environment pins Hub 0.36.2 while the Transformers 5.x sidecars pin Hub 1.8.0, leaving the sidecar Transformers process using an incompatible cached Hub module and potentially failing model loads. Only call the API when Hub is already present, or defer it until after sidecar activation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, and the docstring claimed the opposite. The Hub API is only called when huggingface_hub is already in sys.modules; otherwise the env var alone does the job, which is what a later import reads anyway.
| # map() calls that draw them. | ||
| try: | ||
| from loggers.config import quiet_third_party_progress_bars | ||
| quiet_third_party_progress_bars() |
There was a problem hiding this comment.
Preserve structured dataset-formatting progress
For non-streaming chat datasets, utils/datasets/chat_templates.py derives the existing structured formatting status updates by polling the dataset.map() tqdm instance and forwarding its count through progress_callback. Disabling the datasets progress bar immediately before that map prevents the disabled tqdm object from appearing in the monitored _instances set, so large formatting jobs now remain at the initial “Formatting dataset” status until completion. Replace that monitor with progress independent of tqdm, or retain an in-memory bar while suppressing only its output.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed by experiment: with bars on, the map bar shows up in tqdm._instances with n advancing; with datasets' disable_progress_bar() it never registers, so the status would freeze. datasets is no longer disabled, its bar is pointed at a null stream instead, so the counter chat_templates polls stays live and the log stays clean.
| """ | ||
| if os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS") is None: | ||
| os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1" | ||
| elif os.environ["HF_HUB_DISABLE_PROGRESS_BARS"].strip().lower() in ("0", "false", ""): |
There was a problem hiding this comment.
Honor all false values in the progress-bar override
Hugging Face parses HF_HUB_DISABLE_PROGRESS_BARS as true only for 1, ON, YES, or TRUE, so common explicit false values such as no and off request that bars remain enabled. This condition recognizes only 0, false, and the empty string; during a diffusion load with HF_HUB_DISABLE_PROGRESS_BARS=off, for example, the function proceeds to diffusers.utils.logging.disable_progress_bar() and overrides the operator's setting. Match Hugging Face's boolean parsing before invoking any of the library-specific disable APIs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed. The parse now uses the Hub's own true set (1/on/yes/true), so off and no mean keep the bars.
| return | ||
| for callback_cls in (PrinterCallback, ProgressCallback): | ||
| try: | ||
| trainer.remove_callback(callback_cls) |
There was a problem hiding this comment.
Retain non-duplicate Trainer summary metrics
On every non-verbose run, removing PrinterCallback also removes the only publication of the final train_samples_per_second, train_steps_per_second, total_flos, memory, and evaluation runtime/throughput metrics produced by Trainer. Studio's replacement callback only copies loss, learning rate, epoch, gradient norm, token count, and eval_loss into TrainingProgress, so these summary values are not among the supposedly duplicated data and disappear from the run log entirely. Keep stdout quiet, but emit the remaining Trainer metrics through a structured callback before removing the printer.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fair, those numbers appeared nowhere else. on_log now publishes the Trainer summary record structurally as a trainer summary event with train_samples_per_second, train_steps_per_second, total_flos and the eval runtime fields.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b60793d5f2
ℹ️ 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 os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS") is None: | ||
| os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1" |
There was a problem hiding this comment.
Let verbose mode preserve third-party progress bars
When Studio is started with unsloth studio --verbose and the operator has not explicitly set HF_HUB_DISABLE_PROGRESS_BARS, the CLI sets only the two access-log variables, then server startup reaches this branch and permanently sets the Hub flag to 1. That value is inherited by training workers, whose later formatting helper also disables the datasets API, so verbose mode restores the Trainer callbacks but still suppresses Hub, datasets, and diffusers progress—the opposite of the advertised “restore all” behavior. Make this default suppression conditional on the verbose signal as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, that was inconsistent with what --verbose advertises. The default is skipped entirely when both access-log windows are zeroed and the operator has not set the flag themselves.
| s_per_step = round(elapsed / step, 3) | ||
| if tokens: | ||
| tok_per_s = round(tokens / elapsed, 1) |
There was a problem hiding this comment.
Exclude checkpoint history from resumed-run throughput
On a run started with resume_from_checkpoint, Transformers restores state.global_step and num_input_tokens_seen, while training_start_time and therefore elapsed_seconds start fresh in the new worker. The first progress line consequently divides a few seconds of resumed execution by all steps and tokens completed before the checkpoint; resuming at step 1000 can report roughly one-thousandth of the real seconds-per-step and an enormous token rate. Seed a resume baseline or omit throughput until two progress samples from the current process are available.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, the counters are restored from the checkpoint while the clock is not. The first-line run average is skipped when the run was started with resume_from_checkpoint; the next line has a real interval and reports normally.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8b64b7f4a9
ℹ️ 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".
| from loggers.config import quiet_third_party_progress_bars | ||
| quiet_third_party_progress_bars() |
There was a problem hiding this comment.
Move dataset-bar suppression before early formatting branches
When training in raw-text/CPT or audio-VLM mode, this suppression is never reached: the raw branch calls prepare_raw_text_dataset(), which runs Dataset.filter() and an EOS-appending Dataset.map(), while _format_audio_vlm_dataset() also runs Dataset.map(), and both branches return above this block. Large datasets in either mode therefore still emit Filter:/Map: tqdm output into the structured worker log and can corrupt adjacent JSON records. Invoke the helper before these branches (ideally before the first dataset operation) instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, both branches return before that point. The call moved up to the last spot common to every branch, before the audio preprocessors, the raw-text filter/map and the audio-VLM formatter.
| from huggingface_hub.utils import disable_progress_bars | ||
| disable_progress_bars() |
There was a problem hiding this comment.
Reapply Hub suppression after helper precaching
When optional helper-model precaching is enabled, this API suppression is later undone by utils/datasets/llm_assist.py::precache_helper_gguf(), whose finally block unconditionally calls enable_progress_bars(). In the inspected server startup path, route imports load huggingface_hub before LogConfig.setup_logging(), so Hub cached the progress environment as unset; setting the environment here does not stop that later API call from globally re-enabling bars. After precaching finishes, subsequent in-process Hub downloads can therefore write tqdm output into structured logs again. Preserve and restore the prior Hub state in the precache helper, or reapply this suppression afterward.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, that finally was unconditional. precache_helper_gguf now records whether bars were already off and only re-enables them if it was the one that turned them off.
| from loggers.config import quiet_third_party_progress_bars | ||
|
|
||
| quiet_third_party_progress_bars() |
There was a problem hiding this comment.
Apply Diffusers suppression to the other pipeline loaders
This lazy-import fix only covers image diffusion loads. core/inference/video.py::VideoBackend.load_pipeline() separately imports Diffusers and invokes pipeline from_pretrained() without calling this helper, and the spawned diffusion-training path imports its Diffusers trainers directly without running LogConfig.setup_logging() or this helper. Because Diffusers does not honor HF_HUB_DISABLE_PROGRESS_BARS, video inference and diffusion LoRA model loads can still emit component-loading tqdm output into the server's structured stream. Apply the same post-import suppression at those entry points as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fair, the lazy fix only covered the image pipeline. VideoBackend.load_pipeline calls the same helper right after its diffusers import.
8b64b7f to
1a7e231
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2dc93b516a
ℹ️ 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 "datasets" not in sys.modules: | ||
| return | ||
| try: | ||
| from datasets.utils.tqdm import tqdm as bar_cls |
There was a problem hiding this comment.
Silence the direct VLM conversion bars
This only redirects datasets.utils.tqdm.tqdm, but the same formatting flow calls utils/datasets/format_conversion.py, whose sequential local/embedded VLM and ShareGPT-image branches import generic tqdm directly and draw Converting VLM samples / Converting ShareGPT+image bars. Those supported dataset inputs therefore still write carriage-return fragments beside the training worker's structured records, preserving the corruption this change is intended to prevent; route those explicit bars to the null stream or through the shared quiet wrapper as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, those are our own bars so no library switch reaches them. Both conversion loops take a shared kwargs helper that points them at the null stream while keeping the counter, matching what the datasets bar does.
| def _drop_hf_stdout_callbacks(trainer) -> None: | ||
| """Remove HF's stdout progress callbacks from an already-built trainer. | ||
|
|
||
| `disable_tqdm=True` only swaps ProgressCallback for PrinterCallback, which prints a | ||
| raw dict per step instead (`{'loss': '0.5684', 'grad_norm': ..., 'epoch': ...}`). |
There was a problem hiding this comment.
Silence the embedding Trainer callbacks too
For embedding training, core/training/worker.py::_run_embedding_training bypasses UnslothTrainer: its SentenceTransformerTrainingArguments omit disable_tqdm, and the constructed SentenceTransformerTrainer never passes through this callback-removal helper. Consequently embedding runs still install the default HF progress callback and emit a tqdm bar into the same structured worker log despite already having _create_embedding_progress_callback; apply the quiet/verbose behavior to this trainer path too.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, _run_embedding_training bypasses UnslothTrainer. It now sets disable_tqdm from the same helper and runs the callback removal on the SentenceTransformerTrainer.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ce2552c6bd
ℹ️ 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".
| # can land mid-record on a structlog JSON line. Idempotent and cheap. | ||
| from loggers.config import quiet_third_party_progress_bars | ||
|
|
||
| quiet_third_party_progress_bars() |
There was a problem hiding this comment.
Apply progress suppression in the diffusion-training child
Although the video loader now invokes this helper, the separately spawned diffusion-training path still does not: _run_diffusion_child imports diffusion_lora_trainer, whose SDXL and DiT trainers call Diffusers from_pretrained() without configuring logging or invoking quiet_third_party_progress_bars(). During diffusion LoRA model loading, Diffusers can therefore still write component-loading bars directly to the inherited server stdout and interleave them with structured records. Invoke the helper in that child after Diffusers is imported and before any pipeline load.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, that child never runs setup_logging. It calls the helper after the trainer import and before any pipeline load now.
| # disable_tqdm only swaps ProgressCallback for PrinterCallback, which prints a | ||
| # raw dict per step instead; both write to the same stdout. | ||
| _drop_hf_stdout_callbacks(trainer) |
There was a problem hiding this comment.
Republish summary metrics for embedding training
For embedding runs, removing the stdout callbacks here also removes the final Trainer record containing train_runtime, samples/steps per second, total_flos, and memory metrics. The newly added structured summary handling exists only in UnslothTrainer._create_progress_callback; the separate _create_embedding_progress_callback.on_log forwards only loss, learning rate, gradient norm, token count, and eval loss. Consequently those end-of-run metrics still disappear specifically for embedding training, so this callback should publish the summary record before the printer is removed.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, the embedding callback is separate. It publishes the same trainer summary line, reusing the key list from the trainer module.
| for callback_cls in (PrinterCallback, ProgressCallback): | ||
| try: | ||
| trainer.remove_callback(callback_cls) |
There was a problem hiding this comment.
Preserve structured evaluation progress
When evaluation is enabled and the eval dataloader is slow or large, removing ProgressCallback eliminates the only per-batch evaluation progress: Studio's replacement callback implements on_log but not on_prediction_step, and the next eval log is emitted only after the whole evaluation finishes. A long VLM or audio evaluation can therefore leave both the UI status and structured log apparently stalled until completion. Keep stdout quiet, but replace the removed callback's evaluation counter with structured progress events.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fair, that bar was the only sign a long evaluation was moving. The replacement callback implements on_prediction_step and publishes the batch count as UI status plus one throttled structured line every 15s.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c8c20d1b24
ℹ️ 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".
| def on_evaluate(self, args, state, control, **kwargs): | ||
| type(self)._eval_seen = 0 | ||
| type(self)._eval_last_report = 0.0 |
There was a problem hiding this comment.
Restore training status when evaluation ends
After an intermediate evaluation, the UI remains stuck on the last Evaluating... message while training resumes. on_prediction_step publishes that non-empty status, but the worker and parent deliberately ignore subsequent empty status_message values, and this end-of-evaluation callback only resets counters. Publish Training in progress... (or another post-evaluation status) from on_evaluate so the displayed phase reflects the resumed training loop.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, an empty status is ignored downstream on purpose, so the UI would have stayed on Evaluating for the rest of the run. on_evaluate hands it back to "Training in progress..." when it had published an evaluation status.
| s_per_step = round(elapsed / step, 3) | ||
| if tokens: | ||
| tok_per_s = round(tokens / elapsed, 1) |
There was a problem hiding this comment.
Start first-line throughput at actual training
For embedding runs, elapsed_seconds starts before importing libraries, downloading/loading the model, and loading the dataset (worker.py initializes training_start_time at the beginning of _run_embedding_training). Consequently this first-line calculation can divide many minutes of setup by the first training step and report an extremely slow s_per_step and token rate for up to the next 30-second log interval. Seed the throughput clock when trainer.train() begins or omit the first average until an in-training interval exists.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, and it is the same shape as the resume case: elapsed_seconds is wall time since the worker started, so it covers imports, the model load and the dataset build. The first line now reports no rate at all and the second one measures a real in-training interval, which also subsumes the resume guard, so that flag is gone.
| if "datasets" not in sys.modules: | ||
| return |
There was a problem hiding this comment.
Reapply dataset suppression in embedding workers
In an embedding training worker, setup_logging() reaches this return before _run_embedding_training lazily imports datasets, and that separate training path never invokes quiet_third_party_progress_bars() afterward. Its subsequent local JSON/CSV/Parquet and Hub load_dataset() calls can therefore still emit datasets bars such as Generating train split into the structured worker log. Reapply the helper immediately after the embedding libraries are imported and before loading the dataset.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, that path never called it. The helper runs right after the embedding imports and before load_dataset now.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0e4fa9e5d2
ℹ️ 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".
| from loggers.config import quiet_third_party_progress_bars | ||
| quiet_third_party_progress_bars() |
There was a problem hiding this comment.
Move Diffusers suppression after the actual import
For diffusion-training jobs, this helper runs while diffusers is still absent from sys.modules: importing diffusion_lora_trainer only defines the entrypoints, while the actual from diffusers ... statements occur locally inside run_diffusion_lora_training() at core/training/diffusion_lora_trainer.py:305-310 (and similarly inside the DiT entrypoint). Since quiet_third_party_progress_bars() only calls the Diffusers API for an already-imported module and Diffusers does not honor the Hub environment flag, its pipeline-loading bars remain enabled in this spawned child and can still pollute the inherited server output. Fresh evidence in the current revision is that the new helper call still precedes those local Diffusers imports rather than following them.
Useful? React with 👍 / 👎.
| return | ||
| cls._eval_last_report = now | ||
| where = f"{cls._eval_seen:,}" + (f"/{total:,}" if total else "") | ||
| trainer_ref._update_progress(status_message = f"Evaluating... {where} batches") |
There was a problem hiding this comment.
Avoid replaying stale metrics for evaluation status
When evaluation follows a logged training step, TrainingProgress still contains the previous loss, learning rate, gradient norm, and possibly the previous evaluation loss, so this status-only _update_progress() invokes _create_trainer_progress_callback() with those stale values. Its predicate at core/training/worker.py:4521-4540 consequently emits another full progress event, and TrainingBackend appends that event to the metric histories and persistence buffer without deduplicating the step. Long evaluations therefore add duplicate training points every 15 seconds, and later evaluations can repeatedly record an old eval_loss; publish evaluation status separately or prevent status-only updates from entering the metric callback.
Useful? React with 👍 / 👎.
| # own dataset operations and return before the chat-template path. | ||
| try: | ||
| from loggers.config import quiet_third_party_progress_bars | ||
| quiet_third_party_progress_bars() |
There was a problem hiding this comment.
Silence dataset bars before loading the dataset
For ordinary LLM/VLM training, this suppression runs only after the dataset has already been loaded: local JSON/CSV/Parquet inputs call load_dataset() at lines 2485 and 2501, and the normal Hub path calls it at line 2638. Those operations can emit Generating train split, download, and extraction bars, while datasets ignores HF_HUB_DISABLE_PROGRESS_BARS, so they still write into the structured worker stream before this helper is reached. Fresh evidence in the current revision is that importing UnslothTrainer at core/training/worker.py:3863 has already imported datasets, making it possible to apply this helper before _load_training_dataset() rather than after all of its load operations.
Useful? React with 👍 / 👎.
|
@codex review |
…the structured log tqdm writes with carriage returns to a stream with no line discipline against the structlog writer, so a bar lands mid-record and the JSON line stops being parseable. The bars are quieted rather than disabled wherever something reads them: datasets and our own conversion bars are redirected to a null stream so the counter the UI status poller reads stays alive, the training worker keeps its bars countable for the same reason, and the export worker keeps drawing them because its dialog streams them. HF's stdout callbacks are dropped and what they carried is republished structurally: a trainer summary event with runtime, samples and steps per second, total_flos and memory, s_per_step and tok_per_s on training_progress, and throttled evaluation progress.
c596b5d to
b21a59a
Compare
Log reduction in Studio is several PRs deep (#6377, #7087, #8310, #8311) and every round started the same way: someone noticed a log was huge, measured it, and trimmed it. Nothing stopped the next chatty endpoint, and nothing told the author they had added one. Five guards, all CPU-only, no network, no sleeping. A 30 minute idle session and a 5 minute in-flight session are replayed through the real LoggingMiddleware against a virtual clock, so a thirty minute scenario runs in a second and lands identically on a loaded runner. budget lines per class against a formula of the poll period and the dedup window, plus an envelope on the whole scenario classify a path cannot be quieted without recording how often it is polled, and cannot be polled without being classified signal failures and mutations log at every interval, and the scenario is proved to have exercised the real middleware before any count from it is trusted parity one JSON fixture defines a successful access record for both the backend and the desktop shell bounds every log family prunes, and the two line caps agree The signal guard is the point. An upper bound on log lines is satisfied just as well by a middleware that was never mounted, a logger replaced with a no-op, a scenario that stopped issuing requests, or an error log someone deleted to get under the number. Each of those now fails. Two ledgers record what is already broken rather than weakening the rules to accommodate it: /api/settings/remote-access and /api/liveness sit in the 300ms burst class and write a line per poll, and the llama-server and diffusion-server directories never prune. Both ledgers are self-expiring, so fixing an entry forces its removal. Verified by mutation: eight deliberate breakages, each turning exactly the intended guard red.
* Studio: guard log volume in CI so it cannot regress unnoticed Log reduction in Studio is several PRs deep (#6377, #7087, #8310, #8311) and every round started the same way: someone noticed a log was huge, measured it, and trimmed it. Nothing stopped the next chatty endpoint, and nothing told the author they had added one. Five guards, all CPU-only, no network, no sleeping. A 30 minute idle session and a 5 minute in-flight session are replayed through the real LoggingMiddleware against a virtual clock, so a thirty minute scenario runs in a second and lands identically on a loaded runner. budget lines per class against a formula of the poll period and the dedup window, plus an envelope on the whole scenario classify a path cannot be quieted without recording how often it is polled, and cannot be polled without being classified signal failures and mutations log at every interval, and the scenario is proved to have exercised the real middleware before any count from it is trusted parity one JSON fixture defines a successful access record for both the backend and the desktop shell bounds every log family prunes, and the two line caps agree The signal guard is the point. An upper bound on log lines is satisfied just as well by a middleware that was never mounted, a logger replaced with a no-op, a scenario that stopped issuing requests, or an error log someone deleted to get under the number. Each of those now fails. Two ledgers record what is already broken rather than weakening the rules to accommodate it: /api/settings/remote-access and /api/liveness sit in the 300ms burst class and write a line per poll, and the llama-server and diffusion-server directories never prune. Both ledgers are self-expiring, so fixing an entry forces its removal. Verified by mutation: eight deliberate breakages, each turning exactly the intended guard red. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: fail CI when the app polls a path the log budget never declared The budget suite compares two backend files against each other: the suppression sets in loggers/handlers.py and the poll cadences in log_budget/session.py. A pull request that adds a polling call site in the frontend edits neither, so nothing fails, the endpoint lands in the normal class on a 300 ms window, and the access log grows by lines nobody chose. Static analysis does not close it. Polling here is 53 setInterval call sites, most of them UI timers rather than fetches, plus 257 setTimeout of which an unknown number are recursive poll loops, and the fetch usually sits several helper layers below the timer. So watch the browser. Walk the sidebar sections, count API requests per dwell rather than across the walk (a timer repeats within one dwell, a per-view fetch fires once and stops, and summing the two is what makes navigation look like polling), and fail on any path repeated inside a single dwell that is absent from the budget. Measured on a runner with no GPU and no model, two paths qualify. The floor is set there so a run that observed nothing fails instead of reporting green, and the docstring states plainly that polls gated behind a loaded model are outside what this can see. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Run the declared-polls guard where a backend actually exists The step landed in studio-frontend-ci's build job, which drives Playwright against a vite dev server: no backend, no BASE_URL, no auth. The suite reads BASE_URL at import, so it would have failed on a KeyError every run rather than guarding anything. Move it to studio-ui-smoke's ui-indicator job, which installs Studio with --local --no-torch and already boots an authenticated server per engine, and reuse that job's boot/rotate/teardown script instead of duplicating it. The script's suite path becomes STUDIO_PW_SUITE with its current value as the default, so every existing caller is unchanged. Own port and home, for the reason the three engines get one each: a shared home races on the bootstrap password. tests/studio/** is already in this workflow's paths filter, so no trigger change is needed. * Ratchet the log budget onto a main that has #8763 Rebasing onto the merge turned three of these guards red, which is what they are for: each one refuses to let a ledger outlive the problem it records. KNOWN_UNCLASSIFIED_POLLS /api/liveness and /api/settings/remote-access now have heartbeat classes, so both entries went stale. KNOWN_UNBOUNDED_FAMILIES llama-server and diffusion-server now prune. the Rust parity check process.rs implements the success rule but no Rust test read the shared fixture, so the corpus was only ever checked from Python. Both ledgers are now empty. Added the shared_access_log_fixture_tests module the fixture names, which asserts all 14 cases against is_backend_access_log_line; verified green with cargo test. Idle envelope ratcheted 1450 -> 1170 against a re-measured 1110. The old note predicted the fix would take idle to roughly 930 and that was wrong: a 10s heartbeat against a 5s poll still emits half of /api/settings/remote-access, 180 lines over 30 minutes, now the joint-largest contributor. Left at 1450 there would have been 340 lines of slack, enough for a new 10s endpoint to land unnoticed; at 1170 that same endpoint trips the envelope. * Name the declared-polls suite where CI can see it test_every_playwright_driver_is_invoked_by_ci caught this, and it was right on both counts. Routing the suite through STUDIO_PW_SUITE meant the only place its path appeared was an env: block, and that guard reads run:, uses: and with:, never env:. Worse, wrapping the script's invocation in ${STUDIO_PW_SUITE:-...} hid the suite that was already there: the guard reported TWO orphans, mine and playwright_loaded_models_indicator.py, which had been named literally since it was written. A parameterisation that makes an existing suite invisible is a bad trade even when it saves duplication. So drop the indirection. The script goes back untouched, and the step moves to the ui-smoke extra shard, which already boots a Studio on 18894 and already mints the credentials, so every sibling step there is just 'python tests/studio/<driver>.py' against it. Mine now reads the same, needs no second boot, and the guard matches it the ordinary way. Placed last in the shard: it dwells for two minutes and rotates the bootstrap password, so a step after it would wait, then meet a password it did not mint. Verified locally: the full Workflow guard suites step, 698 passed. * Let the replay model a slow request The harness could not express the case the suppressors are blindest to. Both of them key on the status code and neither reads how long the request took, so a 200 that took a minute is indistinguishable from a 200 that took a millisecond -- and _app_returning sent its response without touching the clock, so every replayed request cost zero virtual time. A budget cannot bound what its harness cannot express. Request grows a duration_ms, defaulting to 0 so every existing scenario is unchanged, and the poll loop now reads the clock instead of its own counter so time spent inside a slow handler counts against the session rather than extending it. Idle stays at 1110 and busy at 239, measured, and all 93 tests pass. The two new tests assert TODAY's behaviour, not the desired behaviour: a slow success on a quiet-success path still writes nothing. The gap is worth closing, but a guard that tolerated either answer would let an exemption be added and then removed again unnoticed, so closing it should flip these deliberately and budget the new volume. Measured, an unbounded exemption emits one line per request on a sustained degradation, which is the growth these budgets exist to stop; it needs a heartbeat of its own. The third test guards the other two. If duration_ms ever stopped reaching the middleware, every "slow" assertion here would silently be testing a fast request. Verified by breaking the advance on purpose: that test, and only that test, goes red. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
* Studio: guard log volume in CI so it cannot regress unnoticed Log reduction in Studio is several PRs deep (#6377, #7087, #8310, #8311) and every round started the same way: someone noticed a log was huge, measured it, and trimmed it. Nothing stopped the next chatty endpoint, and nothing told the author they had added one. Five guards, all CPU-only, no network, no sleeping. A 30 minute idle session and a 5 minute in-flight session are replayed through the real LoggingMiddleware against a virtual clock, so a thirty minute scenario runs in a second and lands identically on a loaded runner. budget lines per class against a formula of the poll period and the dedup window, plus an envelope on the whole scenario classify a path cannot be quieted without recording how often it is polled, and cannot be polled without being classified signal failures and mutations log at every interval, and the scenario is proved to have exercised the real middleware before any count from it is trusted parity one JSON fixture defines a successful access record for both the backend and the desktop shell bounds every log family prunes, and the two line caps agree The signal guard is the point. An upper bound on log lines is satisfied just as well by a middleware that was never mounted, a logger replaced with a no-op, a scenario that stopped issuing requests, or an error log someone deleted to get under the number. Each of those now fails. Two ledgers record what is already broken rather than weakening the rules to accommodate it: /api/settings/remote-access and /api/liveness sit in the 300ms burst class and write a line per poll, and the llama-server and diffusion-server directories never prune. Both ledgers are self-expiring, so fixing an entry forces its removal. Verified by mutation: eight deliberate breakages, each turning exactly the intended guard red. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: fail CI when the app polls a path the log budget never declared The budget suite compares two backend files against each other: the suppression sets in loggers/handlers.py and the poll cadences in log_budget/session.py. A pull request that adds a polling call site in the frontend edits neither, so nothing fails, the endpoint lands in the normal class on a 300 ms window, and the access log grows by lines nobody chose. Static analysis does not close it. Polling here is 53 setInterval call sites, most of them UI timers rather than fetches, plus 257 setTimeout of which an unknown number are recursive poll loops, and the fetch usually sits several helper layers below the timer. So watch the browser. Walk the sidebar sections, count API requests per dwell rather than across the walk (a timer repeats within one dwell, a per-view fetch fires once and stops, and summing the two is what makes navigation look like polling), and fail on any path repeated inside a single dwell that is absent from the budget. Measured on a runner with no GPU and no model, two paths qualify. The floor is set there so a run that observed nothing fails instead of reporting green, and the docstring states plainly that polls gated behind a loaded model are outside what this can see. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Run the declared-polls guard where a backend actually exists The step landed in studio-frontend-ci's build job, which drives Playwright against a vite dev server: no backend, no BASE_URL, no auth. The suite reads BASE_URL at import, so it would have failed on a KeyError every run rather than guarding anything. Move it to studio-ui-smoke's ui-indicator job, which installs Studio with --local --no-torch and already boots an authenticated server per engine, and reuse that job's boot/rotate/teardown script instead of duplicating it. The script's suite path becomes STUDIO_PW_SUITE with its current value as the default, so every existing caller is unchanged. Own port and home, for the reason the three engines get one each: a shared home races on the bootstrap password. tests/studio/** is already in this workflow's paths filter, so no trigger change is needed. * Ratchet the log budget onto a main that has #8763 Rebasing onto the merge turned three of these guards red, which is what they are for: each one refuses to let a ledger outlive the problem it records. KNOWN_UNCLASSIFIED_POLLS /api/liveness and /api/settings/remote-access now have heartbeat classes, so both entries went stale. KNOWN_UNBOUNDED_FAMILIES llama-server and diffusion-server now prune. the Rust parity check process.rs implements the success rule but no Rust test read the shared fixture, so the corpus was only ever checked from Python. Both ledgers are now empty. Added the shared_access_log_fixture_tests module the fixture names, which asserts all 14 cases against is_backend_access_log_line; verified green with cargo test. Idle envelope ratcheted 1450 -> 1170 against a re-measured 1110. The old note predicted the fix would take idle to roughly 930 and that was wrong: a 10s heartbeat against a 5s poll still emits half of /api/settings/remote-access, 180 lines over 30 minutes, now the joint-largest contributor. Left at 1450 there would have been 340 lines of slack, enough for a new 10s endpoint to land unnoticed; at 1170 that same endpoint trips the envelope. * Name the declared-polls suite where CI can see it test_every_playwright_driver_is_invoked_by_ci caught this, and it was right on both counts. Routing the suite through STUDIO_PW_SUITE meant the only place its path appeared was an env: block, and that guard reads run:, uses: and with:, never env:. Worse, wrapping the script's invocation in ${STUDIO_PW_SUITE:-...} hid the suite that was already there: the guard reported TWO orphans, mine and playwright_loaded_models_indicator.py, which had been named literally since it was written. A parameterisation that makes an existing suite invisible is a bad trade even when it saves duplication. So drop the indirection. The script goes back untouched, and the step moves to the ui-smoke extra shard, which already boots a Studio on 18894 and already mints the credentials, so every sibling step there is just 'python tests/studio/<driver>.py' against it. Mine now reads the same, needs no second boot, and the guard matches it the ordinary way. Placed last in the shard: it dwells for two minutes and rotates the bootstrap password, so a step after it would wait, then meet a password it did not mint. Verified locally: the full Workflow guard suites step, 698 passed. * Let the replay model a slow request The harness could not express the case the suppressors are blindest to. Both of them key on the status code and neither reads how long the request took, so a 200 that took a minute is indistinguishable from a 200 that took a millisecond -- and _app_returning sent its response without touching the clock, so every replayed request cost zero virtual time. A budget cannot bound what its harness cannot express. Request grows a duration_ms, defaulting to 0 so every existing scenario is unchanged, and the poll loop now reads the clock instead of its own counter so time spent inside a slow handler counts against the session rather than extending it. Idle stays at 1110 and busy at 239, measured, and all 93 tests pass. The two new tests assert TODAY's behaviour, not the desired behaviour: a slow success on a quiet-success path still writes nothing. The gap is worth closing, but a guard that tolerated either answer would let an exemption be added and then removed again unnoticed, so closing it should flip these deliberately and budget the new volume. Measured, an unbounded exemption emits one line per request on a sustained degradation, which is the growth these budgets exist to stop; it needs a heartbeat of its own. The third test guards the other two. If duration_ms ever stopped reaching the middleware, every "slow" assertion here would silently be testing a fast request. Verified by breaking the advance on purpose: that test, and only that test, goes red. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Summary
Third-party tqdm bars and HF's own trainer printing go straight into Studio's log. They are pure progress spam, they are the largest single source of lines during a training run, and because they share the stream with the structlog JSON writer with no line discipline between them, a bar can land in the middle of a record and make it unparseable:
Anything reading the log record by record silently drops that record. It is not just noise, it is data loss in the structured log.
Measured
Identical run on two instances, same model, same dataset, same 30 steps (
unsloth/gemma-4-E2B-itQLoRA onmlabonne/FineTome-100k,max_steps=30), counting from the moment the run was queued:training_progresseventsThe two runs were not equally fast (the unpatched one shared its GPU and took about four times as long), which is why the
training_progresscount differs: that event is throttled by wall time (first step, then at most every 30s, then the final step), so its count tracks run duration, not how much is reported. The noise columns are what the change is about.Across a longer 58 minute session on the unpatched instance the totals were 1095 bar lines, 266 raw step dicts and 152 unparseable records.
The three sources
1.
huggingface_hub/transformers/diffusers, in the server process. The subprocess workers already exportHF_HUB_DISABLE_PROGRESS_BARS(hub/services/download_lifecycle.py,core/inference/stt_download_worker.py). The server process, which loads the RAG embedder at boot and every diffusers pipeline in-process, never did.setup_loggingnow does the same and honours an explicitHF_HUB_DISABLE_PROGRESS_BARS=0from the operator.diffusershard-codes_tqdm_active = Trueat import and reads no env var, and is imported lazily long after logging setup, so the diffusion load path calls the helper once more after its import.2.
datasets, in the training worker. TheMap:andStandardizing chat format (num_proc=8):bars from dataset preparation were the ones actually landing inside JSON records.datasets4.x exposes no env var, so the API call is the only lever, and it is imported long after logging setup; the helper is idempotent and is called again immediately before themap()calls that draw them.3. HF
Trainer's own stdout callbacks.disable_tqdm=Truealone does not fix this: it swapsProgressCallbackforPrinterCallback, which prints a raw dict per step instead:So both go:
disable_tqdmis set on both shared training-config builders, and both callbacks are removed right where Studio attaches its own progress callback.Nothing is lost
Every number those lines carry is already published twice, and both survive untouched:
training_progressevent added in Studio: quiet noisy logs, log real progress, and speed up Windows/macOS dataset prep #7087 (first step, then at most every 30s, then the final step), which carries step, total, percent, loss, epoch and eta;Download and model-load progress likewise already reach the UI as
hub_download_progressandinference_load_progressevents and via/api/inference/{images,video}/load-progress.Library warnings and errors are untouched, and so is the transformers
LOAD REPORT, which names missing and unexpected keys. Only the bars and the duplicate per-step prints go.unsloth studio --verboserestores all of it: it zeroes both access-log windows, and the training worker inherits that env, so_verbose_logging_requested()reads the same signal and bothdisable_tqdmand the callback removal stand down.Throughput is not lost, it moves onto the structured line
The bar and the per-step print were the only place trainer speed appeared
(
1.84s/iton the bar,train_tokens_per_secondin the raw dict), andtraining_progresscarried step, loss, epoch and eta but no throughput. Removingthem without replacing that would have been a downgrade, so
training_progressnow also carries
s_per_stepandtok_per_s, measured over the interval betweentwo logged lines (the first line of a run reports the average since it began).
From a live 60-step run on this branch:
Step 1 shows the warmup cost, and the steady-state rate is visible from then on:
the same information the bar carried, in a line a log consumer can parse.
Tests
studio/backend/tests/test_trainer_stdout_quiet.py(8 cases): bars are off by default,--verboserestores them, only zeroing both windows counts as verbose, an unparseable env value is not verbose, bothPrinterCallbackandProgressCallbackare removed, verbose keeps them, and a trainer that raises onremove_callbackor has no such method does not break the run.studio/backend/tests/test_training_progress_throughput.py(9 cases): the first line reports the run average, later lines report the interval rather than the average, the value matches the1.84s/itthe bar showed, a missing token count still yields seconds per step, and a missing clock, a repeated or backwards step, and a stalled clock all yield nothing instead of dividing by zero.tests/test_trainer_stdout_quiet.py+tests/test_training_progress_throughput.py: 17 passed. Wider-k "train or logging or progress": 1707 passed, 2 skipped.Note on overlap
#8306 disables the transformers progress bar narrowly around the RAG embedder load and restores the previous setting. With this PR the global flag is already off, so that scoped code becomes a no-op rather than conflicting; the two are independent and can land in either order.