Repository navigation
Studio: preview tokens and the completion mask before training - #13850
Conversation
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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
Security findingsAdvisory findings (1)ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex security review |
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Deliberate: the preview never runs remote tokenizer code; those models get a clear load error and still train as before.
| with self._lock: | ||
| if not self._alive() or self._key != key: | ||
| self._stop_locked() | ||
| self._start_locked(key, config) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Below the bar: a cold start is about 35 s and only delays the next preview, nothing else waits on this lock.
| dataset_name: datasetName || null, | ||
| subset: start.subset, | ||
| train_split: start.train_split, | ||
| dataset_local_path: start.dataset_local_path, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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]
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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: |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…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]
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| trainer = types.SimpleNamespace( | ||
| processing_class = tokenizer, | ||
| train_dataset = Dataset.from_dict({"input_ids": encoded["input_ids"]}), | ||
| eval_dataset = None, | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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]
|
Codex Review: Didn't find any major issues. Breezy! 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". |
…he dialog only when opened
…with retirement, preview pre-tokenized rows, skip fingerprint hashing in the worker [skip ci]
|
Codex Review: Didn't find any major issues. Chef's kiss. 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". |
# Conflicts: # studio/backend/routes/training.py # studio/frontend/scripts/check-bundle-budget.ts
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.
…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.
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:
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-previewtakes the same model, dataset, format, mapping, train on completions and context length fields the start payload sends (the frontend builds them withbuildTrainingStartPayload, so the preview and the run cannot disagree).Rows come from the same reader as View dataset: the slice loading in
check_format_responsemoved intoload_preview_sliceunchanged, 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: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'sadd_special_tokensrule, truncation at the context length, andapply_completion_maskingwith the zoo'strain_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_codeis never used, an adapter's base model is never fetched on its behalf, and every worker start that reads the Hub is recorded withrecording_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_maskingsetup on the same rows (B200, context length 1024):Cost
datasetsno 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.scripts/check-bundle-budget.tsis raised by that growth instead.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 throughapply_completion_masking, a failed load restarting the worker, account retirement and mid-preview stops ending the worker, and a real subprocess run ontrl-internal-testing/tiny-Qwen3ForCausalLM(masking half skipped where torch is absent).load_preview_slice, where the token fetch record and the offline refusal moved.i18n:check:strict,typecheckandnpm testpass; 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 samples: the user turn is masked, the assistant turn (including Qwen3's empty think block, which the run trains on too) is highlighted:
Your text, after Insert chat example and typing
Thanks!after the turn (masked, since it follows the assistant's end marker):