Skip to content

Studio: preview tokens and the completion mask before training - #13850

Merged
danielhanchen merged 21 commits into
mainfrom
studio-token-preview
Oct 15, 2026
Merged

danielhanchen merged 21 commits into
mainfrom
studio-token-preview

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Fixes #5605

What this adds

A Preview tokens button on the selected dataset card in the Train tab. It opens a dialog with two tabs:

  • Dataset samples: three random rows of the selected dataset, rendered with the model's chat template and tokenized exactly as the run would tokenize them. Trained tokens are highlighted, masked tokens (prompt, system, user turns when "Assistant completions only" is on) are greyed out. Each row shows its token count, how many tokens are trained, and a warning when the context length cuts it or when no token is trained (training drops such rows). Shuffle samples draws three other rows.
  • Your text: type or paste anything and see its tokens, with the same masking applied. Insert chat example fills in a conversation rendered through the model's chat template so you can see where the response marker sits.

A Show token IDs switch puts the ID under every token, and Copy IDs copies a row's IDs as a JSON list. Characters split across several byte level tokens are spelled out (for example Llama 3 encodes ű as <0xC5> + <0xB1>), which answers the question in the issue: modern tokenizers never drop such characters, they may just spend two tokens on them.

Nothing else in the Train tab changes; the dialog is not mounted until the button is clicked.

How it works

  • POST /api/train/token-preview takes the same model, dataset, format, mapping, train on completions and context length fields the start payload sends (the frontend builds them with buildTrainingStartPayload, so the preview and the run cannot disagree).

  • Rows come from the same reader as View dataset: the slice loading in check_format_response moved into load_preview_slice unchanged, so it still reads a local file, the local cache, one data file, or a stream, with the same account and offline guards. The preview reads the first 100 rows (the window training scores to pick a raw-text column), formats them all, and shows a few at random, so no dataset is downloaded in full.

  • For a Hub dataset the preview first asks the Hub dataset viewer (/rows, 100 rows) and only streams when it cannot answer exactly (offline, ModelScope, a mirror without its own viewer, a short or cut answer, image / audio columns). View dataset keeps its current reader. Cold, on an empty cache:

    Dataset Viewer Streaming Rows identical
    mlabonne/FineTome-100k 0.07 MB 37.0 MB 100/100
    yahma/alpaca-cleaned 0.03 MB 57.3 MB 100/100
    HuggingFaceH4/ultrachat_200k (train_sft) 0.19 MB 36.1 MB 100/100
    openai/gsm8k (main) 0.02 MB 2.4 MB 100/100
    roneneldan/TinyStories 0.02 MB 38.7 MB 100/100
    philschmid/guanaco-sharegpt-style 0.06 MB 7.9 MB 100/100
  • The tokenizer download is the tokenizer and config files only (about 30 MB for Qwen3 and Llama 3.2, no weights).

  • The tokenizing runs in a small subprocess (core/training/token_preview_worker.py) that loads only the tokenizer (by repo id, from the Unsloth mirror training reads; a cached repo loads from disk), activates the right transformers sidecar, and then calls the training code itself: format_and_template_dataset, get_training_chat_template, the zoo's add_special_tokens rule, truncation at the context length, and apply_completion_masking with the zoo's train_on_responses_only.

  • The subprocess hides every accelerator before torch is imported, so it never creates a CUDA context. It stays warm for the selected model (typing answers in about 20 ms), exits after 5 idle minutes, and is stopped in a background thread when a training run starts or its account is retired. A failed tokenizer load ends it, so a retry starts fresh.

  • Access: the tokenizer is always read by repo id after the same account checks as the model config route (a supplied cache folder is never used), anonymous offline callers are refused like that route, ref: inventory handles are resolved, trust_remote_code is never used, an adapter's base model is never fetched on its behalf, and every worker start that reads the Hub is recorded with recording_a_request_token_fetch.

  • Training behaviour mirrored: CPT and raw text train every token (typed text gets the same EOS), audio models and DeepSeek OCR are never masked, typed text uses the dataset's format from the last preview, MLX reads the picked repo as given, Spark-TTS loads from LLM/, and a packed run shows a note that its cut points differ.

