Skip to content

Studio: train a speculative decoding drafter with fine-tunes and export it for llama.cpp and vLLM - #13806

Merged
danielhanchen merged 48 commits into
mainfrom
studio-drafter-training
Oct 15, 2026
Merged

danielhanchen merged 48 commits into
mainfrom
studio-drafter-training

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Lets Unsloth Studio and Unsloth Desktop train a speculative decoding drafter together with a fine-tune, and ships it with merged and GGUF exports so the fine-tuned model decodes faster in llama.cpp and vLLM. Builds on #13719 (merged) and unslothai/unsloth-zoo#1748 / #1762 (merged).

What users see

Train tab, advanced mode: a new collapsed section "Speculative Decoding Drafter" with one checkbox, "Train a speculative decoding drafter". What it does depends on the selected model:

  • Model has a native MTP head (Qwen3.5 / 3.6, GLM-4.5 / 4.7, Qwen3-Next, ...): "Retrains this model's MTP head".
  • Model has no MTP head (Llama, Qwen3, Gemma 4, gpt-oss, ...): "Trains an EAGLE-3 drafter (this model has no MTP head)".
  • Neither engine can run a drafter for it (Gemma 3, Mistral 3): disabled, with the reason.

Expanded: data source (dataset answers, or the model's own answers: slower, closer to what the model generates), number of examples, epochs, learning rate, draft tokens. With the box unticked nothing changes: the training request is byte-identical to today's.

After the fine-tune finishes, a "Training drafter" phase trains the drafter against the fine-tuned model (frozen, adapter active). A drafter failure is reported as a warning and the fine-tune is kept; stopping during this phase discards only the drafter. The export page then says "Includes trained drafter (MTP | EAGLE-3)" and shows the vllm serve command.

How it works

Backend:

  • TrainingStartRequest.drafter (optional) -> route -> worker config -> core/training/drafter.py, run in the worker after the fine-tune is saved: frees the SFT optimizer and data, builds examples (SFT rows with the same prompt masking, or greedy regeneration), then FastModel.get_mtp_head + UnslothMTPTrainer (native head, saved as mtp_head.safetensors beside the adapter) or the zoo EAGLE-3 trainer (saved to eagle3/). Writes drafter.json (strategy, layers, metrics). Progress has its own step counter and does not touch the fine-tune's loss history.
  • GET /api/train/drafter-capability?model_name=...: native head detected from the checkpoint's tensor index (not the config alone), otherwise EAGLE-3 support for the architecture.
  • Export: the native head is re-attached when export reloads the adapter and stitched into merged and GGUF outputs (Fine-tune and export native MTP heads and DSpark drafters #13719). EAGLE-3 is copied to <export>/eagle3 (verifier = the Hub repo on push, else the base model) and converted to eagle3-<name>-F16.gguf next to GGUF exports; drafter.json carries the vllm serve ... --speculative-config command.
  • Inference: llama-server gets --model-draft <eagle3 gguf> --spec-type draft-eagle3 when an export's drafter sits beside the GGUF and the binary supports it; a GGUF whose drafter.json says its MTP head was trained turns MTP on in auto even under the 3B size floor and the MLA default-off (the user trained it to be used). GGUFs without that file route exactly as before. The managed vLLM engine adds --speculative-config when the model folder has a drafter.json.
  • Fix: after an export reload, an outer save wrapper hid the MTP save wrapper, so the head was stitched twice per save. Internal savers now set a context flag the wrapper honours wherever it sits in the chain.

Frontend: drafter-section.tsx, store / types / defaults / persistence (v23, old state migrates to off) / YAML / payload mapping (sent only when ticked, supported for the selected model, and not CPT / embedding / decision / MLX), training_drafter phase label, export banner; strings in all 14 locales.

Tests

  • Backend: test_drafter_training.py, test_drafter_launch_flags.py, the managed engine, admission and phase sync suites: 439 passed.
  • Frontend: training-start-payload-drafter.test.ts (off payload unchanged in every gated case, on payload = off payload plus exactly the drafter block, bounds, persistence migration, YAML round trip) and persistence: 24 passed; npm run typecheck, npm run i18n:check:strict, npm run build pass.

Regression A/B (Studio journeys auth / settings / crawl / inference settings / parallel / train_responses_only / export_reload / diffusion train, plus the core regression smoke, jobs/sft.py, jobs/inference_smoke.py), base vs head on Colab A100 / L4 and Kaggle T4x2: no functional regression (63 steps identical, 10 DOM-only, 1 failing on both sides: export_reload/export_merged). The visual diffs that reproduced are the Train form (the new section) and a chat title in a parallel-streams journey whose order depends on which stream finishes first.

End-to-end results

Driven only through Studio's HTTP API on Colab (train with the drafter, merged 16-bit + GGUF Q8_0 export, then serve), 60 held-out prompts, 192 new tokens, greedy, arms interleaved on one GPU, 95% paired bootstrap CIs over prompts.

Qwen3.5-2B, native MTP head retrained on 600 of the model's own answers (L4, bf16):

Engine Arm Acceptance Speedup vs no draft
llama.cpp stock head 0.740 1.51x [1.48, 1.55]
llama.cpp trained head 0.757 1.53x [1.49, 1.57]
vLLM 0.31.0 stock head 0.747 1.55x [1.51, 1.59]
vLLM 0.31.0 trained head 0.766 1.57x [1.53, 1.61]

Trained vs stock is a tie on this small model (llama.cpp 1.013x [0.996, 1.032], vLLM 1.015x [0.999, 1.031]; an A100 run gave 1.035x [1.018, 1.052]). The default learning rate for the MTP head is 2e-5: at 1e-4 the retrained head drafted worse than stock (acceptance 0.53 vs 0.70).

Qwen3-1.7B, new EAGLE-3 drafter from 6,000 dataset rows, 2 epochs (T4, fp16): llama.cpp acceptance 0.449, 1.28x [1.21, 1.35] vs no draft, 60/60 outputs identical; vLLM acceptance 0.463, about 2.2x (the T4 no-draft baseline was noisy).

Limits

  • A drafter learns the prompt format it was trained on: trained on Alpaca-formatted rows, it drafts worse on chat-template prompts (the EAGLE-3 drafter above was slower than no draft there, 0.81x), so train it on rows formatted the way the model will be served.
  • "Model's own answers" regenerates every example (600 prompts took about 35 minutes on an A100).
  • EAGLE-3 was not run on a bf16 GPU end to end.
  • The trained-MTP marker lives in drafter.json beside the GGUF, not in GGUF metadata; a GGUF downloaded on its own keeps Studio's default MTP policy.
  • LoRA-only exports keep the MTP head beside the adapter but do not carry the EAGLE-3 folder.
  • No drafter training on Mac (MLX) yet.

Screenshots

Before (base) on the left, after (this PR) on the right.

Train tab, advanced view: the new collapsed "Speculative Decoding Drafter" section under the training hyperparameters.

drafter section

Qwen3.5-2B (native MTP head): "Retrains this model's MTP head".

qwen3.5 mtp

Qwen3-1.7B (no MTP head): "Trains an EAGLE-3 drafter (this model has no MTP head)".

qwen3 eagle3

Gemma 3 1B: no drafter either engine can run, so the checkbox is disabled with the reason.

gemma3 disabled

FastModel.get_mtp_head loads a Qwen3.5/3.6 checkpoint's native MTP head (transformers drops mtp.* on load) and attaches it; UnslothMTPTrainer / UnslothDSparkTrainer train drafters against the frozen model. Every merged, GGUF, Hub and LoRA save path then writes the trained head instead of copying the stock one through.
@danielhanchen danielhanchen self-assigned this Oct 15, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 15, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 15, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 15, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 15, 2026
@danielhanchen
danielhanchen marked this pull request as ready for review October 15, 2026 10:00
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-15T17:31:43.200298Z 1a02f55 New commits
🔒 Security Review ✅ Completed 2026-10-15T10:12:54.686684Z 5365a6d Manual request

Security findings

Advisory findings (3)

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5365a6d5c3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +131 to +135
@field_validator("max_examples", "draft_steps", "epochs", mode = "before")
@classmethod
def _reject_booleans(cls, value: Any) -> Any:
if isinstance(value, bool):
raise ValueError("expected a number, not a boolean")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject boolean drafter learning rates

The numeric validator omits learning_rate, so Pydantic accepts an API payload such as "learning_rate": true by coercing it to 1.0, which passes the field bounds and starts drafter training at an extreme rate rather than rejecting the malformed request. Include learning_rate in the boolean rejection applied to the other numeric drafter settings.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: a boolean learning rate is a malformed API payload the UI never sends; the bounds still apply.

Comment on lines +1954 to +1958
except Exception as exception:
logger.warning(
f"Could not package the trained drafter with the GGUF export: {exception}"
)
return []

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Surface EAGLE-3 conversion failures as export failures

If EAGLE-3 conversion fails—for example because the merged checkpoint is missing or the converter writes no GGUF—package_gguf deliberately raises because the exported pair is incomplete, but this wrapper suppresses the exception and the operation reports a successful GGUF export with no drafter. Users who requested and trained the drafter receive an incomplete artifact while the frontend has no warning beyond logs; propagate the failure or return it in the export response.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By design: a drafter conversion failure must not fail the GGUF export the user asked for; it is logged and the response carries no drafter, so the export banner does not claim one.

Comment on lines +73 to +77
export function normalizeDrafterLearningRate(value: unknown): number | null {
const n = Number(value);
return value !== null && value !== "" && Number.isFinite(n) && n > 0
? n
: null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Enforce the learning-rate upper bound in the frontend

The backend caps learning_rate at 1.0, but this normalizer returns every finite positive value unchanged and the number input has no max, unlike the other drafter controls that clamp to backend bounds. Entering a value above 1 therefore produces a 422 response when Start is pressed instead of a normalized request; clamp to the backend maximum or reject the field in the UI before submission.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: a learning rate above 1 is rejected by the backend with a clear 422, which is the right answer for that input.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 22483a6670

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

from huggingface_hub import hf_hub_download

path = hf_hub_download(repo_id, DRAFTER_MANIFEST, token = token)
for name in ("adapter_config.json", "mtp_head.safetensors"):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Resolve Hub EAGLE checkpoints before packaging

When a previously exported EAGLE-3 checkpoint is loaded from a Hub ID such as owner/model, this recovery path downloads only the manifest and MTP files, so training_manifest() cannot find eagle3/config.json and treats the trained drafter as absent. Consequently, re-exporting that Hub checkpoint to merged or GGUF silently omits its EAGLE sidecar; download the EAGLE directory and propagate the resolved snapshot directory to the packaging functions instead of retaining the raw repo ID.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this: re-exporting a model that was itself loaded back from a Hub export is outside what this PR covers; drafters ship with exports made from the training run's own checkpoint.

Comment on lines +268 to +270
if manifest is None or manifest["strategy"] != "mtp" or not head_saved:
clear_stale(adapter_dir)
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Carry EAGLE drafters with LoRA exports

When an EAGLE-3-trained LoRA run is exported as an adapter, save_pretrained() writes only the adapter and tokenizer, and this condition then rejects every non-MTP manifest and clears any drafter metadata instead of copying eagle3/. The exported local folder or Hub adapter permanently loses the trained drafter, so a later merged or GGUF export from that adapter cannot recover it; preserve the EAGLE directory and manifest alongside LoRA adapters just as the MTP sidecar is preserved.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this: LoRA-only exports carrying the EAGLE-3 folder are listed as a limit in the PR description; merged and GGUF exports from the run carry it.

…d, retry failed capability probes while drafter training stays on
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 48187a9873

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines 373 to +376
return {"output_path": output_path}


def _with_drafter(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include drafter metadata when recovering export results

When an export POST response is lost—for example through the Cloudflare 524 path explicitly handled by runRecoverableOp—or the page reloads during the export, the frontend reconstructs the result from GET /status. That route still returns only last_op_output_path and never invokes this helper, so the recovered result has no details.drafter and the new “Includes trained drafter” note disappears even though the artifact contains one. Expose the drafter block through status recovery as well as the direct POST responses.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this: the exported files carry drafter.json either way; this only affects the one note on the export page after a lost response or a reload mid-export.

Comment on lines +202 to +206
with lock:
hit = _CAPABILITY_CACHE.get(key)
if hit and time.time() - hit[0] < _CAPABILITY_TTL_S:
return dict(hit[1])
with _PROBE_SLOTS:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid blocking the shared executor while probes wait

The route runs this entire function through asyncio.to_thread, so every concurrent capability request occupies a worker from the process-wide default executor while waiting on either the per-key lock or _PROBE_SLOTS. Once requests reach the executor's worker count—multiple tabs requesting the same cold model is sufficient—all remaining workers can be blocked behind one or two probes for up to the 300-second subprocess timeout, starving unrelated endpoints that also use asyncio.to_thread. Acquire/coalesce probe capacity without occupying the shared executor, or move these waits to a dedicated pool.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this: the frontend sends one probe per model and token, answers are cached, and same-model requests coalesce on the per-key lock; filling the default executor needs dozens of concurrent probes of different cold models, which the Train tab does not produce.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 48187a9873

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +337 to +340
const refused =
capability !== null &&
capability.model_name === config.selectedModel &&
!capability.supported;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Retry inconclusive probes before dropping the drafter request

When the capability subprocess times out, crashes, or emits no result, the backend returns HTTP 200 with supported: false and the reason “Could not check this model for drafter support.” The hook therefore records the probe as successfully completed rather than retryable, and this predicate treats that transient result as a definitive refusal. For the same model/token selection, a user who enabled drafter training will then have the drafter block omitted from every start request until the selection changes or the page reloads, even if the backend's training-time check would now succeed. Distinguish inconclusive probe failures from actual unsupported models or allow them to be retried before suppressing the requested phase.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in bec187c: a probe that could not run is marked inconclusive; the Train tab retries it and still sends the drafter block (the backend re-checks before the drafter phase).

Comment on lines +34552 to +34554
if canonical_mode == "eagle3" or (
_auto_mode and eagle3_draft_path and caps.get("supports_eagle3")
):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Record unsupported Auto EAGLE-3 as a binary fallback

When Auto finds a paired EAGLE-3 sidecar but the installed llama-server does not yet advertise draft-eagle3, the supports_eagle3 requirement makes this entire branch unreachable. Execution falls through to the ordinary MTP/ngram routing, so it never records spec_drafter_kind = "eagle3" or binary_no_mtp. Consequently, after the user updates llama.cpp to a build with EAGLE-3 support, applying the unchanged Auto configuration is deduplicated instead of invoking the existing binary-fallback retry logic, and the trained sidecar remains unused until some unrelated setting forces a reload. Enter the EAGLE-3 branch whenever Auto has the paired sidecar, then let its capability check record the recoverable fallback.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this: it needs llama.cpp updated under an already loaded model with no reload in between; the next load picks the sidecar up, and a binary without draft-eagle3 keeps today's routing.

Comment on lines +166 to +168
dest = os.path.join(final_dir, EAGLE3_DIRNAME)
shutil.rmtree(dest, ignore_errors = True)
shutil.copytree(os.path.join(checkpoint_dir, EAGLE3_DIRNAME), dest)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid deleting the source EAGLE directory on in-place exports

If a local merged or base export targets the loaded training checkpoint directory itself, which the export path resolver currently permits, dest and the source <checkpoint>/eagle3 are the same path. This removal therefore deletes the only trained EAGLE-3 checkpoint before copytree tries to read it; the packaging wrapper suppresses the resulting error, so the otherwise successful export permanently loses the drafter from the source run. Detect identical resolved source/destination paths or stage the copy before replacing the destination.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in bec187c: when the export folder is the training folder, eagle3/ is left in place instead of deleted and re-copied.

… request, keep eagle3/ on an export into the training folder
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: bec187c884

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 1be7795 into main Oct 15, 2026
@danielhanchen
danielhanchen deleted the studio-drafter-training branch October 15, 2026 17:32
danielhanchen added a commit that referenced this pull request Oct 15, 2026
…3909)

With #13846 merged, main (d303bac) is still red in Backend CI and
Repo tests, from three regressions that landed in the last few hours.
Each is reproduced locally on main and fixed here.

## 1. `test_text_io_names_its_encoding[drafter.py]` (from #13806)

```
drafter.py:222: subprocess(text = True) without encoding
```

`core/training/drafter.py` runs the drafter capability probe in a child
interpreter with `text = True` and no encoding, so the parent decodes
the child's output with the locale codec (cp1252 on Windows, ASCII under
a C locale). The guard is right and the code is what changes: the call
now passes `encoding = "utf-8", errors = "replace"`, and the child gets
`PYTHONIOENCODING=utf-8` so it writes what the parent reads. That
matches how `core/training/worker.py` runs its own probes. The payload
line is `json.dumps` output, so nothing parsed changes.

## 2. `test_backfill_splits_a_quant_suffix_the_way_the_backend_does`
(from #13899)

```
AssertionError: MXFP
```

#13899 widened the GGUF known-quant pattern from `MXFP...` to
`(?:MX|NV)FP...` so NVFP4 files get their own variant key. That change
is right, and it was made consistently in all three places that must
agree: `core/inference/llama_cpp.py` (`_GGUF_KNOWN_QUANT_RE`),
`hub/utils/gguf.py` (`_GGUF_QUANT_RE`) and the frontend's
`model-identity.ts` (`QUANT_TOKEN_SOURCE`). The test was checking that
the literal substring `MXFP` appears in `llama_cpp.py`, which it no
longer does.

The test now checks the property it was standing in for: it reads the
pattern string out of both Python modules with `ast` (adjacent literals
joined as Python joins them) and the TypeScript constant, asserts all
three are identical, and asserts the shared pattern still fully matches
`MXFP4`, `NVFP4`, `IQ4_XS`, `TQ1_0`, `Q4_K_M`, `Q8_0`, `BF16`, `F16` and
`F32`. That is stricter than before, since a pattern edited on one side
only now fails, and it no longer breaks on a correct rewording.

## 3. `test_every_tracked_python_file_is_already_formatted`

Formatter drift (pinned ruff 0.6.9 via `scripts/run_ruff_format.py`),
output only, no logic change:

| file | from |
| --- | --- |
| `studio/backend/core/inference/llama_cpp.py`, `offload_layout.py`,
`tests/test_nemotron35_bolt_super.py`,
`tests/test_nemotron35_planner.py` | #13899 |
| `studio/backend/tests/test_muse_spark.py` | #13903 |
| `tests/test_norm_fast_launch.py`, `unsloth/kernels/layernorm.py` |
#13889 |
| `tests/test_remote_code_class_and_expert_submodules.py`,
`unsloth/models/_utils.py` | #13851 |
| `tests/test_triton_fp_fusion.py` | #13846 |

## Verification

- `tests/test_formatter_fixed_point.py` (ruff 0.6.9): fails on main, 16
passed here.
- `tests/studio/test_model_picker_contracts.py` and
`tests/test_runtime_text_encoding.py`: 210 passed.
- `studio/backend/tests/test_text_io_encoding.py`,
`test_nemotron35_bolt_super.py`, `test_drafter_training.py`: all pass
except `test_capability_child_process_runs_for_real`, which fails
identically on main without this change on this host (it runs the probe
in a real child interpreter) and is not failing in CI.
- Sabotage on the rewritten picker guard: dropping `NV` from the pattern
in `hub/utils/gguf.py` only, or in `model-identity.ts` only, fails it;
restored, it passes.
- Sabotage for (1) is main itself: without the encoding, the guard fails
as quoted above.
danielhanchen added a commit that referenced this pull request Oct 15, 2026
…13922)

`(Python 3.13, rest)` is red on main since #13806 (1be7795),
including on #13909's own run:

```
FAILED studio/backend/tests/test_tensor_parallel.py::test_mtp_decode_probe_wired_under_tensor_parallel
AssertionError: the probe must precede the drafter-drop fallback
```

#13806 is right. It made an EAGLE-3 drafter droppable on a failed load
like the others, so the fallback in `LlamaCppBackend.load_model` became

```python
if (
    not healthy
    and (
        _spec_requested_mtp
        or _spec_requested_dspark
        or _spec_requested_dflash
        or _spec_requested_eagle3
    )
    and not _load_cancelled()
):
```

The test located that block with `src.find("and (_spec_requested_mtp or
_spec_requested_dspark or _spec_requested_dflash)")`, the old one-line
spelling. After the change `find` returns -1, so `0 <= probe < fallback`
fails even though the probe still comes first. The ordering it guards is
intact.

The test now finds the fallback by its shape: `not healthy and (`
followed by the `_spec_requested_mtp or _spec_requested_dspark ...
_spec_requested_dflash` alternatives, whitespace and line breaks
allowed, so adding another drafter kind or rewrapping does not break it.
If no such block exists it fails with its own message (`load_model no
longer has a drafter-drop fallback for MTP`) rather than reporting a
misleading order failure.

Verification:
- `studio/backend/tests/test_tensor_parallel.py`: fails on main as
above, 111 passed with this change.
- Sabotage, `_spec_requested_dflash` removed from the fallback in
`llama_cpp.py`: fails with `load_model no longer has a drafter-drop
fallback for MTP`.
- Sabotage, the fallback block moved ahead of the probe in the source
the test reads: fails with `the probe must precede the drafter-drop
fallback`.
- `tests/test_formatter_fixed_point.py`: passes.
danielhanchen added a commit that referenced this pull request Oct 15, 2026
Main (bd06376) is red in Backend CI on five tests, seen on every PR
based on it (#13914, #13919). Four come from #13850 and #13806, which
are both right; one comes from my own #13909. Each is reproduced locally
on main and fixed here.

## From #13850 (token preview)

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

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

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

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

## From #13806 (drafter training)

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

## From #13909 (mine)

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

## Verification

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

Two gaps in the drafter flow from unslothai#13806.

## Packed rows were one drafter example

`_row_examples` split a packed row only where `position_ids` restart at
0. TRL's packed dataset (`pack_dataset(..., strategy="bfd")`, used by
`packing=True`) stores the boundaries as `seq_lengths` and only builds
`position_ids` later in its collator, so the rows the drafter phase
reads from `trainer.train_dataset` have no `position_ids`. With packing
on, every packed row became one long example: the drafter was trained
across unrelated documents, and `data_source="regenerate"` found only
the first prompt of each packed row.

`_row_examples` now cuts at `seq_lengths` when they add up to the row
length, and still falls back to `position_ids` for older layouts. Rows
packed with the `wrapped` strategy carry no boundaries, as before.

## Hub full fine-tunes lost their trained MTP head on export

`_attach_full_checkpoint_mtp_head` returned early for anything that is
not a local folder, so loading a full fine-tune with a trained MTP head
by Hub id never reattached it. transformers drops the `mtp.*` tensors on
load, the merged save only stitches an attached head, and
`package_merged` still wrote an MTP `drafter.json` next to a model whose
config had its MTP declaration stripped.

The manifest is now read with `training_manifest(checkpoint_path,
token)`, which already resolves Hub ids with the load's credential, and
the head is loaded from the local snapshot the load just cached (found
through `config.json` at the loaded commit, `local_files_only=True`), so
a private repo needs no extra credential plumbing and nothing large is
downloaded. Local folders behave as before.

## Tests

`studio/backend/tests/test_drafter_training.py`:
- `test_examples_split_trl_packed_rows_at_seq_lengths` packs three
documents with real TRL `pack_dataset` and checks one example per
document, each with its own mask and prompt. On main it gets two
examples, one of them spanning two documents.
- `test_export_reattaches_the_head_of_a_hub_full_fine_tune` loads by Hub
id and checks the head is attached from the cached snapshot at the
loaded commit with the load's token, and nothing is attached without a
manifest. On main `get_mtp_head` is never called.

Both fail on main and pass here; `test_drafter_training.py` and
`test_drafter_launch_flags.py` pass (75).

Not covered: a real Hub full fine-tune exported end to end, and the
separate case where both `completion_mask` and `assistant_masks` are
present (only `completion_mask` is applied).

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant