Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

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

Daniel Hana2003f1a05e0
diff --git a/studio/backend/core/training/token_preview.py b/studio/backend/core/training/token_preview.py
new file mode 100644
index 00000000000..c774e630beb
--- /dev/null
+++ b/studio/backend/core/training/token_preview.py
@@ -0,0 +1,219 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Owns the token preview subprocess (core.training.token_preview_worker).
+
+One worker at a time, kept for the model it was started for so typing in the preview answers in
+milliseconds; a request for another model, a training start or an idle timeout ends it.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import itertools
+import multiprocessing as mp
+import queue
+import threading
+import time
+from typing import Any, Callable, Optional
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+_CTX = mp.get_context("spawn")
+# The first request imports torch and Unsloth and may download the tokenizer files.
+FIRST_REQUEST_TIMEOUT_S = 300.0
+REQUEST_TIMEOUT_S = 60.0
+# Applied in the child before anything imports torch: a CUDA context alone costs hundreds of MB of
+# VRAM, and the preview only tokenizes. UNSLOTH_ALLOW_CPU lets Unsloth's chat templates import there.
+_NO_ACCELERATOR_ENV = {
+ "CUDA_VISIBLE_DEVICES": "",
+ "HIP_VISIBLE_DEVICES": "",
+ "UNSLOTH_ALLOW_CPU": "1",
+}
+
+
+class TokenPreviewError(RuntimeError):
+ pass
+
+
+class _TokenPreviewService:
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._proc: Optional[Any] = None
+ self._cmd_queue: Optional[Any] = None
+ self._resp_queue: Optional[Any] = None
+ self._key: Optional[tuple] = None
+ self._served = False
+ self._stop_pending = False
+ self._ids = itertools.count(1)
+ from core.training.account_jobs import init_job_owner
+
+ # Lets retire_account_jobs stop a retired account's warm worker before its roots move.
+ init_job_owner(self, self._alive, self.stop)
+
+ def _alive(self) -> bool:
+ return self._proc is not None and self._proc.is_alive()
+
+ def _stop_locked(self) -> None:
+ self._stop_pending = False
+ proc, self._proc = self._proc, None
+ self._key = None
+ if proc is None:
+ return
+ try:
+ if proc.is_alive() and self._cmd_queue is not None:
+ self._cmd_queue.put({"op": "shutdown"})
+ proc.join(timeout = 2)
+ if proc.is_alive():
+ proc.terminate()
+ proc.join(timeout = 3)
+ if proc.is_alive():
+ proc.kill()
+ proc.join(timeout = 3)
+ except Exception: # noqa: BLE001 - the reap is best-effort
+ logger.warning("could not stop the token preview worker", exc_info = True)
+ if proc.exitcode is not None:
+ from utils.process_lifetime import forget_pid
+ forget_pid(proc.pid)
+
+ def _start_locked(self, key: tuple, config: dict) -> None:
+ from utils.process_lifetime import is_process_shutting_down
+ from utils.transformers_version import sidecar_swap_kind
+
+ if is_process_shutting_down():
+ raise TokenPreviewError("Unsloth is shutting down.")
+ if sidecar_swap_kind() is not None:
+ raise TokenPreviewError(
+ "A transformers installation is in progress; try the preview again when it finishes."
+ )
+ from core.training.account_jobs import account_is_retired
+ from utils.account_context import current_account
+
+ # Owner and in-flight count go up before the spawn, as owned_job does: a retirement in between
+ # then refuses (retry) or sees this worker, instead of finishing before it exists.
+ with self._account_job_lock:
+ if account_is_retired():
+ raise TokenPreviewError("This account has been removed.")
+ self._result_account = current_account()
+ self._account_inflight += 1
+ try:
+ self._spawn_locked(key, config)
+ finally:
+ with self._account_job_lock:
+ self._account_inflight -= 1
+
+ def _spawn_locked(self, key: tuple, config: dict) -> None:
+ from core.training.account_jobs import account_process_spec
+ from utils.hf_cache_settings import child_environment_for_spawn, get_hf_cache_paths
+ from utils.native_path_leases import (
+ native_path_secret_removed_for_child_start,
+ run_without_native_path_secret,
+ )
+ from utils.process_lifetime import adopt_pid
+
+ cache_env = get_hf_cache_paths().child_env({})
+ with (
+ child_environment_for_spawn(cache_env),
+ native_path_secret_removed_for_child_start(),
+ ):
+ self._cmd_queue = _CTX.Queue()
+ self._resp_queue = _CTX.Queue()
+ process_args, process_kwargs = account_process_spec(
+ "core.training.token_preview_worker",
+ "run_token_preview_process",
+ {**cache_env, **_NO_ACCELERATOR_ENV},
+ {
+ "cmd_queue": self._cmd_queue,
+ "resp_queue": self._resp_queue,
+ "config": config,
+ },
+ )
+ proc = _CTX.Process(
+ target = run_without_native_path_secret,
+ args = process_args,
+ kwargs = process_kwargs,
+ daemon = True,
+ )
+ proc.start()
+ adopt_pid(proc.pid)
+ self._proc, self._key, self._served = proc, key, False
+ logger.info("Token preview worker started (pid=%s)", proc.pid)
+
+ def preview(
+ self,
+ key: tuple,
+ config: dict,
+ request: dict,
+ record_load: Optional[Callable[[], Any]] = None,
+ ) -> dict:
+ """``record_load`` wraps a request that loads the tokenizer, decided under the lock so a
+ concurrent request swapping the worker cannot make that load go unrecorded."""
+ with self._lock:
+ loads = not (self._alive() and self._key == key and self._served)
+ with record_load() if loads and record_load else contextlib.nullcontext():
+ reply = self._request_locked(key, config, request)
+ if not reply.get("ok"):
+ raise TokenPreviewError(reply.get("error") or "Token preview failed.")
+ return reply["result"]
+
+ def _request_locked(self, key: tuple, config: dict, request: dict) -> dict:
+ if not self._alive() or self._key != key:
+ self._stop_locked()
+ self._start_locked(key, config)
+ request_id = next(self._ids)
+ self._cmd_queue.put({**request, "id": request_id})
+ deadline = time.monotonic() + (
+ REQUEST_TIMEOUT_S if self._served else FIRST_REQUEST_TIMEOUT_S
+ )
+ while True:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ self._stop_locked()
+ raise TokenPreviewError("The token preview timed out.")
+ try:
+ reply = self._resp_queue.get(timeout = min(remaining, 1.0))
+ except queue.Empty:
+ if not self._alive():
+ self._stop_locked()
+ raise TokenPreviewError("The token preview worker stopped unexpectedly.")
+ continue
+ if reply.get("id") == request_id:
+ break
+ self._served = True
+ if reply.get("fatal") or self._stop_pending:
+ self._stop_locked()
+ return reply
+
+ def stop(self) -> None:
+ # Never waits behind a preview in flight (a first one can take minutes): ending its worker
+ # makes that request fail at once instead.
+ if self._lock.acquire(blocking = False):
+ try:
+ self._stop_locked()
+ finally:
+ self._lock.release()
+ return
+ # The holder may be between workers, with none to terminate yet; it ends whatever it ends up with.
+ self._stop_pending = True
+ proc = self._proc
+ if proc is not None and proc.is_alive():
+ proc.terminate()
+
+
+_service = _TokenPreviewService()
+
+
+def run_token_preview(
+ key: tuple,
+ config: dict,
+ request: dict,
+ record_load: Optional[Callable[[], Any]] = None,
+) -> dict:
+ return _service.preview(key, config, request, record_load)
+
+
+def stop_token_preview_worker() -> None:
+ """Free the worker's memory; safe to call when none is running."""
+ _service.stop()
diff --git a/studio/backend/core/training/token_preview_worker.py b/studio/backend/core/training/token_preview_worker.py
new file mode 100644
index 00000000000..0fdb28af508
--- /dev/null
+++ b/studio/backend/core/training/token_preview_worker.py
@@ -0,0 +1,355 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Token preview subprocess: loads only a model's tokenizer and shows how training would tokenize and
+mask a few dataset rows or a typed text.
+
+Runs the same formatting, chat template and completion masking calls as the training worker, so
+what the preview marks as trained is what the run trains on. It never touches a GPU: the parent
+starts it with every accelerator hidden, and it exits on its own once idle.
+"""
+
+from __future__ import annotations
+
+import copy
+import os
+import queue
+import sys
+import traceback
+import types
+from pathlib import Path
+from typing import Any
+
+# Long enough to type between edits, short enough that an abandoned dialog does not keep torch in memory.
+IDLE_TIMEOUT_S = 300
+# A token list this long already fills the dialog; the counts below still cover the whole row.
+MAX_TOKENS_SHOWN = 4096
+PRETOKENIZED_FORMAT = "pretokenized" # utils.datasets.pretokenized, kept import-free here
+
+_EXAMPLE_CONVERSATION = [
+ {"role": "user", "content": "What is the capital of Hungary?"},
+ {"role": "assistant", "content": "The capital of Hungary is Budapest."},
+]
+
+
+def _load_tokenizer(config: dict):
+ from transformers import AutoTokenizer
+
+ 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)
+ except Exception as root_error:
+ # Spark-TTS keeps its tokenizer under LLM/, as _spark_tts_tokenizer_kwargs reads it for training. No
+ # adapter base fallback: that repo comes from the adapter's own config, which the route never authorized.
+ try:
+ return AutoTokenizer.from_pretrained(
+ source, token = token, trust_remote_code = False, subfolder = "LLM"
+ )
+ except Exception:
+ raise root_error from None
+
+
+def _byte_level_decoder() -> dict:
+ """GPT-2's byte-to-unicode table, inverted: byte-level BPE vocabularies spell every byte as one of these."""
+ printable = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1))
+ printable += list(range(ord("®"), ord("ÿ") + 1))
+ chars, extra = {}, 0
+ for byte in range(256):
+ if byte in printable:
+ chars[chr(byte)] = byte
+ else:
+ chars[chr(256 + extra)] = byte
+ extra += 1
+ return chars
+
+
+_BYTE_LEVEL = _byte_level_decoder()
+
+
+def _token_text(tokenizer, token_id: int, raw: str) -> str:
+ """The token as text. A piece holding part of a multi-byte character decodes to U+FFFD on its
+ own, so its bytes are spelled out instead: Llama's "ű" after a space is "Ġ" + 0xC5, then 0xB1."""
+ text = tokenizer.decode([token_id])
+ # Legacy SentencePiece decoding (Mistral, Llama 2) drops the word-initial space of a lone "▁" piece.
+ if raw.startswith("▁") and not text.startswith(" "):
+ text = " " + text
+ if "\ufffd" not in text or not raw:
+ return text
+ if all(char in _BYTE_LEVEL for char in raw):
+ data = bytes(_BYTE_LEVEL[char] for char in raw)
+ return "".join(
+ char if char.isprintable() or char in " \n\t" else f"<0x{ord(char) - 0xDC00:02X}>"
+ for char in data.decode("utf-8", errors = "surrogateescape")
+ )
+ return raw
+
+
+def _render_tokens(tokenizer, input_ids: list, labels: list | None) -> dict:
+ shown = input_ids[:MAX_TOKENS_SHOWN]
+ raw_pieces = tokenizer.convert_ids_to_tokens(shown)
+ tokens = []
+ for index, token_id in enumerate(shown):
+ trained = labels is None or labels[index] != -100
+ tokens.append(
+ [int(token_id), _token_text(tokenizer, token_id, raw_pieces[index] or ""), trained]
+ )
+ trained_count = (
+ len(input_ids) if labels is None else sum(1 for label in labels if label != -100)
+ )
+ return {
+ "tokens": tokens,
+ "input_ids": [int(token_id) for token_id in input_ids],
+ "num_tokens": len(input_ids),
+ "num_trained": trained_count,
+ "num_hidden": max(0, len(input_ids) - len(shown)),
+ }
+
+
+def _mask(tokenizer, model_name: str, encoded: dict, final_format: str) -> tuple[list, dict]:
+ """Labels for each row via apply_completion_masking, the call the training worker makes."""
+ from datasets import Dataset
+ from unsloth.chat_templates import train_on_responses_only
+ from utils.datasets.completion_masking import apply_completion_masking
+
+ markers: dict[str, Any] = {}
+ notes: list[str] = []
+
+ def preview_train_fn(
+ trainer,
+ instruction_part = None,
+ response_part = None,
+ **_ignored,
+ ):
+ inner = getattr(trainer.processing_class, "tokenizer", trainer.processing_class)
+ markers["instruction_part"] = instruction_part or getattr(
+ inner, "_unsloth_input_part", None
+ )
+ markers["response_part"] = response_part or getattr(inner, "_unsloth_output_part", None)
+ label_fn = train_on_responses_only(
+ None,
+ instruction_part = instruction_part,
+ response_part = response_part,
+ tokenizer = trainer.processing_class,
+ return_function = True,
+ )
+ trainer.train_dataset = trainer.train_dataset.map(label_fn, batched = True)
+ return trainer
+
+ trainer = types.SimpleNamespace(
+ processing_class = tokenizer,
+ train_dataset = Dataset.from_dict({"input_ids": encoded["input_ids"]}),
+ eval_dataset = None,
+ )
+ trainer, applied = apply_completion_masking(
+ trainer,
+ model_name,
+ preview_train_fn,
+ notify = lambda level, message: notes.append(message),
+ dataset_template = "alpaca" if final_format == "alpaca" else None,
+ )
+ masking = {"applied": bool(applied), "notes": notes, **markers}
+ if not applied:
+ return [None] * len(encoded["input_ids"]), masking
+ return list(trainer.train_dataset["labels"]), masking
+
+
+def _format_rows(tokenizer, config: dict, rows: list) -> tuple[list, str]:
+ from datasets import Dataset
+ from utils.datasets import format_and_template_dataset
+ from utils.datasets.raw_text import prepare_raw_text_dataset
+
+ dataset = Dataset.from_list(rows)
+ if config.get("raw_text"):
+ result = prepare_raw_text_dataset(
+ dataset,
+ mode_label = "CPT" if config.get("is_cpt") else "raw text",
+ split_name = "train",
+ eos_token = getattr(tokenizer, "eos_token", None),
+ append_eos = True,
+ )
+ return list(result.dataset["text"]), "raw_text"
+
+ info = format_and_template_dataset(
+ dataset,
+ model_name = config["model_name"],
+ tokenizer = tokenizer,
+ is_vlm = False,
+ format_type = config.get("format_type") or "auto",
+ dataset_name = config.get("dataset_name"),
+ custom_format_mapping = config.get("custom_format_mapping"),
+ # In-process: a pool for three rows costs seconds and changes nothing in the output.
+ num_proc = 1,
+ )
+ if not info.get("success", True):
+ raise ValueError("; ".join(info.get("errors") or []) or "Dataset formatting failed")
+ final_format = str(info.get("final_format", "")).lower()
+ if final_format == PRETOKENIZED_FORMAT:
+ return info["dataset"].to_list(), final_format
+ return list(info["dataset"]["text"]), final_format
+
+
+def _pretokenized(tokenizer, model_name: str, rows: list, max_length: int, request: dict):
+ """IDs, labels, full lengths and masking for pre-tokenized rows, as training prepares them: truncated by
+ prepare_pretokenized_dataset, trained where the rows' own labels say, else masked from input_ids."""
+ from datasets import Dataset
+ from utils.datasets.pretokenized import has_custom_labels, prepare_pretokenized_dataset
+
+ dataset = Dataset.from_list(rows)
+ full_lengths = [len(ids) for ids in dataset["input_ids"]]
+ dataset = prepare_pretokenized_dataset(dataset, max_seq_length = max_length)
+ input_ids = [list(ids) for ids in dataset["input_ids"]]
+ if has_custom_labels(dataset):
+ return (
+ input_ids,
+ [list(row) for row in dataset["labels"]],
+ full_lengths,
+ {"applied": False, "notes": []},
+ )
+ if request.get("train_on_completions"):
+ labels, masking = _mask(
+ tokenizer, model_name, {"input_ids": input_ids}, PRETOKENIZED_FORMAT
+ )
+ return input_ids, labels, full_lengths, masking
+ return input_ids, [None] * len(input_ids), full_lengths, {"applied": False, "notes": []}
+
+
+def _sample(texts: list, count: int, seed: int) -> list:
+ import random
+ if len(texts) <= count:
+ return texts
+ return random.Random(seed).sample(texts, count)
+
+
+def _preview(tokenizer, config: dict, request: dict) -> dict:
+ from utils.datasets.chat_templates import get_training_chat_template
+ from utils.datasets.online_tokenization import resolve_add_special_tokens
+
+ model_name = config["model_name"]
+ if request.get("text") and request.get("raw_text"):
+ texts, final_format = _format_rows(tokenizer, request, [{"text": request["text"]}])
+ first_text = texts[0]
+ elif request.get("text") is not None:
+ texts, final_format = [request["text"]], str(request.get("final_format") or "").lower()
+ first_text = texts[0]
+ else:
+ # Formatting may set a template on the tokenizer it is given; training formats with a throwaway
+ # tokenizer too, and masks with the one the model load returns. The whole pool is formatted so a
+ # raw-text column and the BOS rule are chosen from the dataset's head, as training does.
+ texts, final_format = _format_rows(
+ copy.deepcopy(tokenizer), {**config, **request}, request["rows"]
+ )
+ first_text = texts[0] if texts else None
+ texts = _sample(texts, int(request.get("num_samples") or 3), request.get("seed") or 0)
+ if not getattr(tokenizer, "chat_template", None):
+ tokenizer = copy.deepcopy(tokenizer)
+ tokenizer = get_training_chat_template(tokenizer, model_name, final_format)
+
+ max_length = int(request.get("max_seq_length") or 2048)
+ if final_format == PRETOKENIZED_FORMAT:
+ add_special_tokens = False
+ all_ids, labels, full_lengths, masking = _pretokenized(
+ tokenizer, model_name, texts, max_length, request
+ )
+ texts = [tokenizer.decode(ids) for ids in all_ids]
+ else:
+ 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
+ )
+ all_ids = encoded["input_ids"]
+ full_lengths = [
+ len(ids) for ids in tokenizer(texts, add_special_tokens = add_special_tokens)["input_ids"]
+ ]
+ masking = {"applied": False, "notes": []}
+ labels = [None] * len(texts)
+ if request.get("train_on_completions") and final_format != "raw_text" and any(texts):
+ labels, masking = _mask(tokenizer, model_name, dict(encoded), final_format)
+
+ samples = []
+ for text, input_ids, row_labels, full_length in zip(texts, all_ids, labels, full_lengths):
+ sample = _render_tokens(tokenizer, list(input_ids), row_labels)
+ sample["text"] = text
+ sample["truncated_from"] = full_length if full_length > len(input_ids) else None
+ samples.append(sample)
+
+ example_text = None
+ if getattr(tokenizer, "chat_template", None):
+ try:
+ example_text = tokenizer.apply_chat_template(_EXAMPLE_CONVERSATION, tokenize = False)
+ except Exception:
+ example_text = None
+
+ return {
+ "samples": samples,
+ "masking": masking,
+ "final_format": final_format or None,
+ "add_special_tokens": add_special_tokens,
+ "vocab_size": len(tokenizer),
+ "bos_token": getattr(tokenizer, "bos_token", None),
+ "eos_token": getattr(tokenizer, "eos_token", None),
+ "example_text": example_text,
+ }
+
+
+def _skip_fingerprint_hashing() -> None:
+ """datasets dill-hashes each map function (and the tokenizer it closes over) to name cache files the
+ in-memory preview never writes; a random id serves the same. Idempotent."""
+ import datasets.arrow_dataset as arrow_dataset
+ import datasets.fingerprint as fingerprint
+
+ random_fingerprint = fingerprint.generate_random_fingerprint
+ for module in (fingerprint, arrow_dataset):
+ if hasattr(module, "update_fingerprint"):
+ module.update_fingerprint = lambda *args, **kwargs: random_fingerprint()
+
+
+def run_token_preview_process(*, cmd_queue: Any, resp_queue: Any, config: dict) -> None:
+ """Subprocess entrypoint. ``config`` names the model; each command on ``cmd_queue`` is a preview
+ request answered on ``resp_queue`` with the same ``id``."""
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+ os.environ["PYTHONWARNINGS"] = "ignore"
+ backend_path = str(Path(__file__).resolve().parent.parent.parent)
+ if backend_path not in sys.path:
+ sys.path.insert(0, backend_path)
+
+ from utils.security.hub_data_files import install as guard_hub_data_files
+
+ guard_hub_data_files()
+
+ tokenizer = None
+ load_error = None
+ try:
+ from utils.transformers_version import activate_transformers_for_subprocess
+ activate_transformers_for_subprocess(config["model_name"], config.get("hf_token"))
+ tokenizer = _load_tokenizer(config)
+ except Exception as exc: # noqa: BLE001 - reported on every request instead
+ load_error = f"Could not load the tokenizer for {config['model_name']}: {exc}"
+ if tokenizer is not None:
+ try:
+ # Paid once here rather than on the first preview; both are needed by most requests.
+ import unsloth.chat_templates # noqa: F401
+ import unsloth_zoo.dataset_utils # noqa: F401
+ _skip_fingerprint_hashing()
+ except Exception: # noqa: BLE001 - the request that needs them reports the failure
+ pass
+
+ while True:
+ try:
+ request = cmd_queue.get(timeout = IDLE_TIMEOUT_S)
+ except queue.Empty:
+ return
+ if not isinstance(request, dict) or request.get("op") == "shutdown":
+ return
+ reply: dict[str, Any] = {"id": request.get("id")}
+ if load_error is not None:
+ # Fatal: the parent starts a fresh worker for the next request, so a retry can succeed.
+ reply.update(ok = False, error = load_error, fatal = True)
+ resp_queue.put(reply)
+ return
+ try:
+ reply.update(ok = True, result = _preview(tokenizer, config, request))
+ except Exception as exc: # noqa: BLE001 - one bad request must not end the worker
+ traceback.print_exc()
+ reply.update(ok = False, error = str(exc) or type(exc).__name__)
+ resp_queue.put(reply)
diff --git a/studio/backend/hub/services/datasets/formatting.py b/studio/backend/hub/services/datasets/formatting.py
index 7e7d4ad2ed6..8161b36a914 100644
--- a/studio/backend/hub/services/datasets/formatting.py
+++ b/studio/backend/hub/services/datasets/formatting.py
@@ -370,6 +370,221 @@ def _load_any_cached_hf_preview_slice(
return cached_preview
+_VIEWER_MAX_ROWS = 100
+_VIEWER_MEDIA_TYPES = ("Image", "Audio", "Video", "Pdf")
+
+
+def _viewer_rows(request: CheckFormatRequest, hf_token, preview_size: int) -> Optional[list]:
+ """The first rows from the Hub dataset viewer, a ~100 KB answer where streaming reads a whole parquet
+ row group or JSON block. None whenever it cannot stand in for the stream exactly."""
+ import json
+ import os
+
+ import httpx
+
+ from utils.hf_endpoint import _DEFAULT_HF_ENDPOINT, browser_hf_endpoint, get_hf_datasets_server
+ from utils.hub_settings import MODELSCOPE, active_source
+ from utils.utils import hf_env_offline
+
+ split = request.train_split or "train"
+ if (
+ preview_size > _VIEWER_MAX_ROWS
+ or hf_env_offline()
+ or active_source() == MODELSCOPE
+ or (
+ browser_hf_endpoint() != _DEFAULT_HF_ENDPOINT
+ and not os.environ.get("HF_DATASETS_SERVER")
+ )
+ or not re.fullmatch(r"[\w.-]+", split)
+ ):
+ return None
+ try:
+ response = httpx.get(
+ # /rows, not /first-rows: first-rows caps its answer by size and returns as few as 28 rows.
+ f"{get_hf_datasets_server()}/rows",
+ params = {
+ "dataset": request.dataset_name,
+ "config": request.subset or "default",
+ "split": split,
+ "offset": 0,
+ "length": preview_size,
+ },
+ headers = {"Authorization": f"Bearer {hf_token}"} if hf_token else None,
+ timeout = 10,
+ )
+ body = response.json() if response.status_code == 200 else None
+ except Exception as e:
+ logger.info(
+ "Dataset viewer rows unavailable: %s",
+ download_registry.scrub_secrets(str(e), hf_token = hf_token),
+ )
+ return None
+ body = body or {}
+ entries = body.get("rows") or []
+ expected = min(preview_size, body.get("num_rows_total") or preview_size)
+ features = json.dumps(body.get("features") or [])
+ if (
+ not entries
+ or len(entries) < expected
+ or any(entry.get("truncated_cells") for entry in entries)
+ or any(f'"_type": "{kind}"' in features for kind in _VIEWER_MEDIA_TYPES)
+ ):
+ return None
+ return [entry["row"] for entry in entries[:preview_size]]
+
+
+def load_preview_slice(
+ request: CheckFormatRequest,
+ hf_token,
+ preview_size: int,
+ *,
+ allow_unlabeled_tier1_fallback: bool = False,
+ viewer_rows: bool = False,
+):
+ """The first ``preview_size`` rows of a dataset and its total row count (None when unknown), read the
+ way check-format reads them: a local file directly, else the local cache, one data file, or a stream.
+ ``hf_token`` and the request paths must already be resolved for the account. ``viewer_rows`` asks the
+ Hub dataset viewer first."""
+ from itertools import islice
+
+ # An audio column decodes on the first preview row, so this precedes every tier.
+ ensure_audio_decoding()
+
+ try:
+ dataset_path = resolve_dataset_path(request.dataset_name)
+ except ValueError as e:
+ # Malformed path (null bytes, '..', outside roots) is a client error: surface 400, not 500.
+ raise HTTPException(status_code = 400, detail = str(e)) from e
+ total_rows = None
+
+ dataset_exists = dataset_path.exists()
+ if not dataset_exists and _is_local_dataset_ref(request.dataset_name):
+ raise HTTPException(status_code = 404, detail = _MISSING_DATASET_DETAIL)
+
+ # Both streaming tiers run on the default prefer_local_cache=false, ahead of the
+ # guarded cache reader below, so the gate stands in front of them.
+ if not dataset_exists:
+ refuse_unauthorized_dataset_preview(
+ hf_token,
+ request.dataset_name,
+ # A prefer-local request reads the cache or 404s below, either way without
+ # the network, so the probe would be a round trip it had ruled out.
+ offline = bool(request.prefer_local_cache),
+ )
+ if dataset_exists:
+ train_split = request.train_split or "train"
+ preview_slice, total_rows = _load_local_preview_slice(
+ dataset_path = dataset_path,
+ train_split = train_split,
+ preview_size = preview_size,
+ )
+ else:
+ from datasets import Dataset, load_dataset
+
+ # Tier 1: list_repo_files → load only the first data file
+ cached_preview = (
+ _load_any_cached_hf_preview_slice(request, preview_size, hf_token)
+ if request.prefer_local_cache
+ else None
+ )
+ if cached_preview is not None:
+ preview_slice, total_rows = cached_preview
+ elif request.prefer_local_cache:
+ raise HTTPException(
+ status_code = 404,
+ detail = {
+ "code": _LOCAL_CACHE_MISS_ERROR_CODE,
+ "message": "Dataset is not available in the local cache.",
+ },
+ )
+ elif viewer_rows and (viewer := _viewer_rows(request, hf_token, preview_size)):
+ preview_slice = Dataset.from_list(viewer)
+ else:
+ preview_slice = None
+
+ try:
+ from huggingface_hub import HfApi
+
+ # No token on the constructor: list_repo_files is given it explicitly
+ # and that argument wins.
+ api = HfApi()
+ repo_files = api.list_repo_files(
+ request.dataset_name,
+ repo_type = "dataset",
+ token = hf_token,
+ )
+ train_split = request.train_split or "train"
+ first_file = _select_tier1_repo_file(
+ repo_files,
+ subset = request.subset,
+ train_split = train_split,
+ allow_unlabeled_fallback = allow_unlabeled_tier1_fallback,
+ )
+ if first_file:
+ logger.info(f"Tier 1: loading single file {first_file}")
+ load_kwargs = {
+ "path": request.dataset_name,
+ "data_files": {train_split: [first_file]},
+ "split": train_split,
+ "streaming": True,
+ "token": hf_token,
+ }
+
+ # Recorded against the call that can materialise rows, not the
+ # listing above it: a preview writes into the datasets cache under
+ # what may be a one-off token, and unrecorded a later tokenless
+ # caller reads "none needed one". Recording before `list_repo_files`
+ # left a record for a fetch a 404 or outage never made.
+ with recording_a_request_token_fetch(hf_token, request.dataset_name, "dataset"):
+ streamed_ds = load_dataset(**load_kwargs)
+ rows = list(islice(streamed_ds, preview_size))
+ if rows:
+ preview_slice = Dataset.from_list(rows)
+ except Exception as e:
+ logger.warning(
+ "Tier 1 (single-file) failed: %s",
+ download_registry.scrub_secrets(str(e), hf_token = hf_token),
+ )
+
+ if preview_slice is None:
+ # Tier 2: full streaming (resolves all files - slow for large repos)
+ logger.info("Tier 2: falling back to full streaming load_dataset")
+ try:
+ load_kwargs = {
+ "path": request.dataset_name,
+ "split": request.train_split or "train",
+ "streaming": True,
+ "token": hf_token,
+ }
+ if request.subset:
+ load_kwargs["name"] = request.subset
+
+ # Tier 2 reaches the network on its own, whether or not tier 1 ran, and
+ # takes its record back if it fails having cached nothing.
+ with recording_a_request_token_fetch(hf_token, request.dataset_name, "dataset"):
+ streamed_ds = load_dataset(**load_kwargs)
+
+ rows = list(islice(streamed_ds, preview_size))
+ if not rows:
+ raise HTTPException(
+ status_code = 400,
+ detail = "Dataset appears to be empty or could not be streamed",
+ )
+
+ preview_slice = Dataset.from_list(rows)
+ total_rows = None
+ except Exception:
+ cached_preview = _load_any_cached_hf_preview_slice(
+ request,
+ preview_size,
+ hf_token,
+ )
+ if cached_preview is None:
+ raise
+ preview_slice, total_rows = cached_preview
+ return preview_slice, total_rows
+
+
def check_format_response(
request: CheckFormatRequest,
hf_token: Optional[str] = None,
@@ -390,147 +605,16 @@ def check_format_response(
account_path(request.dataset_name, reference = True)
visible_cached_path(getattr(request, "local_path", None), "dataset")
try:
- from itertools import islice
-
PREVIEW_SIZE = 10
logger.info(f"Checking format for dataset: {request.dataset_name}")
- # An audio column decodes on the first preview row, so this precedes every tier.
- ensure_audio_decoding()
-
- try:
- dataset_path = resolve_dataset_path(request.dataset_name)
- except ValueError as e:
- # Malformed path (null bytes, '..', outside roots) is a client error: surface 400, not 500.
- raise HTTPException(status_code = 400, detail = str(e)) from e
- total_rows = None
-
- dataset_exists = dataset_path.exists()
- if not dataset_exists and _is_local_dataset_ref(request.dataset_name):
- raise HTTPException(status_code = 404, detail = _MISSING_DATASET_DETAIL)
-
- # Both streaming tiers run on the default prefer_local_cache=false, ahead of the
- # guarded cache reader below, so the gate stands in front of them.
- if not dataset_exists:
- refuse_unauthorized_dataset_preview(
- hf_token,
- request.dataset_name,
- # A prefer-local request reads the cache or 404s below, either way without
- # the network, so the probe would be a round trip it had ruled out.
- offline = bool(request.prefer_local_cache),
- )
- if dataset_exists:
- train_split = request.train_split or "train"
- preview_slice, total_rows = _load_local_preview_slice(
- dataset_path = dataset_path,
- train_split = train_split,
- preview_size = PREVIEW_SIZE,
- )
- else:
- from datasets import Dataset, load_dataset
-
- # Tier 1: list_repo_files → load only the first data file
- cached_preview = (
- _load_any_cached_hf_preview_slice(request, PREVIEW_SIZE, hf_token)
- if request.prefer_local_cache
- else None
- )
- if cached_preview is not None:
- preview_slice, total_rows = cached_preview
- elif request.prefer_local_cache:
- raise HTTPException(
- status_code = 404,
- detail = {
- "code": _LOCAL_CACHE_MISS_ERROR_CODE,
- "message": "Dataset is not available in the local cache.",
- },
- )
- else:
- preview_slice = None
-
- try:
- from huggingface_hub import HfApi
-
- # No token on the constructor: list_repo_files is given it explicitly
- # and that argument wins.
- api = HfApi()
- repo_files = api.list_repo_files(
- request.dataset_name,
- repo_type = "dataset",
- token = hf_token,
- )
- train_split = request.train_split or "train"
- first_file = _select_tier1_repo_file(
- repo_files,
- subset = request.subset,
- train_split = train_split,
- allow_unlabeled_fallback = allow_unlabeled_tier1_fallback,
- )
- if first_file:
- logger.info(f"Tier 1: loading single file {first_file}")
- load_kwargs = {
- "path": request.dataset_name,
- "data_files": {train_split: [first_file]},
- "split": train_split,
- "streaming": True,
- "token": hf_token,
- }
-
- # Recorded against the call that can materialise rows, not the
- # listing above it: a preview writes into the datasets cache under
- # what may be a one-off token, and unrecorded a later tokenless
- # caller reads "none needed one". Recording before `list_repo_files`
- # left a record for a fetch a 404 or outage never made.
- with recording_a_request_token_fetch(
- hf_token, request.dataset_name, "dataset"
- ):
- streamed_ds = load_dataset(**load_kwargs)
- rows = list(islice(streamed_ds, PREVIEW_SIZE))
- if rows:
- preview_slice = Dataset.from_list(rows)
- except Exception as e:
- logger.warning(
- "Tier 1 (single-file) failed: %s",
- download_registry.scrub_secrets(str(e), hf_token = hf_token),
- )
-
- if preview_slice is None:
- # Tier 2: full streaming (resolves all files - slow for large repos)
- logger.info("Tier 2: falling back to full streaming load_dataset")
- try:
- load_kwargs = {
- "path": request.dataset_name,
- "split": request.train_split or "train",
- "streaming": True,
- "token": hf_token,
- }
- if request.subset:
- load_kwargs["name"] = request.subset
-
- # Tier 2 reaches the network on its own, whether or not tier 1 ran, and
- # takes its record back if it fails having cached nothing.
- with recording_a_request_token_fetch(hf_token, request.dataset_name, "dataset"):
- streamed_ds = load_dataset(**load_kwargs)
-
- rows = list(islice(streamed_ds, PREVIEW_SIZE))
- if not rows:
- raise HTTPException(
- status_code = 400,
- detail = "Dataset appears to be empty or could not be streamed",
- )
-
- preview_slice = Dataset.from_list(rows)
- total_rows = None
- except Exception:
- cached_preview = _load_any_cached_hf_preview_slice(
- request,
- PREVIEW_SIZE,
- hf_token,
- )
- if cached_preview is None:
- raise
- preview_slice, total_rows = cached_preview
+ preview_slice, total_rows = load_preview_slice(
+ request,
+ hf_token,
+ PREVIEW_SIZE,
+ allow_unlabeled_tier1_fallback = allow_unlabeled_tier1_fallback,
+ )
result = check_dataset_format(preview_slice, is_vlm = request.is_vlm)
diff --git a/studio/backend/models/training.py b/studio/backend/models/training.py
index cca32a8e6a3..0c270a0af29 100644
--- a/studio/backend/models/training.py
+++ b/studio/backend/models/training.py
@@ -783,6 +783,32 @@ class TrainingJobResponse(BaseModel):
error_code: Optional[str] = Field(None, description = "Stable error code if status is 'error'")
+class TokenPreviewRequest(BaseModel):
+ """How a training run would tokenize and mask a few dataset rows, or ``text`` when given. Only
+ the model's tokenizer is read, never its weights."""
+
+ model_name: str = Field(..., min_length = 1)
+ model_type: Optional[str] = None
+ load_in_4bit: bool = True
+ dataset_name: Optional[str] = None
+ subset: Optional[str] = None
+ train_split: Optional[str] = None
+ dataset_local_path: Optional[str] = None
+ dataset_known_cached: bool = False
+ format_type: str = "auto"
+ custom_format_mapping: Optional[Dict[str, Any]] = None
+ train_on_completions: bool = False
+ is_cpt: bool = False
+ max_seq_length: int = Field(2048, ge = 1, le = 1_048_576)
+ num_samples: int = Field(3, ge = 1, le = 8)
+ seed: int = 0
+ text: Optional[str] = Field(None, max_length = 200_000)
+ # The dataset's format from an earlier preview, so typed text gets the template and markers it would.
+ final_format: Optional[str] = None
+
+ _resolve_the_handles = field_validator("model_name", "dataset_name")(_resolve_inventory_handle)
+
+
class TrainingStartRequestStatus(BaseModel):
start_request_id: str
job_id: str
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index a78d772e8b7..b45308db5a4 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -96,7 +96,7 @@ except ImportError:
from utils.paths import is_local_path, normalize_path, resolve_dataset_path
from auth.authentication import authenticated_via_api_key, get_current_subject
-from hub.dependencies import get_hf_token
+from hub.dependencies import get_hf_token, get_request_hf_token
from hub.utils.host_paths import redact_host_paths
from hub.utils.hf_tokens import HfTokenArg, cached_read_refused, hf_token_arg
@@ -137,6 +137,7 @@ from models.training import (
DiffusionTrainingStatusResponse,
DiffusionTrainingStopRequest,
TRAINING_REQUEST_ID_PATTERN,
+ TokenPreviewRequest,
)
from models.responses import TrainingStopResponse, TrainingMetricsResponse
from pydantic import (
@@ -1735,6 +1736,122 @@ async def get_visible_hardware_utilization(current_subject: str = Depends(get_cu
return await asyncio.to_thread(get_visible_gpu_utilization)
+# As many head rows as prepare_raw_text_dataset scores to pick a column; the worker shows a few at random.
+_TOKEN_PREVIEW_POOL_ROWS = 100
+
+
+def _token_preview_rows(request: TokenPreviewRequest, hf_token) -> list[dict]:
+ from hub.schemas.datasets import CheckFormatRequest as HubCheckFormatRequest
+ from hub.services.datasets.formatting import load_preview_slice
+
+ from core.training.account_jobs import visible_cached_path
+
+ from hub.utils import download_registry
+ from hub.utils.hf_errors import hf_error_status
+
+ visible_cached_path(request.dataset_local_path, "dataset")
+ try:
+ rows, _ = load_preview_slice(
+ HubCheckFormatRequest(
+ dataset_name = request.dataset_name,
+ subset = request.subset,
+ train_split = request.train_split or "train",
+ prefer_local_cache = request.dataset_known_cached
+ and bool(request.dataset_local_path),
+ local_path = request.dataset_local_path,
+ ),
+ hf_token,
+ _TOKEN_PREVIEW_POOL_ROWS,
+ viewer_rows = True,
+ )
+ except HTTPException:
+ raise
+ except Exception as exc:
+ raise HTTPException(
+ status_code = hf_error_status(exc) or 400,
+ detail = download_registry.scrub_secrets(str(exc), hf_token = hf_token),
+ ) from exc
+ return rows.to_list()
+
+
[email protected]("/token-preview")
+async def token_preview(
+ request: TokenPreviewRequest,
+ hf_token: HfTokenArg = Depends(get_request_hf_token),
+ current_subject: str = Depends(get_current_subject),
+):
+ """Tokens and completion mask for a few rows of the selected dataset, or for ``text``, as
+ training would produce them. Loads the tokenizer only, in a GPU-free subprocess."""
+ from core.training.token_preview import (
+ TokenPreviewError,
+ run_token_preview,
+ )
+ from core.training.training import should_use_mlx_training_backend
+ from routes.models import _require_model_access_or_caller_token
+ from utils.account_context import current_account_id
+ from hub.utils.hf_tokens import recording_a_request_token_fetch
+ from utils.models.unsloth_mirror import unsloth_public_mirror
+ from utils.paths import is_local_path
+ from utils.utils import anonymous_and_offline
+
+ if request.text is None and not request.dataset_name:
+ raise HTTPException(status_code = 400, detail = "Pick a dataset or type a text to preview.")
+ hf_token = account_hf_token(hf_token)
+ model_name = request.model_name.strip()
+ account_path(model_name, reference = True)
+ if request.dataset_name:
+ account_path(request.dataset_name, reference = True)
+ await _require_model_access_or_caller_token(model_name, hf_token)
+ # By repo id, not the picked cache folder: a cached repo still resolves from disk, and a folder
+ # path would skip the account checks above.
+ # Same repo the trainer reads: MLX loads the picked name as given (see _metadata_lookup_name).
+ source = model_name
+ if not should_use_mlx_training_backend():
+ source = unsloth_public_mirror(model_name, request.load_in_4bit) or model_name
+ remote = not is_local_path(source)
+ if remote and anonymous_and_offline(hf_token, repo_id = source):
+ raise HTTPException(status_code = 404, detail = "This model is not available offline.")
+
+ def _run() -> dict:
+ rows = None if request.text is not None else _token_preview_rows(request, hf_token)
+ payload = {
+ "rows": rows,
+ "text": request.text,
+ "final_format": request.final_format,
+ "dataset_name": request.dataset_name,
+ "format_type": request.format_type,
+ "custom_format_mapping": request.custom_format_mapping,
+ "raw_text": request.is_cpt or request.format_type == "raw",
+ "is_cpt": request.is_cpt,
+ # The trainer never masks audio models or DeepSeek OCR (it skips apply_completion_masking).
+ "train_on_completions": request.train_on_completions
+ and not request.is_cpt
+ and request.model_type != "audio"
+ and not ("deepseek" in model_name.lower() and "ocr" in model_name.lower()),
+ "max_seq_length": request.max_seq_length,
+ "num_samples": request.num_samples,
+ "seed": request.seed,
+ }
+ key = (current_account_id(), model_name, source, hf_token)
+ # The tokenizer is loaded only when a worker starts, and which files that load resolves is not
+ # known up front, so every load is recorded; a warm worker fetches nothing.
+ return run_token_preview(
+ key,
+ {"model_name": model_name, "tokenizer_source": source, "hf_token": hf_token},
+ payload,
+ (lambda: recording_a_request_token_fetch(hf_token, source, "model"))
+ if remote
+ else None,
+ )
+
+ try:
+ return await asyncio.to_thread(_run)
+ except TokenPreviewError as exc:
+ from hub.utils import download_registry
+ detail = download_registry.scrub_secrets(str(exc), hf_token = hf_token)
+ raise HTTPException(status_code = 422, detail = detail) from exc
+
+
@router.get("/start-requests/{start_request_id}", response_model = TrainingStartRequestStatus)
async def get_training_start_request(
start_request_id: str = ApiPath(
@@ -1844,6 +1961,10 @@ async def start_training(
status_code = 400,
detail = "Drafter training is not available on Apple Silicon (MLX) yet.",
)
+ from core.training.token_preview import stop_token_preview_worker
+
+ # The run needs the host RAM more than the preview needs to stay warm; reaped off the request path.
+ threading.Thread(target = stop_token_preview_worker, daemon = True).start()
if managed_account():
from utils.paths import tensorboard_root
diff --git a/studio/backend/tests/test_hub_token_caller_identity.py b/studio/backend/tests/test_hub_token_caller_identity.py
index 471c2decb3f..284c000a194 100644
--- a/studio/backend/tests/test_hub_token_caller_identity.py
+++ b/studio/backend/tests/test_hub_token_caller_identity.py
@@ -1541,7 +1541,7 @@ def test_every_offline_reachable_route_refuses_before_it_reads(monkeypatch):
for owner, name in (
(models_routes.get_model_config, "/config"),
(models_routes.scan_model_remote_code, "scan-remote-code"),
- (formatting.check_format_response, "check-format"),
+ (formatting.load_preview_slice, "check-format"),
):
source = inspect.getsource(owner)
assert any(
diff --git a/studio/backend/tests/test_offline_local_cache_discovery.py b/studio/backend/tests/test_offline_local_cache_discovery.py
index c9f21b54151..a22e503cdc6 100644
--- a/studio/backend/tests/test_offline_local_cache_discovery.py
+++ b/studio/backend/tests/test_offline_local_cache_discovery.py
@@ -493,7 +493,7 @@ def _fetch_sites():
"diffusion-load": _source(inference_routes.load_diffusion_model_gated),
"video-load": _source(video_routes.load_video_model_gated),
}
- preview = _source(formatting.check_format_response)
+ preview = _source(formatting.load_preview_slice)
picker = _source(picker_module)
config_read = _source(model_config_module)
return {
@@ -534,7 +534,7 @@ _PRESENT = [
("download-lifecycle", "note_repo_fetched_with_a_request_token(hf_token, repo_id, repo_type)"),
(
"dataset-preview",
- "recording_a_request_token_fetch(\n hf_token, request.dataset_name",
+ "recording_a_request_token_fetch(hf_token, request.dataset_name",
),
("picker-template", "recording_a_request_token_fetch(hf_token, resolved"),
("config-read", "recording_a_request_token_fetch(token, model_name"),
diff --git a/studio/backend/tests/test_token_preview.py b/studio/backend/tests/test_token_preview.py
new file mode 100644
index 00000000000..c59246d50fc
--- /dev/null
+++ b/studio/backend/tests/test_token_preview.py
@@ -0,0 +1,499 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import asyncio
+import contextlib
+import importlib.util
+import os
+import sys
+import threading
+import types
+
+import pytest
+from datasets import Dataset
+from fastapi import HTTPException
+
+from core.training import token_preview, token_preview_worker
+from models.training import TokenPreviewRequest
+
+
+def _call_route(request: TokenPreviewRequest):
+ from routes import training as training_routes
+ return asyncio.run(
+ training_routes.token_preview(request, hf_token = None, current_subject = "owner")
+ )
+
+
+def captured(monkeypatch):
+ from hub.services.datasets import formatting
+
+ calls = []
+ rows = Dataset.from_list([{"text": f"row {i}"} for i in range(100)])
+ monkeypatch.setattr(formatting, "load_preview_slice", lambda *args, **kwargs: (rows, 64))
+ monkeypatch.setattr(
+ token_preview,
+ "run_token_preview",
+ lambda key, config, payload, record_load = None: calls.append((key, config, payload))
+ or {"samples": []},
+ )
+ return calls
+
+
+def test_a_request_without_a_dataset_or_text_is_refused(captured):
+ with pytest.raises(HTTPException) as excinfo:
+ _call_route(TokenPreviewRequest(model_name = "unsloth/Qwen3-0.6B"))
+ assert excinfo.value.status_code == 400
+ assert captured == []
+
+
+def test_the_pool_and_the_run_settings_reach_the_worker(captured):
+ _call_route(
+ TokenPreviewRequest(
+ model_name = "unsloth/Qwen3-0.6B",
+ dataset_name = "org/data",
+ num_samples = 3,
+ seed = 1,
+ train_on_completions = True,
+ max_seq_length = 512,
+ )
+ )
+ payload = captured[-1][2]
+ assert len(payload["rows"]) == 100
+ assert (payload["num_samples"], payload["seed"]) == (3, 1)
+ assert payload["train_on_completions"] is True
+ assert payload["raw_text"] is False
+ assert payload["max_seq_length"] == 512
+ assert captured[-1][1]["model_name"] == "unsloth/Qwen3-0.6B"
+
+
+def test_samples_are_drawn_by_seed():
+ texts = [f"row {i}" for i in range(64)]
+ first = token_preview_worker._sample(texts, 3, 1)
+ assert len(first) == 3
+ assert token_preview_worker._sample(texts, 3, 1) == first
+ assert token_preview_worker._sample(texts, 3, 2) != first
+ assert token_preview_worker._sample(texts[:2], 3, 1) == texts[:2]
+
+
+def test_continued_pretraining_trains_every_token(captured):
+ _call_route(
+ TokenPreviewRequest(
+ model_name = "unsloth/Qwen3-0.6B",
+ dataset_name = "org/data",
+ is_cpt = True,
+ train_on_completions = True,
+ )
+ )
+ payload = captured[-1][2]
+ assert payload["raw_text"] is True
+ assert payload["train_on_completions"] is False
+
+
+def test_typed_text_reads_no_dataset(captured, monkeypatch):
+ from hub.services.datasets import formatting
+
+ monkeypatch.setattr(
+ formatting,
+ "load_preview_slice",
+ lambda *args, **kwargs: pytest.fail("typed text must not read the dataset"),
+ )
+ _call_route(
+ TokenPreviewRequest(model_name = "unsloth/Qwen3-0.6B", dataset_name = "org/data", text = "hi")
+ )
+ assert captured[-1][2]["rows"] is None
+ assert captured[-1][2]["text"] == "hi"
+
+
+class _ByteTokenizer:
+ def decode(self, ids):
+ return "�"
+
+
+def test_a_partial_byte_level_piece_shows_its_bytes():
+ # Llama 3 splits " ű" into "ĠÅ" (space + 0xC5) and "±" (0xB1).
+ assert token_preview_worker._token_text(_ByteTokenizer(), 1, "ĠÅ") == " <0xC5>"
+ assert token_preview_worker._token_text(_ByteTokenizer(), 2, "±") == "<0xB1>"
+ # SentencePiece byte fallback already names the byte.
+ assert token_preview_worker._token_text(_ByteTokenizer(), 3, "<0xC5>") == "<0xC5>"
+
+
+def test_masking_goes_through_apply_completion_masking(monkeypatch):
+ def fake_train_on_responses_only(
+ trainer,
+ instruction_part = None,
+ response_part = None,
+ tokenizer = None,
+ return_function = False,
+ ):
+ assert trainer is None and return_function
+ return lambda batch: {"labels": [[-100, -100] + ids[2:] for ids in batch["input_ids"]]}
+
+ monkeypatch.setitem(
+ sys.modules,
+ "unsloth.chat_templates",
+ types.SimpleNamespace(train_on_responses_only = fake_train_on_responses_only),
+ )
+ tokenizer = types.SimpleNamespace(
+ _unsloth_input_part = "<user>", _unsloth_output_part = "<assistant>"
+ )
+ labels, masking = token_preview_worker._mask(
+ tokenizer, "org/model", {"input_ids": [[1, 2, 3, 4]]}, "chatml_messages"
+ )
+ assert labels == [[-100, -100, 3, 4]]
+ assert masking["applied"] is True
+ assert masking["response_part"] == "<assistant>"
+
+
+def test_stop_does_not_wait_behind_a_preview_in_flight():
+ service = token_preview._TokenPreviewService()
+ terminated = threading.Event()
+ service._proc = types.SimpleNamespace(is_alive = lambda: True, terminate = terminated.set)
+ with service._lock:
+ service.stop()
+ assert terminated.is_set()
+
+
+_TINY = "trl-internal-testing/tiny-Qwen3ForCausalLM"
+
+
+def real_worker():
+ if os.environ.get("HF_HUB_OFFLINE") == "1":
+ pytest.skip("needs the Hub for the tiny tokenizer")
+ config = {"model_name": _TINY, "tokenizer_source": _TINY, "hf_token": None}
+
+ def run(**payload):
+ return token_preview.run_token_preview(("owner", _TINY, _TINY, None), config, payload)
+
+ yield run
+ token_preview.stop_token_preview_worker()
+
+
+def test_the_subprocess_tokenizes_and_masks_typed_text(real_worker):
+ text = "Árvíztűrő ű ő"
+ plain = real_worker(text = text, train_on_completions = False, max_seq_length = 128)
+ sample = plain["samples"][0]
+ assert sample["num_tokens"] == sample["num_trained"] > 0
+ assert all(isinstance(token[0], int) for token in sample["tokens"])
+
+ if importlib.util.find_spec("torch") is None:
+ pytest.skip("completion masking needs torch, as it does for training")
+ chat = "<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\nhello<|im_end|>\n"
+ masked = real_worker(text = chat, train_on_completions = True, max_seq_length = 128)
+ assert masked["masking"]["applied"] is True
+ trained = "".join(
+ piece for _, piece, is_trained in masked["samples"][0]["tokens"] if is_trained
+ )
+ assert trained.startswith("hello") and "user" not in trained
+
+
+def test_typed_text_carries_the_dataset_format(captured):
+ _call_route(
+ TokenPreviewRequest(model_name = "unsloth/Qwen3-0.6B", text = "hi", final_format = "alpaca")
+ )
+ assert captured[-1][2]["final_format"] == "alpaca"
+
+
+def test_a_tokenizer_load_failure_ends_the_worker(monkeypatch):
+ service = token_preview._TokenPreviewService()
+ stopped = []
+ replies = [{"id": 1, "ok": False, "error": "offline", "fatal": True}]
+
+ def fake_start(key, config):
+ service._proc = types.SimpleNamespace(is_alive = lambda: True)
+ service._cmd_queue = types.SimpleNamespace(put = lambda item: None)
+ service._resp_queue = types.SimpleNamespace(get = lambda timeout: replies.pop(0))
+ service._key, service._served = key, False
+
+ monkeypatch.setattr(service, "_start_locked", fake_start)
+ monkeypatch.setattr(service, "_stop_locked", lambda: stopped.append(True))
+ with pytest.raises(token_preview.TokenPreviewError, match = "offline"):
+ service.preview(("k",), {}, {"text": "hi"})
+ assert stopped[-1] is True
+
+
+def test_a_supplied_cache_folder_is_never_the_tokenizer_source(captured):
+ _call_route(
+ TokenPreviewRequest.model_validate(
+ {
+ "model_name": "unsloth/Qwen3-0.6B",
+ "text": "hi",
+ "model_known_cached": True,
+ "model_local_path": "/somewhere/else",
+ }
+ )
+ )
+ assert "/somewhere" not in captured[-1][1]["tokenizer_source"]
+
+
+class _LegacySentencePiece:
+ def decode(self, ids):
+ return "quick"
+
+
+def test_a_sentencepiece_word_keeps_its_leading_space():
+ assert token_preview_worker._token_text(_LegacySentencePiece(), 1, "▁quick") == " quick"
+
+
+def test_audio_models_train_every_token_as_training_does(captured):
+ _call_route(
+ TokenPreviewRequest(
+ model_name = "unsloth/orpheus-3b-0.1-ft",
+ model_type = "audio",
+ text = "hi",
+ train_on_completions = True,
+ )
+ )
+ assert captured[-1][2]["train_on_completions"] is False
+
+
+def test_retiring_an_account_stops_its_preview_worker():
+ from core.training import account_jobs
+ from utils.account_context import AccountContext
+
+ service = token_preview._TokenPreviewService()
+ stopped = threading.Event()
+ service._proc = types.SimpleNamespace(is_alive = lambda: True, terminate = stopped.set)
+ account = AccountContext(account_id = "alice", username = "alice")
+ service._result_account = account
+ service.stop = lambda: stopped.set()
+ service._account_cancel = service.stop
+ assert service in set(account_jobs._services)
+ try:
+ account_jobs.retire_account_jobs(account)
+ except RuntimeError:
+ pass # the stand-in process never reports itself stopped
+ finally:
+ account_jobs._retired.discard("alice")
+ assert stopped.is_set()
+
+
+def test_an_adapter_base_is_never_fetched(monkeypatch):
+ import transformers
+ from utils.models import model_config
+
+ tried = []
+
+ def from_pretrained(source, **kwargs):
+ tried.append(source)
+ raise OSError("no tokenizer files")
+
+ monkeypatch.setattr(transformers.AutoTokenizer, "from_pretrained", from_pretrained)
+ monkeypatch.setattr(
+ model_config, "get_base_model_from_lora_identifier", lambda *args: "org/private-base"
+ )
+ with pytest.raises(OSError):
+ token_preview_worker._load_tokenizer({"model_name": "org/adapter", "hf_token": None})
+ assert set(tried) == {"org/adapter"}
+
+
+def test_inventory_handles_are_resolved(monkeypatch):
+ import models.inference as inference
+
+ monkeypatch.setattr(
+ inference, "resolve_inventory_handle", lambda v: v.replace("ref:", "/real/")
+ )
+ request = TokenPreviewRequest(model_name = "ref:abc", dataset_name = "ref:def", text = "hi")
+ assert (request.model_name, request.dataset_name) == ("/real/abc", "/real/def")
+
+
+def test_a_stop_during_a_preview_ends_the_worker_it_started(monkeypatch):
+ service = token_preview._TokenPreviewService()
+ stopped = []
+
+ def fake_start(key, config):
+ service._proc = types.SimpleNamespace(
+ is_alive = lambda: False,
+ terminate = lambda: None,
+ join = lambda timeout: None,
+ exitcode = 0,
+ pid = None,
+ )
+ service._cmd_queue = types.SimpleNamespace(put = lambda item: service.stop())
+ service._resp_queue = types.SimpleNamespace(
+ get = lambda timeout: {"id": 1, "ok": True, "result": {}}
+ )
+ service._key, service._served = key, False
+
+ real_stop_locked = service._stop_locked
+ monkeypatch.setattr(service, "_start_locked", fake_start)
+ monkeypatch.setattr(service, "_stop_locked", lambda: (stopped.append(True), real_stop_locked()))
+ service.preview(("k",), {}, {"text": "hi"})
+ assert len(stopped) == 2 and service._proc is None
+
+
+def _viewer(
+ monkeypatch,
+ body,
+ status = 200,
+):
+ import httpx
+
+ from hub.services.datasets import formatting
+ from hub.schemas.datasets import CheckFormatRequest
+
+ calls = []
+
+ def fake_get(url, **kwargs):
+ calls.append((url, kwargs))
+ return types.SimpleNamespace(status_code = status, json = lambda: body)
+
+ monkeypatch.setattr(httpx, "get", fake_get)
+ for var in ("HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE", "HF_DATASETS_SERVER", "HF_ENDPOINT"):
+ monkeypatch.delenv(var, raising = False)
+ request = CheckFormatRequest(dataset_name = "org/data", train_split = "train")
+ return lambda: formatting._viewer_rows(request, "hf_x", 100), calls
+
+
+def _rows(n, **extra):
+ return [
+ {"row_idx": i, "row": {"text": f"row {i}"}, "truncated_cells": [], **extra}
+ for i in range(n)
+ ]
+
+
+def test_viewer_rows_stand_in_only_when_complete(monkeypatch):
+ features = [{"name": "text", "type": {"dtype": "string", "_type": "Value"}}]
+ rows, calls = _viewer(
+ monkeypatch, {"rows": _rows(100), "features": features, "num_rows_total": 5000}
+ )
+ assert rows() == [{"text": f"row {i}"} for i in range(100)]
+ assert calls[0][0].endswith("/rows") and calls[0][1]["params"]["length"] == 100
+ assert calls[0][1]["headers"] == {"Authorization": "Bearer hf_x"}
+ # A dataset smaller than the pool is complete at its own size.
+ rows, _ = _viewer(monkeypatch, {"rows": _rows(7), "features": features, "num_rows_total": 7})
+ assert len(rows()) == 7
+ # Short, cut or media answers fall back to streaming.
+ for body in (
+ {"rows": _rows(28), "features": features, "num_rows_total": 5000},
+ {"rows": _rows(100, truncated_cells = ["text"]), "features": features},
+ {"rows": _rows(100), "features": [{"name": "image", "type": {"_type": "Image"}}]},
+ {"error": "not ready"},
+ ):
+ rows, _ = _viewer(monkeypatch, body)
+ assert rows() is None
+ rows, _ = _viewer(monkeypatch, {"rows": _rows(100), "features": features}, status = 404)
+ assert rows() is None
+
+
+def test_viewer_is_not_asked_offline_or_behind_a_mirror(monkeypatch):
+ from utils import hf_endpoint
+
+ rows, calls = _viewer(monkeypatch, {"rows": _rows(100)})
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ assert rows() is None
+ monkeypatch.delenv("HF_HUB_OFFLINE")
+ monkeypatch.setattr(hf_endpoint, "browser_hf_endpoint", lambda: "https://hf-mirror.com")
+ assert rows() is None
+ assert calls == []
+
+
+def test_only_the_token_preview_asks_the_viewer(monkeypatch):
+ import inspect
+
+ from hub.services.datasets import formatting
+ from routes import training as training_routes
+
+ assert "viewer_rows = True" in inspect.getsource(training_routes._token_preview_rows)
+ assert "viewer_rows" not in inspect.getsource(formatting.check_format_response)
+
+
+def _scripted_service(monkeypatch, alive_key = None):
+ service = token_preview._TokenPreviewService()
+ starts = []
+
+ def fake_start(key, config):
+ starts.append(key)
+ service._proc = types.SimpleNamespace(is_alive = lambda: True)
+ service._cmd_queue = types.SimpleNamespace(
+ put = lambda item: service._replies.append({"id": item["id"], "ok": True, "result": {}})
+ )
+ service._resp_queue = types.SimpleNamespace(get = lambda timeout: service._replies.pop(0))
+ service._key, service._served = key, False
+
+ service._replies = []
+ monkeypatch.setattr(service, "_start_locked", fake_start)
+ monkeypatch.setattr(service, "_stop_locked", lambda: None)
+ if alive_key is not None:
+ fake_start(alive_key, {})
+ service._served = True
+ return service, starts
+
+
+def test_a_load_is_recorded_whenever_the_request_starts_a_worker(monkeypatch):
+ recorded = []
+
+ def record():
+ recorded.append(True)
+ return contextlib.nullcontext()
+
+ # Warm for the same key: nothing loads, nothing is recorded.
+ service, starts = _scripted_service(monkeypatch, alive_key = ("a",))
+ service.preview(("a",), {}, {"text": "hi"}, record)
+ assert recorded == [] and starts == [("a",)]
+ # Another request swapped the worker in between: this one starts a worker, so it records.
+ service._key = ("b",)
+ service.preview(("a",), {}, {"text": "hi"}, record)
+ assert recorded == [True] and starts[-1] == ("a",)
+
+
+def test_a_retired_account_never_spawns_a_preview_worker(monkeypatch):
+ from core.training import account_jobs
+
+ service = token_preview._TokenPreviewService()
+ spawned = []
+ monkeypatch.setattr(
+ service, "_spawn_locked", lambda key, config: spawned.append(service._account_inflight)
+ )
+ monkeypatch.setattr(account_jobs, "account_is_retired", lambda: True)
+ with pytest.raises(token_preview.TokenPreviewError):
+ service._start_locked(("k",), {})
+ assert spawned == []
+ monkeypatch.setattr(account_jobs, "account_is_retired", lambda: False)
+ service._start_locked(("k",), {})
+ # Retirement sees the start in flight (and refuses) for the whole spawn.
+ assert spawned == [1] and service._account_inflight == 0
+
+
+def test_the_pretokenized_constant_matches_the_training_one():
+ from utils.datasets.pretokenized import PRETOKENIZED_FORMAT
+ assert token_preview_worker.PRETOKENIZED_FORMAT == PRETOKENIZED_FORMAT
+
+
+class _IdTokenizer:
+ chat_template = "x"
+ bos_token = eos_token = None
+
+ def convert_ids_to_tokens(self, ids):
+ return [f"t{i}" for i in ids]
+
+ def decode(self, ids):
+ return " ".join(f"t{i}" for i in ids)
+
+ def __len__(self):
+ return 100
+
+
+def test_pretokenized_rows_show_their_own_ids_and_labels(monkeypatch):
+ import utils.datasets as datasets_pkg
+ from utils.datasets import chat_templates
+
+ rows = [{"input_ids": [1, 2, 3, 4, 5], "labels": [-100, -100, 3, 4, 5]}]
+ monkeypatch.setattr(
+ datasets_pkg,
+ "format_and_template_dataset",
+ lambda dataset, **kwargs: {"dataset": dataset, "final_format": "pretokenized"},
+ )
+ monkeypatch.setattr(chat_templates, "get_training_chat_template", lambda tok, *args: tok)
+ tokenizer = _IdTokenizer()
+ out = token_preview_worker._preview(
+ tokenizer,
+ {"model_name": "m"},
+ {"rows": rows, "train_on_completions": True, "max_seq_length": 4},
+ )
+ sample = out["samples"][0]
+ assert out["final_format"] == "pretokenized"
+ assert [token[0] for token in sample["tokens"]] == [1, 2, 3, 4]
+ assert [token[2] for token in sample["tokens"]] == [False, False, True, True]
+ assert sample["truncated_from"] == 5 and out["masking"]["applied"] is False
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index 521941bc72b..da84b71bcfc 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -167,8 +167,12 @@ export const BUDGET = {
// the resident-config check) adds 1,448 B raw / 433 B transfer, inline in the eager chat chunk (6,787,367 ->
// 6,788,815 B raw, 2,040,805 -> 2,041,238 B transfer against 4494fa58c, one machine and build, Node 24, chunk
// count unchanged at 95). Raised by that growth.
- transferBytes: 2_041_433,
- rawBytes: 6_788_948,
+ // The Train tab's Preview tokens button, its dialog and strings (#13850) add 2,233 B raw / 858 B transfer
+ // (6,788,764 -> 6,790,997 B raw, 2,041,243 -> 2,042,101 B transfer against 5e5511027, one machine and build,
+ // Node 24, chunk count unchanged at 95). Lazy-loading the dialog cost more (2.7 KB transfer) and a 96th
+ // startup chunk, so it is imported statically and the budget raised by that growth.
+ transferBytes: 2_042_291,
+ rawBytes: 6_791_181,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/src/features/studio/sections/dataset-selection.tsx b/studio/frontend/src/features/studio/sections/dataset-selection.tsx
index 32c5cd11184..7471720fe66 100644
--- a/studio/frontend/src/features/studio/sections/dataset-selection.tsx
+++ b/studio/frontend/src/features/studio/sections/dataset-selection.tsx
@@ -20,10 +20,12 @@ import {
import { useT } from "@/i18n";
import { FileAttachmentIcon, ViewIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { useEffect, useMemo } from "react";
+import { TextSelectIcon } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
import { useShallow } from "zustand/react/shallow";
import { formatUpdatedDate } from "./dataset-panel-helpers";
import { EvaluationDatasetUpload } from "./dataset-upload";
+import { TokenPreviewDialog } from "./token-preview-dialog";
import type { DatasetUploads } from "./use-dataset-uploads";
function DatasetSubsetConfiguration({
@@ -153,6 +155,20 @@ function DatasetConfiguration({
return <LocalDatasetMetadata dataset={selectedLocalDataset} />;
}
+/** Text SFT runs only: embedding and decision models train no tokens a chat mask would pick. */
+function canPreviewTokens(state: {
+ selectedModel: string | null;
+ modelType: string | null;
+ isEmbeddingModel: boolean;
+}): boolean {
+ return (
+ !!state.selectedModel &&
+ !state.isEmbeddingModel &&
+ state.modelType !== "embeddings" &&
+ state.modelType !== "decision"
+ );
+}
+
function SelectedDatasetCard({
selectedLocalDataset,
}: {
@@ -162,8 +178,11 @@ function SelectedDatasetCard({
const openPreview = useDatasetPreviewDialogStore(
(state) => state.openPreview,
);
+ const [tokenPreviewOpen, setTokenPreviewOpen] = useState(false);
const settings = useTrainingConfigStore(
useShallow((state) => ({
+ canPreviewTokens: canPreviewTokens(state),
+ isCheckingDataset: state.isCheckingDataset,
dataset: state.dataset,
datasetSource: state.datasetSource,
datasetSplit: state.datasetSplit,
@@ -235,6 +254,19 @@ function SelectedDatasetCard({
<HugeiconsIcon icon={ViewIcon} className="size-3.5" />
{t("studio.dataset.viewDataset")}
</Button>
+ {settings.canPreviewTokens ? (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="shrink-0 text-xs"
+ // The dialog reads the dataset's modality once, so wait until the check has it.
+ disabled={settings.isCheckingDataset}
+ onClick={() => setTokenPreviewOpen(true)}
+ >
+ <TextSelectIcon className="size-3.5" />
+ {t("studio.dataset.previewTokens")}
+ </Button>
+ ) : null}
<Button
variant="ghost"
size="sm"
@@ -244,6 +276,9 @@ function SelectedDatasetCard({
{t("studio.dataset.clear")}
</Button>
</div>
+ {tokenPreviewOpen ? (
+ <TokenPreviewDialog open={true} onOpenChange={setTokenPreviewOpen} />
+ ) : null}
</div>
);
}
diff --git a/studio/frontend/src/features/studio/sections/token-preview-dialog.tsx b/studio/frontend/src/features/studio/sections/token-preview-dialog.tsx
new file mode 100644
index 00000000000..50724b4be81
--- /dev/null
+++ b/studio/frontend/src/features/studio/sections/token-preview-dialog.tsx
@@ -0,0 +1,499 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Spinner } from "@/components/ui/spinner";
+import { Switch } from "@/components/ui/switch";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { Textarea } from "@/components/ui/textarea";
+import { useHfTokenStore } from "@/features/hub";
+import {
+ type PreviewToken,
+ type TokenPreviewResponse,
+ type TokenPreviewSample,
+ type TrainingConfigState,
+ fetchTokenPreview,
+ useTrainingConfigStore,
+} from "@/features/training";
+import { useT } from "@/i18n";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
+import { toast } from "@/lib/toast";
+import { cn } from "@/lib/utils";
+import { CopyIcon, ShuffleIcon, TextSelectIcon } from "lucide-react";
+import { type ReactNode, memo, useEffect, useMemo, useState } from "react";
+
+// Neighbouring tokens alternate shades so their boundaries stay visible.
+const TRAINED_SHADES = [
+ "bg-emerald-500/20 text-foreground",
+ "bg-sky-500/20 text-foreground",
+ "bg-amber-500/25 text-foreground",
+ "bg-violet-500/20 text-foreground",
+];
+const MASKED_SHADES = [
+ "bg-muted text-muted-foreground/80",
+ "bg-muted/50 text-muted-foreground/80",
+];
+const TEXT_DEBOUNCE_MS = 300;
+
+type PreviewState = {
+ data: TokenPreviewResponse | null;
+ error: string | null;
+ loading: boolean;
+};
+
+const IDLE: PreviewState = { data: null, error: null, loading: false };
+
+function visibleText(text: string): string {
+ if (text === "") {
+ return "∅";
+ }
+ return text.replace(/\t/g, "→").replace(/\n/g, "↵\n");
+}
+
+const TokenStream = memo(function TokenStream({
+ tokens,
+ showIds,
+}: {
+ tokens: PreviewToken[];
+ showIds: boolean;
+}) {
+ return (
+ <div className="font-mono text-[12.5px] leading-6 whitespace-pre-wrap break-words">
+ {tokens.map(([id, text, trained], index) => (
+ <span
+ // biome-ignore lint/suspicious/noArrayIndexKey: tokens are positional
+ key={index}
+ title={`#${index} id ${id}`}
+ className={cn(
+ "rounded-[3px] px-px",
+ trained
+ ? TRAINED_SHADES[index % TRAINED_SHADES.length]
+ : MASKED_SHADES[index % MASKED_SHADES.length],
+ )}
+ >
+ {visibleText(text)}
+ {showIds ? (
+ <sub className="ml-0.5 text-[9px] opacity-60">{id}</sub>
+ ) : null}
+ </span>
+ ))}
+ </div>
+ );
+});
+
+function Legend() {
+ const t = useT();
+ return (
+ <div className="flex items-center gap-3 text-xs text-muted-foreground">
+ <span className="flex items-center gap-1.5">
+ <span className="size-3 rounded-[3px] bg-emerald-500/30" />
+ {t("studio.dataset.tokenPreview.trained")}
+ </span>
+ <span className="flex items-center gap-1.5">
+ <span className="size-3 rounded-[3px] bg-muted ring-1 ring-border" />
+ {t("studio.dataset.tokenPreview.masked")}
+ </span>
+ </div>
+ );
+}
+
+function SampleCard({
+ sample,
+ label,
+ showIds,
+ maskingApplied,
+}: {
+ sample: TokenPreviewSample;
+ label?: string;
+ showIds: boolean;
+ maskingApplied: boolean;
+}) {
+ const t = useT();
+ const percent =
+ sample.num_tokens > 0
+ ? Math.round((100 * sample.num_trained) / sample.num_tokens)
+ : 0;
+ const copyIds = async () => {
+ if (await copyToClipboard(JSON.stringify(sample.input_ids))) {
+ toast.success(t("studio.dataset.tokenPreview.copied"));
+ }
+ };
+ return (
+ <div className="flex flex-col gap-2 rounded-xl border bg-card p-3">
+ <div className="flex flex-wrap items-center gap-2 text-xs">
+ {label ? <span className="font-medium">{label}</span> : null}
+ <span className="text-muted-foreground">
+ {t("studio.dataset.tokenPreview.stats", {
+ tokens: sample.num_tokens.toLocaleString(),
+ trained: sample.num_trained.toLocaleString(),
+ percent,
+ })}
+ </span>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="ml-auto h-6 px-2 text-xs"
+ onClick={copyIds}
+ >
+ <CopyIcon className="size-3" />
+ {t("studio.dataset.tokenPreview.copyIds")}
+ </Button>
+ </div>
+ {maskingApplied && sample.num_trained === 0 ? (
+ <p className="text-xs text-amber-600 dark:text-amber-400">
+ {t("studio.dataset.tokenPreview.noTrained")}
+ </p>
+ ) : null}
+ {sample.truncated_from ? (
+ <p className="text-xs text-amber-600 dark:text-amber-400">
+ {t("studio.dataset.tokenPreview.truncated", {
+ max: sample.num_tokens.toLocaleString(),
+ full: sample.truncated_from.toLocaleString(),
+ })}
+ </p>
+ ) : null}
+ <TokenStream tokens={sample.tokens} showIds={showIds} />
+ {sample.num_hidden > 0 ? (
+ <p className="text-xs text-muted-foreground">
+ {t("studio.dataset.tokenPreview.hiddenTokens", {
+ count: sample.num_hidden.toLocaleString(),
+ })}
+ </p>
+ ) : null}
+ </div>
+ );
+}
+
+function MaskingSummary({
+ data,
+ requested,
+}: {
+ data: TokenPreviewResponse;
+ requested: boolean;
+}) {
+ const t = useT();
+ if (data.masking.applied) {
+ return (
+ <div className="flex flex-wrap items-center gap-2 text-xs">
+ <Badge variant="secondary">
+ {t("studio.dataset.tokenPreview.completionsOnly")}
+ </Badge>
+ {data.masking.response_part ? (
+ <span className="text-muted-foreground">
+ {t("studio.dataset.tokenPreview.responseMarker")}{" "}
+ <code className="rounded bg-muted px-1 py-0.5 font-mono">
+ {JSON.stringify(data.masking.response_part)}
+ </code>
+ </span>
+ ) : null}
+ </div>
+ );
+ }
+ return (
+ <div className="flex flex-wrap items-center gap-2 text-xs">
+ <Badge variant="outline">
+ {t("studio.dataset.tokenPreview.allTokens")}
+ </Badge>
+ {requested && data.final_format !== "raw_text" ? (
+ <span className="text-amber-600 dark:text-amber-400">
+ {t("studio.dataset.tokenPreview.maskingNotApplied")}
+ </span>
+ ) : null}
+ </div>
+ );
+}
+
+export function TokenPreviewDialog({
+ open,
+ onOpenChange,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ {open ? <TokenPreviewContent /> : null}
+ </Dialog>
+ );
+}
+
+type PreviewQuery = {
+ config: TrainingConfigState;
+ hfToken: string | null;
+ text?: string;
+ finalFormat?: string | null;
+ seed?: number;
+};
+
+/** The latest preview for `query`; a newer query aborts the request before it. */
+function useTokenPreview(query: PreviewQuery | null, debounceMs = 0) {
+ const [state, setState] = useState<PreviewState>(IDLE);
+ useEffect(() => {
+ if (!query) {
+ return;
+ }
+ const controller = new AbortController();
+ setState((prev) => ({ ...prev, error: null, loading: true }));
+ const timer = window.setTimeout(() => {
+ fetchTokenPreview({ ...query, signal: controller.signal })
+ .then((data) => setState({ data, error: null, loading: false }))
+ .catch((error: unknown) => {
+ if (controller.signal.aborted) {
+ return;
+ }
+ setState({
+ data: null,
+ error: error instanceof Error ? error.message : String(error),
+ loading: false,
+ });
+ });
+ }, debounceMs);
+ return () => {
+ window.clearTimeout(timer);
+ controller.abort();
+ };
+ }, [query, debounceMs]);
+ return state;
+}
+
+function LoadingRow() {
+ const t = useT();
+ return (
+ <div className="flex items-center gap-2 py-8 text-sm text-muted-foreground">
+ <Spinner className="size-4" />
+ {t("studio.dataset.tokenPreview.loading")}
+ </div>
+ );
+}
+
+function DatasetSamples({
+ state,
+ showIds,
+ onShuffle,
+}: {
+ state: PreviewState;
+ showIds: boolean;
+ onShuffle: () => void;
+}) {
+ const t = useT();
+ if (state.error) {
+ return (
+ <div className="flex flex-col items-start gap-3 py-6">
+ <p className="text-sm text-destructive">{state.error}</p>
+ <Button variant="outline" size="sm" onClick={onShuffle}>
+ {t("studio.dataset.tokenPreview.retry")}
+ </Button>
+ </div>
+ );
+ }
+ if (!state.data || state.loading) {
+ return <LoadingRow />;
+ }
+ const maskingApplied = state.data.masking.applied;
+ return (
+ <div className="flex flex-col gap-3">
+ {state.data.samples.map((sample, index) => (
+ <SampleCard
+ // biome-ignore lint/suspicious/noArrayIndexKey: samples are positional
+ key={index}
+ sample={sample}
+ label={t("studio.dataset.tokenPreview.sample", { index: index + 1 })}
+ showIds={showIds}
+ maskingApplied={maskingApplied}
+ />
+ ))}
+ <div className="flex justify-end">
+ <Button variant="outline" size="sm" onClick={onShuffle}>
+ <ShuffleIcon className="size-3.5" />
+ {t("studio.dataset.tokenPreview.shuffle")}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+function TextPlayground({
+ text,
+ onTextChange,
+ state,
+ exampleText,
+ showIds,
+}: {
+ text: string;
+ onTextChange: (text: string) => void;
+ state: PreviewState;
+ exampleText: string | null;
+ showIds: boolean;
+}) {
+ const t = useT();
+ const sample = text ? state.data?.samples[0] : undefined;
+ let result: ReactNode = null;
+ if (state.error && text) {
+ result = <p className="text-sm text-destructive">{state.error}</p>;
+ } else if (sample) {
+ result = (
+ <SampleCard
+ sample={sample}
+ showIds={showIds}
+ maskingApplied={state.data?.masking.applied ?? false}
+ />
+ );
+ } else if (state.loading && !state.data) {
+ result = <LoadingRow />;
+ }
+ return (
+ <>
+ <Textarea
+ value={text}
+ onChange={(event) => onTextChange(event.target.value)}
+ placeholder={t("studio.dataset.tokenPreview.textPlaceholder")}
+ className="min-h-28 font-mono text-[12.5px]"
+ />
+ <div className="flex flex-wrap items-center gap-2">
+ <p className="text-xs text-muted-foreground">
+ {t("studio.dataset.tokenPreview.textHint")}
+ </p>
+ {exampleText ? (
+ <Button
+ variant="outline"
+ size="sm"
+ className="ml-auto"
+ onClick={() => onTextChange(exampleText)}
+ >
+ {t("studio.dataset.tokenPreview.insertExample")}
+ </Button>
+ ) : null}
+ </div>
+ {result}
+ </>
+ );
+}
+
+function TokenPreviewContent() {
+ const t = useT();
+ const hfToken = useHfTokenStore((state) => state.token.trim() || null);
+ // A snapshot: the dialog is modal, so the configuration cannot change underneath it.
+ const [config] = useState(() => useTrainingConfigStore.getState());
+ const multimodal = config.isDatasetImage === true || config.isDatasetAudio;
+ const [tab, setTab] = useState(multimodal ? "text" : "dataset");
+ const [showIds, setShowIds] = useState(false);
+ const [seed, setSeed] = useState(0);
+ const [text, setText] = useState("");
+ const datasetQuery = useMemo(
+ () => (multimodal ? null : { config, hfToken, seed }),
+ [config, hfToken, seed, multimodal],
+ );
+ const datasetState = useTokenPreview(datasetQuery);
+ const finalFormat = datasetState.data?.final_format ?? null;
+ const textQuery = useMemo(
+ () => (tab === "text" ? { config, hfToken, text, finalFormat } : null),
+ [config, hfToken, text, tab, finalFormat],
+ );
+ const textState = useTokenPreview(textQuery, TEXT_DEBOUNCE_MS);
+ const summary = datasetState.data ?? textState.data;
+
+ return (
+ <DialogContent className="sm:max-w-4xl w-[90vw] max-sm:w-[calc(100vw-1rem)] max-h-[88dvh] flex flex-col gap-0 p-0 overflow-hidden rounded-3xl corner-squircle">
+ <DialogHeader className="px-6 max-sm:px-4 pt-5 pb-3 shrink-0">
+ <div className="flex items-center gap-3 pr-10">
+ <div className="rounded-xl corner-squircle p-2 ring-1 ring-emerald-200 bg-emerald-50 text-emerald-600 dark:ring-emerald-800 dark:bg-emerald-950 dark:text-emerald-400 shrink-0">
+ <TextSelectIcon className="size-4" />
+ </div>
+ <div className="min-w-0">
+ <DialogTitle className="font-heading text-lg font-semibold tracking-tight">
+ {t("studio.dataset.tokenPreview.title")}
+ </DialogTitle>
+ <DialogDescription className="truncate text-xs">
+ {t("studio.dataset.tokenPreview.description", {
+ model: config.selectedModel ?? "",
+ })}
+ </DialogDescription>
+ </div>
+ </div>
+ </DialogHeader>
+
+ <Tabs
+ value={tab}
+ onValueChange={setTab}
+ className="flex min-h-0 flex-1 flex-col px-6 max-sm:px-4 pb-5"
+ >
+ <div className="flex flex-wrap items-center gap-3 pb-2">
+ <TabsList>
+ <TabsTrigger value="dataset">
+ {t("studio.dataset.tokenPreview.datasetTab")}
+ </TabsTrigger>
+ <TabsTrigger value="text">
+ {t("studio.dataset.tokenPreview.textTab")}
+ </TabsTrigger>
+ </TabsList>
+ <Legend />
+ <div className="ml-auto flex items-center gap-2 text-xs text-muted-foreground">
+ <Switch
+ id="token-preview-show-ids"
+ size="sm"
+ checked={showIds}
+ onCheckedChange={setShowIds}
+ />
+ <label htmlFor="token-preview-show-ids">
+ {t("studio.dataset.tokenPreview.showIds")}
+ </label>
+ </div>
+ </div>
+ {summary ? (
+ <div className="flex flex-wrap items-center justify-between gap-2 pb-3">
+ <MaskingSummary
+ data={summary}
+ requested={config.trainOnCompletions}
+ />
+ <span className="text-xs text-muted-foreground">
+ {t("studio.dataset.tokenPreview.vocab", {
+ count: summary.vocab_size.toLocaleString(),
+ })}
+ </span>
+ </div>
+ ) : null}
+
+ {config.packing ? (
+ <p className="pb-3 text-xs text-muted-foreground">
+ {t("studio.dataset.tokenPreview.packing")}
+ </p>
+ ) : null}
+
+ <TabsContent value="dataset" className="min-h-0 flex-1 overflow-auto">
+ {multimodal ? (
+ <p className="py-6 text-sm text-muted-foreground">
+ {t("studio.dataset.tokenPreview.multimodal")}
+ </p>
+ ) : (
+ <DatasetSamples
+ state={datasetState}
+ showIds={showIds}
+ onShuffle={() => setSeed((value) => value + 1)}
+ />
+ )}
+ </TabsContent>
+
+ <TabsContent
+ value="text"
+ className="flex min-h-0 flex-1 flex-col gap-3 overflow-auto"
+ >
+ <TextPlayground
+ text={text}
+ onTextChange={setText}
+ state={textState}
+ exampleText={summary?.example_text ?? null}
+ showIds={showIds}
+ />
+ </TabsContent>
+ </Tabs>
+ </DialogContent>
+ );
+}
diff --git a/studio/frontend/src/features/training/api/token-preview-api.ts b/studio/frontend/src/features/training/api/token-preview-api.ts
new file mode 100644
index 00000000000..856fa2036b0
--- /dev/null
+++ b/studio/frontend/src/features/training/api/token-preview-api.ts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { authFetch } from "@/features/auth";
+import { hubTokenHeader } from "@/features/hub";
+import { readFastApiError } from "@/lib/format-fastapi-error";
+import type { TrainingConfigState } from "../types/config";
+import { buildTrainingStartPayload } from "./mappers";
+
+/** [token id, text, trained] */
+export type PreviewToken = [number, string, boolean];
+
+export type TokenPreviewSample = {
+ tokens: PreviewToken[];
+ /** Every ID of the row, including the ones past the displayed tokens. */
+ input_ids: number[];
+ num_tokens: number;
+ num_trained: number;
+ num_hidden: number;
+ truncated_from: number | null;
+ text: string;
+};
+
+export type TokenPreviewResponse = {
+ samples: TokenPreviewSample[];
+ masking: {
+ applied: boolean;
+ instruction_part?: string | null;
+ response_part?: string | null;
+ notes: string[];
+ };
+ final_format: string | null;
+ vocab_size: number;
+ example_text: string | null;
+};
+
+type TokenPreviewArgs = {
+ config: TrainingConfigState;
+ hfToken: string | null;
+ text?: string;
+ /** The dataset's format from an earlier preview, so typed text is masked the way the run is. */
+ finalFormat?: string | null;
+ seed?: number;
+ numSamples?: number;
+ signal?: AbortSignal;
+};
+
+/** The dataset and masking fields come from the training start payload, so the preview reads
+ * the rows and markers the run would. */
+export async function fetchTokenPreview({
+ config,
+ hfToken,
+ text,
+ finalFormat,
+ seed = 0,
+ numSamples = 3,
+ signal,
+}: TokenPreviewArgs): Promise<TokenPreviewResponse> {
+ const start = buildTrainingStartPayload(config, null);
+ const datasetName =
+ config.datasetSource === "huggingface"
+ ? config.dataset
+ : config.uploadedFile;
+ const res = await authFetch("/api/train/token-preview", {
+ method: "POST",
+ signal,
+ headers: {
+ "Content-Type": "application/json",
+ ...hubTokenHeader(hfToken),
+ },
+ body: JSON.stringify({
+ model_name: start.model_name,
+ model_type: config.modelType,
+ load_in_4bit: start.load_in_4bit,
+ dataset_name: datasetName || null,
+ subset: start.subset,
+ train_split: start.train_split,
+ dataset_local_path: start.dataset_local_path,
+ dataset_known_cached: start.dataset_known_cached,
+ format_type: start.format_type,
+ custom_format_mapping: start.custom_format_mapping ?? null,
+ train_on_completions: start.train_on_completions,
+ is_cpt: config.trainingMethod === "cpt",
+ max_seq_length: start.max_seq_length,
+ num_samples: numSamples,
+ seed,
+ text: text ?? null,
+ final_format: finalFormat ?? null,
+ }),
+ });
+ if (!res.ok) {
+ throw new Error(await readFastApiError(res));
+ }
+ return res.json();
+}
diff --git a/studio/frontend/src/features/training/index.ts b/studio/frontend/src/features/training/index.ts
index fd296c3cc0d..c2acf9b91d3 100644
--- a/studio/frontend/src/features/training/index.ts
+++ b/studio/frontend/src/features/training/index.ts
@@ -46,6 +46,12 @@ export {
uploadNativeTrainingDataset,
uploadTrainingDataset,
} from "./api/datasets-api";
+export {
+ type PreviewToken,
+ type TokenPreviewResponse,
+ type TokenPreviewSample,
+ fetchTokenPreview,
+} from "./api/token-preview-api";
export { clearDeletedDataset } from "./stores/training-config-store";
export type { CheckFormatResponse } from "./types/datasets";
export type {
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 104638757da..f9557c26a4e 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -3550,6 +3550,36 @@ export const ar = {
uploadDetailsTooltip:
"حتى {limit} لكل ملف. ملفات PDF وDOCX وTXT ليست مجموعات بيانات جاهزة للتدريب، لذا حوّلها أولًا في وصفات التعلّم.",
viewDataset: "عرض مجموعة البيانات",
+ previewTokens: "عرض الرموز",
+ tokenPreview: {
+ title: "معاينة الرموز",
+ description: "كيف يقسّم {model} هذه البيانات إلى رموز للتدريب. يتم تنزيل المُرمِّز فقط.",
+ datasetTab: "عينات مجموعة البيانات",
+ textTab: "نصك",
+ trained: "مُدرَّب",
+ masked: "مقنَّع",
+ completionsOnly: "ردود المساعد فقط",
+ allTokens: "تدريب جميع الرموز",
+ responseMarker: "علامة الرد",
+ maskingNotApplied: "لم يتم العثور على علامات المحادثة، لذا يتم تدريب كل الرموز.",
+ loading: "جارٍ تحميل المُرمِّز. تستغرق المعاينة الأولى وقتًا أطول قليلًا...",
+ shuffle: "خلط العينات",
+ showIds: "إظهار معرّفات الرموز",
+ copyIds: "نسخ المعرّفات",
+ copied: "تم نسخ معرّفات الرموز",
+ sample: "عينة {index}",
+ stats: "{tokens} رمز، {trained} مُدرَّب ({percent}%)",
+ truncated: "تم القص إلى {max} من أصل {full} رمز بسبب طول السياق.",
+ noTrained: "لا يتم تدريب أي رمز في هذا الصف، لذا يتخطاه التدريب.",
+ hiddenTokens: "{count} رمز إضافي غير معروض",
+ multimodal: "لا تُعرض صفوف الصور والصوت هنا. لا يزال بإمكانك تجربة المُرمِّز على نصك.",
+ textPlaceholder: "اكتب نصًا أو الصقه لرؤية رموزه...",
+ textHint: "مع ردود المساعد فقط، يتم تدريب النص الذي يلي علامة المساعد فقط.",
+ insertExample: "إدراج مثال محادثة",
+ vocab: "المفردات: {count} رمز",
+ retry: "إعادة المحاولة",
+ packing: "التجميع مفعّل: يدمج التدريب الصفوف في تسلسلات بطول السياق، لذا قد يختلف موضع القص عن هذا العرض لكل صف.",
+ },
uploadFailed: "فشل الرفع",
unknownError: "خطأ غير معروف",
unsupportedFileType: "نوع ملف غير مدعوم",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 594cb854dbb..d0e94986eb1 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -3605,6 +3605,36 @@ export const de = {
uploadDetailsTooltip:
"Bis zu {limit} pro Datei. PDF-, DOCX- und TXT-Dateien sind keine trainingsfertigen Datensätze; konvertieren Sie sie daher zuerst in den Lernrezepten.",
viewDataset: "Datensatz ansehen",
+ previewTokens: "Tokens ansehen",
+ tokenPreview: {
+ title: "Token-Vorschau",
+ description: "So tokenisiert {model} diese Daten für das Training. Nur der Tokenizer wird heruntergeladen.",
+ datasetTab: "Datensatzbeispiele",
+ textTab: "Eigener Text",
+ trained: "Trainiert",
+ masked: "Maskiert",
+ completionsOnly: "Nur Assistentenantworten",
+ allTokens: "Alle Tokens trainiert",
+ responseMarker: "Antwortmarker",
+ maskingNotApplied: "Die Chat-Marker wurden nicht gefunden, daher wird jedes Token trainiert.",
+ loading: "Tokenizer wird geladen. Die erste Vorschau dauert etwas länger...",
+ shuffle: "Beispiele mischen",
+ showIds: "Token-IDs anzeigen",
+ copyIds: "IDs kopieren",
+ copied: "Token-IDs kopiert",
+ sample: "Beispiel {index}",
+ stats: "{tokens} Tokens, {trained} trainiert ({percent}%)",
+ truncated: "Durch die Kontextlänge auf {max} von {full} Tokens gekürzt.",
+ noTrained: "In dieser Zeile wird kein Token trainiert, daher überspringt das Training sie.",
+ hiddenTokens: "{count} weitere Tokens nicht angezeigt",
+ multimodal: "Bild- und Audiozeilen werden hier nicht angezeigt. Du kannst den Tokenizer trotzdem mit eigenem Text testen.",
+ textPlaceholder: "Text eingeben oder einfügen, um seine Tokens zu sehen...",
+ textHint: "Bei nur Assistentenantworten wird nur der Text nach einem Assistentenmarker trainiert.",
+ insertExample: "Chat-Beispiel einfügen",
+ vocab: "Vokabular: {count} Tokens",
+ retry: "Erneut versuchen",
+ packing: "Packing ist aktiv: Der Lauf fügt Zeilen zu Sequenzen der Kontextlänge zusammen, daher kann die Kürzung von dieser Ansicht pro Zeile abweichen.",
+ },
uploadFailed: "Upload fehlgeschlagen",
unknownError: "Unbekannter Fehler",
unsupportedFileType: "Nicht unterstützter Dateityp",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 809e89068a2..7a459d0e59b 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -3589,6 +3589,36 @@ export const en = {
uploadDetailsTooltip:
"Up to {limit} per file. PDF, DOCX and TXT are not ready-to-train datasets, so convert them in Learning Recipes first.",
viewDataset: "View dataset",
+ previewTokens: "Preview tokens",
+ tokenPreview: {
+ title: "Token preview",
+ description: "How {model} tokenizes this data for training. Only the tokenizer is downloaded.",
+ datasetTab: "Dataset samples",
+ textTab: "Your text",
+ trained: "Trained",
+ masked: "Masked",
+ completionsOnly: "Assistant completions only",
+ allTokens: "All tokens trained",
+ responseMarker: "Response marker",
+ maskingNotApplied: "The chat markers were not found, so every token is trained.",
+ loading: "Loading the tokenizer. The first preview takes a little longer...",
+ shuffle: "Shuffle samples",
+ showIds: "Show token IDs",
+ copyIds: "Copy IDs",
+ copied: "Token IDs copied",
+ sample: "Sample {index}",
+ stats: "{tokens} tokens, {trained} trained ({percent}%)",
+ truncated: "Cut to {max} of {full} tokens by the context length.",
+ noTrained: "No token in this row is trained, so training skips it.",
+ hiddenTokens: "{count} more tokens not shown",
+ multimodal: "Image and audio rows are not shown here. You can still try the tokenizer on your own text.",
+ textPlaceholder: "Type or paste text to see its tokens...",
+ textHint: "With assistant completions only, just the text after an assistant marker is trained.",
+ insertExample: "Insert chat example",
+ vocab: "Vocabulary: {count} tokens",
+ retry: "Try again",
+ packing: "Packing is on: the run joins rows into context-length sequences, so where a row is cut can differ from this per-row view.",
+ },
uploadFailed: "Upload failed",
unknownError: "Unknown error",
unsupportedFileType: "Unsupported file type",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 6c8fdf11279..0c7a1de7033 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -3601,6 +3601,36 @@ export const es = {
uploadDetailsTooltip:
"Hasta {limit} por archivo. Los archivos PDF, DOCX y TXT no son conjuntos de datos listos para entrenar, así que conviértelos primero en Recetas.",
viewDataset: "Ver conjunto de datos",
+ previewTokens: "Ver tokens",
+ tokenPreview: {
+ title: "Vista previa de tokens",
+ description: "Cómo {model} tokeniza estos datos para el entrenamiento. Solo se descarga el tokenizador.",
+ datasetTab: "Muestras del dataset",
+ textTab: "Tu texto",
+ trained: "Entrenado",
+ masked: "Enmascarado",
+ completionsOnly: "Solo respuestas del asistente",
+ allTokens: "Todos los tokens se entrenan",
+ responseMarker: "Marcador de respuesta",
+ maskingNotApplied: "No se encontraron los marcadores del chat, así que se entrena cada token.",
+ loading: "Cargando el tokenizador. La primera vista previa tarda un poco más...",
+ shuffle: "Mezclar muestras",
+ showIds: "Mostrar IDs de tokens",
+ copyIds: "Copiar IDs",
+ copied: "IDs de tokens copiados",
+ sample: "Muestra {index}",
+ stats: "{tokens} tokens, {trained} entrenados ({percent}%)",
+ truncated: "Recortado a {max} de {full} tokens por la longitud de contexto.",
+ noTrained: "Ningún token de esta fila se entrena, así que el entrenamiento la omite.",
+ hiddenTokens: "{count} tokens más sin mostrar",
+ multimodal: "Las filas de imagen y audio no se muestran aquí. Aun así puedes probar el tokenizador con tu propio texto.",
+ textPlaceholder: "Escribe o pega texto para ver sus tokens...",
+ textHint: "Con solo respuestas del asistente, solo se entrena el texto después de un marcador del asistente.",
+ insertExample: "Insertar ejemplo de chat",
+ vocab: "Vocabulario: {count} tokens",
+ retry: "Reintentar",
+ packing: "El empaquetado está activo: la ejecución une filas en secuencias de la longitud de contexto, así que el corte puede diferir de esta vista por fila.",
+ },
uploadFailed: "La subida falló",
unknownError: "Error desconocido",
unsupportedFileType: "Tipo de archivo no admitido",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 91dcf2a0162..9b3cb29e8c6 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -3614,6 +3614,36 @@ export const fr = {
uploadDetailsTooltip:
"Jusqu’à {limit} par fichier. Les fichiers PDF, DOCX et TXT ne sont pas des jeux de données prêts pour l’entraînement ; convertissez-les d’abord dans les Recettes.",
viewDataset: "Voir le jeu de données",
+ previewTokens: "Voir les tokens",
+ tokenPreview: {
+ title: "Aperçu des tokens",
+ description: "Comment {model} tokenise ces données pour l'entraînement. Seul le tokenizer est téléchargé.",
+ datasetTab: "Exemples du jeu de données",
+ textTab: "Votre texte",
+ trained: "Entraîné",
+ masked: "Masqué",
+ completionsOnly: "Réponses de l'assistant uniquement",
+ allTokens: "Tous les tokens sont entraînés",
+ responseMarker: "Marqueur de réponse",
+ maskingNotApplied: "Les marqueurs de chat sont introuvables, donc chaque token est entraîné.",
+ loading: "Chargement du tokenizer. Le premier aperçu prend un peu plus de temps...",
+ shuffle: "Mélanger les exemples",
+ showIds: "Afficher les ID de tokens",
+ copyIds: "Copier les ID",
+ copied: "ID de tokens copiés",
+ sample: "Exemple {index}",
+ stats: "{tokens} tokens, {trained} entraînés ({percent} %)",
+ truncated: "Réduit à {max} sur {full} tokens par la longueur de contexte.",
+ noTrained: "Aucun token de cette ligne n'est entraîné, l'entraînement l'ignore donc.",
+ hiddenTokens: "{count} tokens supplémentaires non affichés",
+ multimodal: "Les lignes d'image et d'audio ne sont pas affichées ici. Vous pouvez quand même tester le tokenizer sur votre propre texte.",
+ textPlaceholder: "Saisissez ou collez du texte pour voir ses tokens...",
+ textHint: "Avec les réponses de l'assistant uniquement, seul le texte après un marqueur de l'assistant est entraîné.",
+ insertExample: "Insérer un exemple de chat",
+ vocab: "Vocabulaire : {count} tokens",
+ retry: "Réessayer",
+ packing: "Le packing est activé : l'entraînement regroupe les lignes en séquences de la longueur de contexte, la coupure peut donc différer de cette vue par ligne.",
+ },
uploadFailed: "Échec du téléversement",
unknownError: "Erreur inconnue",
unsupportedFileType: "Type de fichier non pris en charge",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index c5d9c2f0243..2f8cbd697ca 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -3659,6 +3659,36 @@ export const he = {
uploadDetailsTooltip:
"עד {limit} לקובץ. PDF, DOCX ו-TXT אינם מערכי נתונים מוכנים לאימון, לכן המר אותם ב-Learning Recipes תחילה.",
viewDataset: "הצג מערך נתונים",
+ previewTokens: "הצג טוקנים",
+ tokenPreview: {
+ title: "תצוגה מקדימה של טוקנים",
+ description: "כך {model} מחלק את הנתונים האלה לטוקנים לאימון. רק ה-tokenizer מורד.",
+ datasetTab: "דוגמאות ממערך הנתונים",
+ textTab: "הטקסט שלך",
+ trained: "מאומן",
+ masked: "ממוסך",
+ completionsOnly: "רק תשובות העוזר",
+ allTokens: "כל הטוקנים מאומנים",
+ responseMarker: "סמן תשובה",
+ maskingNotApplied: "סמני הצ'אט לא נמצאו, ולכן כל טוקן מאומן.",
+ loading: "טוען את ה-tokenizer. התצוגה המקדימה הראשונה לוקחת קצת יותר זמן...",
+ shuffle: "ערבב דוגמאות",
+ showIds: "הצג מזהי טוקנים",
+ copyIds: "העתק מזהים",
+ copied: "מזהי הטוקנים הועתקו",
+ sample: "דוגמה {index}",
+ stats: "{tokens} טוקנים, {trained} מאומנים ({percent}%)",
+ truncated: "קוצר ל-{max} מתוך {full} טוקנים בגלל אורך ההקשר.",
+ noTrained: "אף טוקן בשורה הזו לא מאומן, ולכן האימון מדלג עליה.",
+ hiddenTokens: "עוד {count} טוקנים לא מוצגים",
+ multimodal: "שורות תמונה ושמע לא מוצגות כאן. עדיין אפשר לנסות את ה-tokenizer על טקסט משלך.",
+ textPlaceholder: "הקלד או הדבק טקסט כדי לראות את הטוקנים שלו...",
+ textHint: "במצב של רק תשובות העוזר, רק הטקסט שאחרי סמן העוזר מאומן.",
+ insertExample: "הוסף דוגמת צ'אט",
+ vocab: "אוצר מילים: {count} טוקנים",
+ retry: "נסה שוב",
+ packing: "האריזה פעילה: האימון מצרף שורות לרצפים באורך ההקשר, ולכן מקום החיתוך עשוי להיות שונה מהתצוגה הזו לפי שורה.",
+ },
uploadFailed: "ההעלאה נכשלה",
unknownError: "שגיאה לא ידועה",
unsupportedFileType: "סוג קובץ אינו נתמך",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index d135b11d2e0..5c790bf590f 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -3561,6 +3561,36 @@ export const hi = {
uploadDetailsTooltip:
"प्रति फ़ाइल अधिकतम {limit}। PDF, DOCX और TXT ट्रेनिंग के लिए तैयार डेटासेट नहीं हैं, इसलिए पहले उन्हें रेसिपी में बदलें।",
viewDataset: "डेटासेट देखें",
+ previewTokens: "टोकन देखें",
+ tokenPreview: {
+ title: "टोकन पूर्वावलोकन",
+ description: "{model} प्रशिक्षण के लिए इस डेटा को कैसे टोकन में बाँटता है। केवल टोकनाइज़र डाउनलोड होता है।",
+ datasetTab: "डेटासेट नमूने",
+ textTab: "आपका टेक्स्ट",
+ trained: "प्रशिक्षित",
+ masked: "मास्क किया गया",
+ completionsOnly: "केवल असिस्टेंट के जवाब",
+ allTokens: "सभी टोकन प्रशिक्षित",
+ responseMarker: "जवाब मार्कर",
+ maskingNotApplied: "चैट मार्कर नहीं मिले, इसलिए हर टोकन प्रशिक्षित होगा।",
+ loading: "टोकनाइज़र लोड हो रहा है। पहला पूर्वावलोकन थोड़ा अधिक समय लेता है...",
+ shuffle: "नमूने बदलें",
+ showIds: "टोकन ID दिखाएँ",
+ copyIds: "ID कॉपी करें",
+ copied: "टोकन ID कॉपी हो गए",
+ sample: "नमूना {index}",
+ stats: "{tokens} टोकन, {trained} प्रशिक्षित ({percent}%)",
+ truncated: "कॉन्टेक्स्ट लंबाई के कारण {full} में से {max} टोकन तक काटा गया।",
+ noTrained: "इस पंक्ति का कोई टोकन प्रशिक्षित नहीं होता, इसलिए प्रशिक्षण इसे छोड़ देता है।",
+ hiddenTokens: "{count} और टोकन नहीं दिखाए गए",
+ multimodal: "इमेज और ऑडियो पंक्तियाँ यहाँ नहीं दिखतीं। आप फिर भी अपने टेक्स्ट पर टोकनाइज़र आज़मा सकते हैं।",
+ textPlaceholder: "टोकन देखने के लिए टेक्स्ट लिखें या चिपकाएँ...",
+ textHint: "केवल असिस्टेंट के जवाब में, असिस्टेंट मार्कर के बाद का टेक्स्ट ही प्रशिक्षित होता है।",
+ insertExample: "चैट उदाहरण डालें",
+ vocab: "शब्दावली: {count} टोकन",
+ retry: "फिर से कोशिश करें",
+ packing: "पैकिंग चालू है: प्रशिक्षण पंक्तियों को कॉन्टेक्स्ट लंबाई के अनुक्रमों में जोड़ता है, इसलिए कटने की जगह इस पंक्ति-दर-पंक्ति दृश्य से अलग हो सकती है।",
+ },
uploadFailed: "अपलोड विफल",
unknownError: "अज्ञात त्रुटि",
unsupportedFileType: "असमर्थित फ़ाइल प्रकार",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index bfa9963b055..d9b5d1738f8 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -3586,6 +3586,36 @@ export const it = {
clear: "Deseleziona",
dropFileOrClick: "Trascina qui 1 file oppure fai clic per caricarlo",
viewDataset: "Vedi il dataset",
+ previewTokens: "Vedi i token",
+ tokenPreview: {
+ title: "Anteprima dei token",
+ description: "Come {model} tokenizza questi dati per l'addestramento. Viene scaricato solo il tokenizer.",
+ datasetTab: "Esempi del dataset",
+ textTab: "Il tuo testo",
+ trained: "Addestrato",
+ masked: "Mascherato",
+ completionsOnly: "Solo risposte dell'assistente",
+ allTokens: "Tutti i token addestrati",
+ responseMarker: "Marcatore di risposta",
+ maskingNotApplied: "I marcatori della chat non sono stati trovati, quindi ogni token viene addestrato.",
+ loading: "Caricamento del tokenizer. La prima anteprima richiede un po' più di tempo...",
+ shuffle: "Mescola esempi",
+ showIds: "Mostra ID dei token",
+ copyIds: "Copia ID",
+ copied: "ID dei token copiati",
+ sample: "Esempio {index}",
+ stats: "{tokens} token, {trained} addestrati ({percent}%)",
+ truncated: "Ridotto a {max} di {full} token dalla lunghezza del contesto.",
+ noTrained: "Nessun token di questa riga viene addestrato, quindi l'addestramento la salta.",
+ hiddenTokens: "Altri {count} token non mostrati",
+ multimodal: "Le righe con immagini e audio non sono mostrate qui. Puoi comunque provare il tokenizer con il tuo testo.",
+ textPlaceholder: "Scrivi o incolla un testo per vederne i token...",
+ textHint: "Con solo risposte dell'assistente, viene addestrato solo il testo dopo un marcatore dell'assistente.",
+ insertExample: "Inserisci esempio di chat",
+ vocab: "Vocabolario: {count} token",
+ retry: "Riprova",
+ packing: "Il packing è attivo: l'addestramento unisce le righe in sequenze della lunghezza di contesto, quindi il punto di taglio può differire da questa vista per riga.",
+ },
uploadFailed: "Caricamento non riuscito",
unknownError: "Errore sconosciuto",
unsupportedFileType: "Tipo di file non supportato",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index b6f88bc7361..fd6a72a8d8b 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -3514,6 +3514,36 @@ export const ja = {
uploadDetails: "アップロードの詳細",
uploadDetailsTooltip: "1ファイルあたり最大 {limit}。PDF、DOCX、TXT はそのままではトレーニング用データセットとして使用できないため、先にレシピで変換してください。",
viewDataset: "データセットを表示",
+ previewTokens: "トークンを表示",
+ tokenPreview: {
+ title: "トークンのプレビュー",
+ description: "{model} が学習用にこのデータをどうトークン化するかを表示します。ダウンロードするのはトークナイザーのみです。",
+ datasetTab: "データセットのサンプル",
+ textTab: "自分のテキスト",
+ trained: "学習対象",
+ masked: "マスク",
+ completionsOnly: "アシスタントの応答のみ",
+ allTokens: "すべてのトークンを学習",
+ responseMarker: "応答マーカー",
+ maskingNotApplied: "チャットのマーカーが見つからないため、すべてのトークンが学習されます。",
+ loading: "トークナイザーを読み込み中です。初回のプレビューは少し時間がかかります...",
+ shuffle: "サンプルを入れ替える",
+ showIds: "トークン ID を表示",
+ copyIds: "ID をコピー",
+ copied: "トークン ID をコピーしました",
+ sample: "サンプル {index}",
+ stats: "{tokens} トークン、学習対象 {trained}({percent}%)",
+ truncated: "コンテキスト長により {full} トークンから {max} トークンに切り詰められます。",
+ noTrained: "この行には学習対象のトークンがないため、学習ではスキップされます。",
+ hiddenTokens: "表示されていないトークンがあと {count} 個あります",
+ multimodal: "画像と音声の行はここには表示されません。自分のテキストでトークナイザーを試すことはできます。",
+ textPlaceholder: "テキストを入力または貼り付けるとトークンが表示されます...",
+ textHint: "アシスタントの応答のみの場合、アシスタントのマーカー以降のテキストだけが学習されます。",
+ insertExample: "チャットの例を挿入",
+ vocab: "語彙:{count} トークン",
+ retry: "再試行",
+ packing: "パッキングが有効です。学習では行をコンテキスト長のシーケンスにまとめるため、切り詰め位置はこの行ごとの表示と異なる場合があります。",
+ },
uploadFailed: "アップロードに失敗しました",
unknownError: "不明なエラー",
unsupportedFileType: "サポートされていないファイル形式です",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 4729f6d79c4..78780407afe 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -3539,6 +3539,36 @@ export const ko = {
uploadDetailsTooltip:
"파일당 최대 {limit}입니다. PDF, DOCX 및 TXT는 바로 학습할 수 있는 데이터셋이 아니므로 먼저 레시피에서 변환하세요.",
viewDataset: "데이터셋 보기",
+ previewTokens: "토큰 보기",
+ tokenPreview: {
+ title: "토큰 미리보기",
+ description: "{model}이(가) 학습을 위해 이 데이터를 토큰화하는 방식입니다. 토크나이저만 다운로드합니다.",
+ datasetTab: "데이터셋 샘플",
+ textTab: "직접 입력",
+ trained: "학습됨",
+ masked: "마스킹됨",
+ completionsOnly: "어시스턴트 응답만",
+ allTokens: "모든 토큰 학습",
+ responseMarker: "응답 마커",
+ maskingNotApplied: "채팅 마커를 찾지 못해 모든 토큰이 학습됩니다.",
+ loading: "토크나이저를 불러오는 중입니다. 첫 미리보기는 조금 더 걸립니다...",
+ shuffle: "샘플 섞기",
+ showIds: "토큰 ID 표시",
+ copyIds: "ID 복사",
+ copied: "토큰 ID를 복사했습니다",
+ sample: "샘플 {index}",
+ stats: "토큰 {tokens}개, 학습 {trained}개 ({percent}%)",
+ truncated: "컨텍스트 길이 때문에 토큰 {full}개 중 {max}개로 잘립니다.",
+ noTrained: "이 행에는 학습되는 토큰이 없어 학습에서 건너뜁니다.",
+ hiddenTokens: "표시되지 않은 토큰 {count}개",
+ multimodal: "이미지와 오디오 행은 여기에 표시되지 않습니다. 직접 입력한 텍스트로 토크나이저를 확인할 수 있습니다.",
+ textPlaceholder: "텍스트를 입력하거나 붙여 넣으면 토큰이 표시됩니다...",
+ textHint: "어시스턴트 응답만 학습할 때는 어시스턴트 마커 뒤의 텍스트만 학습됩니다.",
+ insertExample: "채팅 예시 넣기",
+ vocab: "어휘: 토큰 {count}개",
+ retry: "다시 시도",
+ packing: "패킹이 켜져 있습니다. 학습은 여러 행을 컨텍스트 길이의 시퀀스로 묶으므로 잘리는 위치가 이 행별 보기와 다를 수 있습니다.",
+ },
uploadFailed: "업로드에 실패했습니다",
unknownError: "알 수 없는 오류",
unsupportedFileType: "지원되지 않는 파일 형식",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index c1718d46576..fcb0cad29c0 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -3577,6 +3577,36 @@ export const ptBR = {
uploadDetailsTooltip:
"Até {limit} por arquivo. PDF, DOCX e TXT não são datasets prontos para treinamento; converta-os primeiro em Receitas.",
viewDataset: "Visualizar dataset",
+ previewTokens: "Ver tokens",
+ tokenPreview: {
+ title: "Prévia de tokens",
+ description: "Como {model} tokeniza estes dados para o treinamento. Apenas o tokenizer é baixado.",
+ datasetTab: "Amostras do dataset",
+ textTab: "Seu texto",
+ trained: "Treinado",
+ masked: "Mascarado",
+ completionsOnly: "Apenas respostas do assistente",
+ allTokens: "Todos os tokens treinados",
+ responseMarker: "Marcador de resposta",
+ maskingNotApplied: "Os marcadores do chat não foram encontrados, então todos os tokens são treinados.",
+ loading: "Carregando o tokenizer. A primeira prévia demora um pouco mais...",
+ shuffle: "Embaralhar amostras",
+ showIds: "Mostrar IDs dos tokens",
+ copyIds: "Copiar IDs",
+ copied: "IDs dos tokens copiados",
+ sample: "Amostra {index}",
+ stats: "{tokens} tokens, {trained} treinados ({percent}%)",
+ truncated: "Cortado para {max} de {full} tokens pelo comprimento de contexto.",
+ noTrained: "Nenhum token desta linha é treinado, então o treinamento a ignora.",
+ hiddenTokens: "Mais {count} tokens não exibidos",
+ multimodal: "Linhas de imagem e áudio não aparecem aqui. Você ainda pode testar o tokenizer com seu próprio texto.",
+ textPlaceholder: "Digite ou cole um texto para ver seus tokens...",
+ textHint: "Com apenas respostas do assistente, só o texto após um marcador do assistente é treinado.",
+ insertExample: "Inserir exemplo de chat",
+ vocab: "Vocabulário: {count} tokens",
+ retry: "Tentar novamente",
+ packing: "O empacotamento está ativo: o treinamento junta linhas em sequências do comprimento de contexto, então o corte pode diferir desta visão por linha.",
+ },
uploadFailed: "Falha no envio",
unknownError: "Erro desconhecido",
unsupportedFileType: "Tipo de arquivo não suportado",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 5104ec6b3d6..727cf425f24 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -3576,6 +3576,36 @@ export const ru = {
uploadDetailsTooltip:
"До {limit} на файл. PDF, DOCX и TXT не являются готовыми датасетами для обучения, поэтому сначала преобразуйте их в разделе «Рецепты».",
viewDataset: "Просмотреть датасет",
+ previewTokens: "Показать токены",
+ tokenPreview: {
+ title: "Просмотр токенов",
+ description: "Как {model} разбивает эти данные на токены для обучения. Загружается только токенизатор.",
+ datasetTab: "Примеры из датасета",
+ textTab: "Ваш текст",
+ trained: "Обучается",
+ masked: "Маскирован",
+ completionsOnly: "Только ответы ассистента",
+ allTokens: "Обучаются все токены",
+ responseMarker: "Маркер ответа",
+ maskingNotApplied: "Маркеры чата не найдены, поэтому обучаются все токены.",
+ loading: "Загрузка токенизатора. Первый просмотр занимает чуть больше времени...",
+ shuffle: "Перемешать примеры",
+ showIds: "Показать ID токенов",
+ copyIds: "Копировать ID",
+ copied: "ID токенов скопированы",
+ sample: "Пример {index}",
+ stats: "{tokens} токенов, обучается {trained} ({percent}%)",
+ truncated: "Обрезано до {max} из {full} токенов длиной контекста.",
+ noTrained: "В этой строке не обучается ни один токен, поэтому обучение её пропускает.",
+ hiddenTokens: "Ещё {count} токенов не показано",
+ multimodal: "Строки с изображениями и аудио здесь не показываются. Вы всё равно можете проверить токенизатор на своём тексте.",
+ textPlaceholder: "Введите или вставьте текст, чтобы увидеть его токены...",
+ textHint: "В режиме только ответов ассистента обучается лишь текст после маркера ассистента.",
+ insertExample: "Вставить пример чата",
+ vocab: "Словарь: {count} токенов",
+ retry: "Повторить",
+ packing: "Упаковка включена: обучение объединяет строки в последовательности длины контекста, поэтому место обрезки может отличаться от этого построчного вида.",
+ },
uploadFailed: "Загрузка не удалась",
unknownError: "Неизвестная ошибка",
unsupportedFileType: "Неподдерживаемый тип файла",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index 470053ac1d0..09a67f63005 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -3780,6 +3780,36 @@ export const sv = {
uploadDetailsTooltip:
"Upp till {limit} per fil. PDF, DOCX och TXT är inte färdiga datauppsättningar för träning, så konvertera dem först i Lärrecept.",
viewDataset: "Visa datauppsättning",
+ previewTokens: "Visa tokens",
+ tokenPreview: {
+ title: "Tokenförhandsvisning",
+ description: "Så tokeniserar {model} dessa data för träning. Endast tokenizern laddas ned.",
+ datasetTab: "Exempel ur datauppsättningen",
+ textTab: "Din text",
+ trained: "Tränad",
+ masked: "Maskerad",
+ completionsOnly: "Endast assistentsvar",
+ allTokens: "Alla tokens tränas",
+ responseMarker: "Svarsmarkör",
+ maskingNotApplied: "Chattmarkörerna hittades inte, så varje token tränas.",
+ loading: "Läser in tokenizern. Den första förhandsvisningen tar lite längre tid...",
+ shuffle: "Blanda exempel",
+ showIds: "Visa token-ID",
+ copyIds: "Kopiera ID",
+ copied: "Token-ID kopierade",
+ sample: "Exempel {index}",
+ stats: "{tokens} tokens, {trained} tränade ({percent} %)",
+ truncated: "Kortad till {max} av {full} tokens av kontextlängden.",
+ noTrained: "Ingen token i den här raden tränas, så träningen hoppar över den.",
+ hiddenTokens: "{count} tokens till visas inte",
+ multimodal: "Bild- och ljudrader visas inte här. Du kan ändå testa tokenizern på egen text.",
+ textPlaceholder: "Skriv eller klistra in text för att se dess tokens...",
+ textHint: "Med endast assistentsvar tränas bara texten efter en assistentmarkör.",
+ insertExample: "Infoga chattexempel",
+ vocab: "Vokabulär: {count} tokens",
+ retry: "Försök igen",
+ packing: "Packning är på: körningen slår ihop rader till sekvenser av kontextlängden, så var en rad kortas kan skilja sig från den här vyn per rad.",
+ },
uploadFailed: "Uppladdningen misslyckades",
unknownError: "Okänt fel",
unsupportedFileType: "Filtypen stöds inte",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index f0baa9d8f40..92395edf930 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -3475,6 +3475,36 @@ export const zhCN = {
uploadDetailsTooltip:
"每个文件最大 {limit}。PDF、DOCX 和 TXT 不是可直接用于训练的数据集,请先在配方中进行转换。",
viewDataset: "查看数据集",
+ previewTokens: "查看 Token",
+ tokenPreview: {
+ title: "Token 预览",
+ description: "{model} 在训练时如何对这些数据进行分词。只会下载分词器。",
+ datasetTab: "数据集样本",
+ textTab: "你的文本",
+ trained: "参与训练",
+ masked: "已遮蔽",
+ completionsOnly: "仅训练助手回复",
+ allTokens: "训练全部 Token",
+ responseMarker: "回复标记",
+ maskingNotApplied: "未找到对话标记,因此所有 Token 都会参与训练。",
+ loading: "正在加载分词器。首次预览需要稍长时间...",
+ shuffle: "随机换一批",
+ showIds: "显示 Token ID",
+ copyIds: "复制 ID",
+ copied: "已复制 Token ID",
+ sample: "样本 {index}",
+ stats: "{tokens} 个 Token,{trained} 个参与训练({percent}%)",
+ truncated: "因上下文长度限制,从 {full} 个 Token 截断为 {max} 个。",
+ noTrained: "此行没有任何 Token 参与训练,因此训练会跳过它。",
+ hiddenTokens: "还有 {count} 个 Token 未显示",
+ multimodal: "此处不显示图像和音频行。你仍可以用自己的文本测试分词器。",
+ textPlaceholder: "输入或粘贴文本以查看其 Token...",
+ textHint: "仅训练助手回复时,只有助手标记之后的文本会参与训练。",
+ insertExample: "插入对话示例",
+ vocab: "词表:{count} 个 Token",
+ retry: "重试",
+ packing: "已开启打包:训练会把多行拼接成上下文长度的序列,因此截断位置可能与此逐行视图不同。",
+ },
uploadFailed: "上传失败",
unknownError: "未知错误",
unsupportedFileType: "不支持的文件类型",