Parity with a real run

Re-run on the final head as well, same result.

Token IDs and the trained mask from the preview, compared row by row with the labels of a real FastLanguageModel + SFTTrainer + apply_completion_masking setup on the same rows (B200, context length 1024):

Model Dataset Format Rows Token IDs identical Trained mask identical
unsloth/Qwen3-0.6B mlabonne/FineTome-100k chatml_conversations 6 6/6 6/6
unsloth/Llama-3.2-1B-Instruct yahma/alpaca-cleaned alpaca 6 6/6 6/6
unsloth/gemma-3-270m-it mlabonne/FineTome-100k chatml_conversations 6 6/6 6/6

Cost

  • No new work anywhere until the button is clicked: the dialog is not mounted, no request is made and no worker runs. The only change on an existing path is one daemon thread at training start that stops an idle preview worker.
  • Measured in a fresh Studio on this head (Qwen3-0.6B, FineTome-100k): first preview 23.6 s (subprocess start, Unsloth import, tokenizer download), Shuffle samples 1.1 s, typed text 0.33 s from the last keystroke including the 300 ms debounce.
  • Inside the worker, datasets no longer hashes each map function (and the tokenizer it closes over) for cache file names the in-memory preview never writes; outputs are byte identical and a 100-row format pass drops from about 3.3 s to 1.1 s.
  • The first screen's JavaScript grows by 866 B transfer / 2,181 B raw (the button, the dialog and its English strings), measured against main with the chunk count unchanged. Lazy-loading the dialog cost more and added a startup chunk, so scripts/check-bundle-budget.ts is raised by that growth instead.
  • The worker uses no VRAM (no compute process listed for its pid while it served three requests).

Tests

  • studio/backend/tests/test_token_preview.py (25 tests): request validation, the dataset viewer rows standing in only when complete and never offline or behind a mirror, pre-tokenized rows keeping their own IDs and labels, a load recorded whenever a request starts a worker, a retired account never spawning one, the row pool and run settings reaching the worker, seeded sampling, CPT and audio models training every token, typed text never reading the dataset and carrying the dataset format, a supplied cache folder never being the source, no adapter base fetch, inventory handles, byte level and SentencePiece token rendering, masking through apply_completion_masking, a failed load restarting the worker, account retirement and mid-preview stops ending the worker, and a real subprocess run on trl-internal-testing/tiny-Qwen3ForCausalLM (masking half skipped where torch is absent).
  • Cross-platform staging (Ubuntu, Windows, macOS 15): 350 passed, 1 skipped on each. AMD gfx1151 (ROCm): the token preview suite passed 8/8 including the real subprocess test.
  • Switchboard (auth, settings, crawl, parallel, train on completions, diffusion training; GPU journeys on Kaggle T4x2 and Colab T4-HM): NO_REGRESSION; the remaining visual diffs are chat answers of the 270M model and the hub crawl's model pick.
  • Two source inspection tests now point at load_preview_slice, where the token fetch record and the offline refusal moved.
  • Backend subset in a fresh Studio venv (multi account route matrix, keyless API, training start, dataset preview, hub token suites): all pass. Frontend: i18n:check:strict, typecheck and npm test pass; the strings are added to every locale.

Screenshots

Before (merge base) and after (this PR), same model (unsloth/Qwen3-0.6B) and dataset (mlabonne/FineTome-100k), two separate Studio installs.

The dataset card gains a Preview tokens button:

Dataset card with the new Preview tokens button

Dataset samples: the user turn is masked, the assistant turn (including Qwen3's empty think block, which the run trains on too) is highlighted:

Dataset samples tab with trained and masked tokens

Your text, after Insert chat example and typing Thanks! after the turn (masked, since it follows the assistant's end marker):

Your text tab with a chat example

Adds a Preview tokens button to the selected dataset card in the Train tab.
It opens a dialog that shows a few random rows of the dataset tokenized and
masked exactly as the training run would (chat template, train on
completions markers, context length), plus a box to type any text and see
its tokens and IDs.

Only the tokenizer is downloaded. The work runs in a small GPU-free
subprocess that reuses the training formatting and masking code, stays warm
for the selected model, exits after 5 idle minutes, and is stopped when a
training run starts.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 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 ⚠️ Failed 2026-10-15T18:41:02.155025Z a590db9 New commits
🔒 Security Review ✅ Completed 2026-10-15T13:07:52.318074Z 64378b0 Manual request

Security findings

Advisory findings (1)

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

@danielhanchen danielhanchen self-assigned this Oct 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

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: 64378b067d

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

source = config.get("tokenizer_source") or config["model_name"]
token = config.get("hf_token")
try:
return AutoTokenizer.from_pretrained(source, token = token, trust_remote_code = False)

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 Support approved custom tokenizer code

For models whose tokenizer is declared through auto_map, training can proceed after the existing remote-code scan and approval flow, but token preview always calls AutoTokenizer with trust_remote_code=False; the preview therefore fails before showing any tokens for those otherwise supported models. The preview request should carry the approved remote-code settings and enforce the same fingerprint/security checks as training before enabling custom tokenizer loading.

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: the preview never runs remote tokenizer code; those models get a clear load error and still train as before.

Comment on lines +119 to +122
with self._lock:
if not self._alive() or self._key != key:
self._stop_locked()
self._start_locked(key, config)

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 Allow a new model request to preempt startup

The service holds its single global lock for the entire response wait, including the five-minute cold-start timeout. If a user closes an in-flight preview or another account requests a different model, the aborted HTTP request continues in asyncio.to_thread and the new request cannot acquire this lock to stop the obsolete worker, contrary to the service's stated preemption behavior. Arrange for a differing key to terminate the active process before waiting on the lock, or otherwise avoid holding the global lock throughout the blocking queue wait.

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.

Below the bar: a cold start is about 35 s and only delays the next preview, nothing else waits on this lock.

Comment on lines +71 to +74
dataset_name: datasetName || null,
subset: start.subset,
train_split: start.train_split,
dataset_local_path: start.dataset_local_path,

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 Apply configured dataset slicing before sampling

The training start payload already contains dataset_slice_start and dataset_slice_end, but the preview request omits both, so _token_preview_rows always samples from the first 64 rows of the unsliced split. When a run is configured for a later range, the dialog can therefore show rows that training will never consume and miss every row it will consume. Forward the slice settings and apply the same inclusive slicing semantics before building the preview pool.

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.

Intended: the preview shows how rows tokenize and mask, which does not depend on the slice; sampling a slice would read further into the dataset.

…etry failed loads

The tokenizer is read by repo id (cached repos still load from disk), so a
supplied cache folder can no longer bypass the account checks or point at a
cache root with no tokenizer in it. Anonymous offline callers get the same
refusal as the model config route, and a fetch made with a request token is
recorded like the other Hub readers. A tokenizer load failure ends the worker
so a retry starts a fresh one, and typed text is formatted and masked with the
dataset's format from the last preview.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 15, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 15, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 15, 2026
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 15, 2026

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

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

model_name = config["model_name"]
if request.get("text") is not None:
texts, final_format = [request["text"]], str(request.get("final_format") or "").lower()
else:

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 Preserve the tokenizer selected while formatting rows

For ChatML datasets on a model whose repository ID appears in MODEL_TO_TEMPLATE_MAPPER, format_and_template_dataset can replace or restore the copied tokenizer's chat template based on the actual rows and then render texts with that choice. Discarding the copy means the subsequent tokenization and completion masking use the original tokenizer's template instead; unlike this preview, the real trainer formats and later masks with the same tokenizer (trainer.py around format_and_template_dataset and get_training_chat_template). This can change the BOS rule and response markers, producing preview token IDs or masks that do not match training, so the tokenizer mutated during formatting must be reused.

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.

Matches training as is: the trainer formats with the pre-detect tokenizer and masks with the one load_model returns. The PR's parity table (Qwen3, Llama 3.2 alpaca, Gemma 3 on ChatML rows) is token and mask identical to a real SFTTrainer run.

tokenizer = get_training_chat_template(tokenizer, model_name, final_format)

max_length = int(request.get("max_seq_length") or 2048)
add_special_tokens = resolve_add_special_tokens(tokenizer, texts[0] if texts else None)

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 Derive the BOS rule from the dataset's actual first row

The add-special-tokens decision is dataset-wide in training and is computed from first_sample_text(train_dataset, ...), but the preview randomly samples and reorders rows before using texts[0] here. For a heterogeneous raw-text or custom dataset where the real first row already starts with the tokenizer's BOS token and the sampled first row does not, or vice versa, the preview adds or omits BOS differently from training for every displayed sample; shuffling can even change the IDs shown for the same row. Preserve the dataset's actual first formatted row for this probe or pass the training decision separately.

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.

Below the bar: it only differs for a dataset that mixes rows with and without a leading BOS, which is not a well-formed training set.

…e MLX repo as given

Copy IDs now copies the whole row, not only the displayed prefix. Legacy
SentencePiece tokenizers (Mistral, Llama 2) decode a lone word piece without
its leading space, so it is restored for display. On Apple Silicon the
tokenizer is read from the picked repo, as the MLX trainer does, and any
Hub read with a request token is recorded.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…d raw text, read Spark-TTS from LLM/

The worker now formats all 64 head rows and samples from the result, so the
raw-text column and the BOS rule come from the dataset's head as in training.
Typed text under CPT or raw text gets the same EOS training appends, and a
repo whose tokenizer sits under LLM/ (Spark-TTS) loads from there.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member 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: f1415350be

ℹ️ 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 on lines +225 to +228
max_length = int(request.get("max_seq_length") or 2048)
add_special_tokens = resolve_add_special_tokens(tokenizer, first_text)
encoded = tokenizer(
texts, truncation = True, max_length = max_length, add_special_tokens = add_special_tokens

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 Clamp preview length to the effective model context

Clamp max_length using the same effective model limit as training. The context-length input accepts arbitrary positive integers, while the trainer's online-tokenization path explicitly lowers the requested value when model.max_seq_length is smaller; this preview always truncates at the unadjusted request. For a model whose loader enforces a lower cap, the dialog therefore shows and copies tokens that the actual run truncates, and reports an incorrect truncation boundary.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Oct 15, 2026 •

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.

Below the bar: a context length above what the model loader allows is an unusual setting, and the preview still shows the run's tokens and mask up to the requested length.

Comment on lines +144 to +148
trainer = types.SimpleNamespace(
processing_class = tokenizer,
train_dataset = Dataset.from_dict({"input_ids": encoded["input_ids"]}),
eval_dataset = None,
)

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 Model the MLX trainer when previewing its masks

Preserve the selected training backend in this stand-in trainer. apply_completion_masking deliberately skips its extra Gemma 4 tool-response masking when type(trainer).__name__ == "MLXTrainer", because MLX labels those batches inside its own masking function; this SimpleNamespace instead always takes the CUDA-specific post-processing path. On Apple Silicon, a Gemma 4 conversation containing tool responses is therefore shown with those response tokens masked even though the MLX run trains them.

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.

Below the bar: it only differs for Gemma 4 conversations with tool responses trained on Apple Silicon.

let result: ReactNode = null;
if (state.error && text) {
result = <p className="text-sm text-destructive">{state.error}</p>;
} else if (sample) {

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 Hide stale token results while a new preview loads

Do not render sample while state.loading is true. Each text edit retains the previous data while setting loading: true, so after the first successful preview the card continues to show—and lets the user copy—the prior text's token IDs during the debounce and request for the newly displayed text. The dataset tab already handles the same state correctly by showing LoadingRow whenever state.loading is set.

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.

Intended: keeping the last result while typing avoids the card flashing on every keystroke; it is replaced about 300 ms after typing stops.

… or DeepSeek OCR models

Matches prepare_raw_text_dataset, which picks a raw-text column from the first
100 rows, and the trainer, which trains every token of an audio model or
DeepSeek OCR.

[skip ci]
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 8301505902

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

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…with retirement, preview pre-tokenized rows, skip fingerprint hashing in the worker

[skip ci]
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 0199f62b63

ℹ️ 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 pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 15, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 15, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 15, 2026
# Conflicts:
#	studio/backend/routes/training.py
#	studio/frontend/scripts/check-bundle-budget.ts
@danielhanchen
danielhanchen merged commit a2003f1 into main Oct 15, 2026
@danielhanchen
danielhanchen deleted the studio-token-preview branch October 15, 2026 18:53
danielhanchen added a commit that referenced this pull request Oct 15, 2026
Main (bd06376) is red in Backend CI on five tests, seen on every PR
based on it (#13914, #13919). Four come from #13850 and #13806, which
are both right; one comes from my own #13909. Each is reproduced locally
on main and fixed here.

## From #13850 (token preview)

**`test_every_long_lived_spawner_consults_the_shutdown_latch`**:
`core/training/token_preview.py` adopts its worker with `adopt_pid` but
was in neither the gated nor the not-gated set. It already checks
`is_process_shutting_down()` before spawning, so it belongs with the
gated spawners, but a gated spawner also has to recheck after adopting:
a quit that lands between the check and `adopt_pid` happens after the
shutdown sweep took its snapshot, and the worker would outlive it.
`_spawn_locked` now rechecks right after adopting, and if the latch is
set it stops the new worker and raises `TokenPreviewError("Unsloth is
shutting down.")`, the same message `_start_locked` uses. The module
goes into the gated set.

New test `test_a_quit_that_races_the_spawn_reaps_the_new_worker` drives
that race: the latch flips inside `Process.start()`, and the worker must
be stopped and the call refused.

**`test_the_dataset_format_check_installs_the_decoder`**:
`check_format_response` now reads its rows through `load_preview_slice`,
which calls `ensure_audio_decoding()` before any tier, so the wiring is
intact. The test only read `check_format_response`'s own source. It now
checks that `check_format_response` reads through `load_preview_slice`,
and that `load_preview_slice` installs the decoder before its first read
(`resolve_dataset_path(` / `load_dataset(`), which also pins the
ordering the old form never checked.

**`test_the_subprocess_tokenizes_and_masks_typed_text`**: the
completion-masking half imports unsloth in the worker, as training does,
and Backend CI has torch but no `unsloth_zoo` (`Unsloth: Please install
unsloth_zoo via pip install unsloth_zoo then retry!`). The test skipped
only when torch was missing; it now also skips when `unsloth_zoo` is not
importable. The plain tokenization half still runs everywhere.

## From #13806 (drafter training)

**`test_owner_training_start_status_cancel_bytes_are_unchanged`**: the
training status details gained `"drafter": null`. The test pins the
exact status bytes on purpose, so a new field is a deliberate, one-line
update to the expected dict.

## From #13909 (mine)

**`test_python_children_are_told_to_emit_utf8`**: #13909 made the
drafter capability probe decode its child as UTF-8 but set
`PYTHONIOENCODING` on its own line, while this guard requires the child
env to go through `utf8_child_env()` at the call site. The probe now
passes `env = utf8_child_env(env)`, which sets the same variable through
the shared helper.

## Verification

- `test_audio_dataset_decode.py`, `test_chat_text_encoding.py`,
`test_job_accounts.py`, `test_orchestrator_unload_cancel.py`,
`test_token_preview.py`, `test_text_io_encoding.py`,
`test_drafter_training.py`: 1144 passed. One failure,
`test_capability_child_process_runs_for_real`, fails identically on main
on this host (it runs the probe in a real child interpreter) and is not
failing in CI.
- Without `unsloth_zoo` importable: the token preview real-worker test
tokenizes, then skips the masking half with its reason.
- Sabotage, the post-adopt recheck removed: the spawner-set guard fails
(`never rechecks the latch after adopting`) and the new race test fails
(`DID NOT RAISE TokenPreviewError`).
- Sabotage, `ensure_audio_decoding()` moved after
`resolve_dataset_path(` in `load_preview_slice`: the decoder test fails
(`the decoder must be installed before the first row is read`).
- `tests/test_formatter_fixed_point.py`: passes.
danielhanchen added a commit that referenced this pull request Oct 15, 2026
…p guards (#13936)

Two more checks are red on main (7382805), seen on #13915 and
#13922's run, both reproduced locally on main.

## `test_no_raw_pixel_text_utilities` (from #13850)

```
Raw px text utilities ignore the UI font size preference; use the text-ui-* / leading-ui-* tokens in index.css instead:
  features/studio/sections/token-preview-dialog.tsx: text-[12.5px]
  features/studio/sections/token-preview-dialog.tsx: text-[9px]
```

The new token preview dialog sized three text runs with raw
`text-[12.5px]` / `text-[9px]`, so they stay fixed when the user changes
Settings > UI font size while the rest of Studio scales. The contract is
right and the dialog is what changes. `index.css` has exact tokens for
both sizes, `--text-ui-12p5: calc(0.78125rem * var(--ui-font-scale, 1))`
and `--text-ui-9: calc(0.5625rem * var(--ui-font-scale, 1))`, so this
swaps to `text-ui-12p5` / `text-ui-9`. At the default scale of 1 those
resolve to the same 12.5px and 9px, so the dialog renders the same as
today; the only difference is that it now follows the font size setting.
No screenshots: there is nothing visible to compare at the default
scale.

## `test_no_skip_guard_reads_a_spoofable_accelerator_probe` (from #13830
and #13889)

```
test_fp8_rowwise_gemv_blackwell_gate.py:47: torch.cuda.is_available()
test_norm_fast_launch.py:189: torch.cuda.device_count()
```

`tests/_zoo_aggressive_cuda_spoof.py` patches the torch.cuda probes to
report a GPU process-wide for the version-compat suites, so a skip guard
that reads them un-skips on a CPU-only runner whenever it shares a
pytest session with those suites. Both guards now ask `has_real_cuda()`
from `tests/_shared/real_accelerator.py` (answered before any spoof),
the form the rest of the tree uses: `not has_real_cuda()` for the FP8
GEMV exactness test, and `not has_real_cuda() or
torch.cuda.device_count() < 2` for the two-GPU norm test, matching
`test_rms_layernorm_multirow.py`. On a real GPU the predicate is the
same as before.

## Verification

- `tests/studio/test_ui_font_scale_contract.py`: fails on main as above,
12 passed here. Prettier clean.
- `tests/python/test_accelerator_skip_guards.py`: fails on main as
above, 24 passed here.
- On CPU, `test_fp8_rowwise_gemv_blackwell_gate.py` and
`test_norm_fast_launch.py`: 6 passed, 4 skipped (the GPU cases, with
their reasons), same as main.
- Not run here: the GPU cases themselves. This host's CUDA torch
environment fails bitsandbytes CUDA setup at collection, unrelated to
this change; the test bodies are untouched.
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.

[Feature] Unsloth studio: Tokenizer viewer, editable list(add new tokens/caracters)

1 participant