Skip to content

Unsloth: native Clef Decisions and PyTorch image serving - #12770

Closed
wasimysaid wants to merge 24 commits into
unslothai:mainfrom
wasimysaid:workbench/add-clef-models-to-studio-decisions-2c01ce
Closed

wasimysaid wants to merge 24 commits into
unslothai:mainfrom
wasimysaid:workbench/add-clef-models-to-studio-decisions-2c01ce

Conversation

@wasimysaid

@wasimysaid wasimysaid commented Oct 5, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Extend Unsloth's existing Clef Flash (9B) and Clef (27B) Decision API support with native text decisions and an explicit PyTorch image fallback. Use the joint-schema heads, not chat generation. Keep bounded media validation, pinned downloads, cache leases, device arbitration, owned-worker retirement, authentication and existing Laya/connection behavior.

Merged upstream main 37bee346 into this branch, preserving its Clef fine-tune serving and account isolation. Reuse the core-vendored Apache-2.0 adapter instead of shipping a second source/license copy.

Cleanup and current native support

  • Removed duplicate adapter/license and redundant test setup/comments; docs 105→62. After CI's canonical formatting, the lifecycle/API suites are 317/191 lines; the new fallback-download regression is 91. No arbitrary test splitting or dropped cases.
  • Latest verified Unsloth llama.cpp: b11443-mix-d65395f, built from 4021fda1a. The actual CPU binary serves /v1/systemone; source also includes Clef projector conversion and image requests.
  • This PR's pinned native GGUF plan still has no projector, so images use PyTorch. Video/audio remain rejected. Native startup/inference errors do not trigger backend retries.

Verification

Current refresh: 231 backend tests passed (8 existing optional skips), 36 frontend tests passed, production build, typecheck, translation parity, Ruff/compile and security checks passed. The shared audited adapter loads with UTF-8 config reads; native capability detection and a real CPU router endpoint probe passed. No fresh model inference is claimed for this refresh; earlier model/SDK evidence is retained in fork PR #221.

The broad combined backend command hits a loggers collection defect reproduced on main. Splitting the groups yielded 645 passing Hub tests and five cache-fixture failures also reproduced on main; the larger backend batch timed out, so it is not claimed complete. Existing informational ESLint/Biome baseline failures remain; new formatting errors were fixed. Remote CI is left to the maintainer as requested.

Auto fallback download fix

Codex's cache finding is genuine. After native weights finish, Auto exposes missing PyTorch fallback assets through the existing user-triggered download flow; it does not claim full cache readiness or silently download them. Explicit backends and no-PyTorch installs are unchanged. The 91-line regression covers both models: four cases fail before, all 14 pass after. Related backend tests: 278 passed, 8 existing skips; fix-scoped CI-equivalent checks and audits pass. The real component renders the fallback Download action at desktop/mobile widths (fixture API responses; screenshots inspected). No completed transfer or fresh model inference is claimed.

Training interlock fix

Both training findings are genuine. GPU Clef admission checks LLM/diffusion training state, and both trainers retire owned GPU workers and pending loads; resident CPU workers remain usable. Training refuses to proceed if a worker has not reaped. The 187-line regression suite has 11 failures before and all 17 cases passing after. Related tests: 377 passed, 8 existing skips; current-head scoped lint/compile/tests pass. Training state is mocked and retirement uses real lightweight child processes; no live GPU training/model test is claimed.

danielhanchen added a commit that referenced this pull request Oct 6, 2026
…x slot (#12781)

* Branch picker chevrons: give back the 24px hit target in the same 20px slot

#12735 shrank .aui-branch-chevron-btn from 24x32 to 20x20 to make the chevrons read
as part of the count. That dropped them under the 24px every footer control keeps
since #12173, which playwright_user_message_time.py checks, so 'Frontend build +
bundle sanity' fails on main once its earlier steps pass (#12770, #12772).

Size the button 24px and take the extra 4px back with a -2px margin. Every footer
element stays where it was and the glyph centres do not move; only the clickable
area grows, and with no hover fill it is not visible.

* Branch picker chevrons: make 24px a floor, not a multiple of the space scale

24px * --ui-space-scale fell to 19.2px at the 12px UI font size (scale 0.8). Size
the target as max(24px, the scaled 20px slot) and hand the difference back with the
margin, so the slot and the glyph centre still follow the scale while the hit area
never drops under 24px. Add the 12px layout to playwright_user_message_time.py,
which only covered 15px and 20px and so could not see it.

* Branch picker chevrons: grow the hit area toward the count, and scale its floor with Interface Scale

The symmetric -extra/2 margin pushed Previous over the Delete/More button beside it:
at the 12px UI font the gap is 1.6px and the extra 8px, and at the browser's 50%
Interface Scale a fixed 24px reached 7px past the slot. In an overlap the later
element wins the click.

Put the extra on the inner side only (toward the count, which is not a control),
with padding keeping the glyph where it was, and make the floor 24px times the
browser Interface Scale, as browser zoom would. The browser check now asserts no
two footer controls overlap and adds the 50% Interface Scale layout; the previous
commit fails the overlap check at 12px.

* Branch picker chevrons: extend the hit area with a ::before so the button and focus ring stay as drawn

Growing the button itself moved its focus ring: a 24px circle off the glyph's
centre and over the count. The button is back to the 20px slot, scaled; an
invisible positioned ::before carries the extra toward the count, and, being
positioned, paints over the count so presses there reach the chevron (the
previous padding never did: the count, painted later, took them).

The layout check now measures each control's real target by hit testing the
middle of every edge, and requires the chevron's own box to stay square and
unpadded so the ring stays centred on the glyph.

* Branch picker: keep the count at least as wide as both chevron extensions

In a narrow custom chat font a short count such as 1/2 can be narrower than
the two ::before extensions together, and Next would then win presses on the
inner edge of Previous. The count now has a minimum width of both extensions
plus 1px, centred; any count wider than that, the usual case, is untouched.
The layout check gains a narrow-count layout at the smallest UI font.

* Branch picker: reserve room above and below for the chevron targets

At 200% Interface Scale and the 12px UI font the target reaches 8px past the
box on each side, more than the footer's 6.4px row gap, so once the picker
wrapped onto its own row it took the lower edge of the action buttons above.
The chevrons now carry block margins of half the extra: inside one row with
the actions they fit in the row's height and nothing moves; a wrapped picker
row grows to hold its targets. The layout check gains 200% layouts at 375 and
320px; the previous head fails them.
@wasimysaid

Copy link
Copy Markdown
Collaborator Author

Review reconciliation on unchanged head 5d6fe71325ec699fb7368e93572eb7b8fc52e57e: exact-head Codex is clean. All seven historical fork review threads now have concise fix/evidence replies and are resolved; their fixes were already present, so no code changes or new test/model runs were needed. Paginated checks found no newer actionable findings on either PR. CI remains for the user to check manually; no waiting or reruns.

@wasimysaid

Copy link
Copy Markdown
Collaborator Author

@codex review

@wasimysaid wasimysaid changed the title Studio: add Clef Decisions with native text and PyTorch fallback Unsloth: native Clef Decisions and PyTorch image serving Oct 7, 2026
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 7, 2026
… GGUF (unslothai#12939)

* Studio: fine-tune Laya decision models and serve them

* Check decision checkpoints at their subfolder, refuse DoRA/LoftQ, steady the toy test

* Turn gradient checkpointing back on in FastDecisionModel.for_training

* Merge decision LoRA on a CPU copy, check decision subfolders before the repo root

* Log decision runs to TensorBoard when it is enabled

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Block a decision run whose model config failed to load, gate the GPU memory test on a real CUDA device

* Use the AGPL-3.0 SPDX header on the new decision model files

* Record the vendored laya import in the risky loader baseline

* Train Cloudflare Clef decision models with FastDecisionModel

* Install the Qwen3.5 fast-path kernels for Clef decision runs, test they engage

* Studio: train and serve Cloudflare Clef decision models

Clef and Clef-flash repos (config.json plus joint_head.*) are detected as
decision models next to Laya. Training goes through FastDecisionModel with
QLoRA allowed and the Qwen3.5 fast-path kernel setup the worker skips for
Laya. The Decision API lists clef and clef-flash and Clef fine-tunes, and
serves them from a spawn child that loads the backbone through Unsloth, so
unloading returns the GPU memory. Clef waits for the GPU while a run trains
instead of loading on CPU.

* Keep Clef off fp16 autocast and fp16 weights

* Vendor Cloudflare's Clef joint_schema_model.py unmodified

* Drop the decision trainer's backward rescale: accelerate never scales the loss here

* Run the decision toy task on CPU, where its dropout stream is fixed

* Fold Clef calibration into the saved head; add label smoothing and Brier loss options

* Build Clef's encoding and head on the vendored joint_schema_model.py

* Check Clef reloads against the folded temperature; skip Clef forwards on CPU when causal_conv1d is installed

* Batch the Clef head, pool its fp32 norm in chunks, checkpoint and compile it

* Record QLoRA in Clef run metadata, stub decision_layout in the export route test

* Decision runs: hold out from training when eval files are training files, honour a cancel during calibration

* Serve Clef with the trainer's temperature rule, incl. option-count buckets

* Fetch a decision checkpoint by its layout so Unsloth's download check accepts it

* Save decision models crash-safely and fold Clef's calibrated temperature into its head

* Load Clef in Unsloth's dynamic 4-bit and train it in float16 and bfloat16

* Add Cloudflare's Clef recipe options and record accuracy, drop the no-op accumulation wrapper

* Run the toy learning test on CPU, where its step budget was tuned

* Format the decision model changes

* Run the Clef head under torch's checkpoint and autocast's matmul dtype; add a train bench

* Refuse Clef on machines without an NVIDIA or AMD GPU, and mark it unavailable in Settings

* Read Clef availability in Settings from finished device detection only

* Keep a Clef save's tokenizer files and config version as the source has them

* Score the Clef bench's head parity against an fp32 per-record oracle

* State the AGPL header and Cloudflare derivation notice on clef.py

* Keep the Clef head's norm op off Unsloth's patched layer_norm; compile test after a model load

* Keep Clef's logit scales float32 on save and fit its temperature with a line search

* Skip the bfloat16 Clef training test on GPUs without bfloat16

* Read the Qwen3.5 kernel a layer picked on transformers before 5.6 too

* Turn a plain language model into a Clef-style decision model with FastDecisionModel

FastDecisionModel.from_pretrained(<causal LM or Qwen3.5 VLM>, decision_head = "clef") loads the
backbone through FastModel and adds a fresh joint schema head sized to its hidden states (width
1024 from hidden 3072 up, else 512; head_width / head_config / head_init override). The model
trains, evaluates, calibrates and saves like a Clef checkpoint. freeze_backbone / unfreeze_backbone
give the head-only warm-up stage.

* Convert public datasets into decision rows and mix them with schema augmentation

decision_datasets.py maps BANKING77, CLINC150 (with out of scope), MNLI, SNLI, WANLI, BoolQ,
AG News, SST-5, MMLU, CommonsenseQA, ARC, xLAM tool selection, deepset prompt injections and
LocalLLaMA/typed-decisions to {state, questions, gold} rows with their licences. augment_row
renames question and option ids, paraphrases or drops instructions, subsamples large option
sets around the gold, adds a derived question of another type, renders states as text and
shuffles field order. build_decision_mixture balances sources, refuses Decision Index
eval-only sets and drops rows sharing a 13-word shingle with given evaluation texts.

* Add a script that trains a decision model from a plain language model

scripts/train_decision_from_lm.py builds the public-dataset mixture (decontaminated against
the evaluation sets) plus LocalLLaMA/typed-decisions, adds a fresh Clef head, optionally warms
it up with the backbone frozen, trains LoRA plus the head, calibrates, and reports accuracy,
ECE and record accuracy on typed-decisions test, BANKING77 and CLINC150.

* Load plain language models with the Clef loading rules and ship Cloudflare's loader on save

A model converted with decision_head = "clef" now gets the same dynamic 4-bit config and
float32-path bookkeeping as a Clef checkpoint, records the source vocabulary for the save, and
copies the vendored unsloth/_vendor/clef/joint_schema_model.py into a Qwen3.5 save so
Cloudflare's load_release_model loads it. The example script reports FastDecisionModel.evaluate
metrics, and the test checks served probabilities through the folded head temperature.

* Compare reloaded decision logits within bf16 rounding of their scale

* Add the license header to the decision-from-LM tests

* Apply the gradient accumulation fix for Laya training on transformers 5.0 to 5.5

* Review the vendored Clef config read and skip the Clef head compile test on CPU

* Name the Clef norm-pool fake kernels instead of reusing _

* Add FastDecisionModel.predict and adapter plus head saves for Clef decision models

predict() answers one Decision API request for Laya, Clef and language models
converted with decision_head="clef", at the calibrated temperatures, in the
Decision API answer shape. save_pretrained on a LoRA Clef model now writes only
the adapters, the joint head and the configs; from_pretrained puts them back on
the base model. save_pretrained_merged stays the Cloudflare-compatible layout.

Ported from unslothai#12796 onto the Clef joint schema head.

* Studio: train text and vision LLMs as Clef decision models and serve them

A decision run on a model that is not a Laya or Clef checkpoint now trains the
LLM with a fresh Clef joint schema head (decision_layout "llm"), with its own
recipe and QLoRA. The model config route answers as_decision=true for text and
vision LLMs. The run saves the merged Clef layout, so the existing Clef runtime
serves it through the Decision API; that runtime now answers through the
library's Clef decide, and also serves adapter plus head folders on their base.

* Studio: add Train as Decision model for text and vision LLMs on the Train page

Ported from unslothai#12796. The choice asks the backend for the model
as a decision model, applies the LLM decision recipe, keeps QLoRA and the
recipe's context length for Clef and LLM decision runs, and is hidden for Laya,
Clef, audio and embedding models.

* Serve Clef with the calibration autocast rule, calibrate a one-row holdout, and give Clef full fine-tunes the full fine-tuning rate

* Send Clef's recipe optimizer instead of forcing torch AdamW on every decision run

* Stop a Clef worker that times out loading or that training overtakes

* Count every Clef question in the held-out decision count

* Never reuse a Clef worker after a timeout or a dead pipe

* Detect a local decision model's layout in the selected subfolder

* Refuse KL regularization for a fully fine-tuned Clef at construction

* Plan decision runs on the one GPU they use and keep an env-pinned local Clef's layout

* Keep full Clef fine-tunes unquantized, save a resized Laya vocabulary, and stop flagging exact-fit Clef prompts as truncated

* Load plain language models as Clef decision models by default and run the decision notebook

FastDecisionModel.from_pretrained on a model that is neither a Laya nor a Clef
checkpoint now adds a Clef head without decision_head. predict answers carry
"answer" (the option, True or False for noul, the level for score) and every
option's probability. DecisionTrainer checkpoints a Clef model as adapters plus
its float32 head and resumes from them, a float16 language model keeps fp16,
and a test runs unslothai/notebooks#380's call sequence on a tiny Qwen3.5.

* Stand in for unsloth in the Clef truncation test on Studio's backend CI

* Load Clef backbones on one device when no device_map is given, and make decision tests portable to multi-GPU, Windows and Apple Silicon hosts

* Load a plain LM backbone for a decision model on one device when no device_map is given

* Keep download caches out of Clef saves, read long states in predict, compile the Clef head only for long runs

The merged save downloads the base shards with local_dir set to the save
folder, which left .cache/huggingface in it; the staging copy now drops it and
the save tests check the folder holds only model files. build_dataset reports
how many inputs were cut at max_seq_length, and predict() reads up to 16384
tokens like Studio's Decision API. DecisionTrainer compiles the Clef head only
when the run is long enough to pay for the compile; UNSLOTH_CLEF_COMPILE=1 or 0
forces it either way.

* Score Clef metric passes in the run's batch size and drop the parent run's training record when loading a Clef checkpoint

* Compile the Clef head from 5000 forward passes, its measured break-even on Qwen3.5-2B

* Refuse Clef LoRA options it cannot apply and stop a loading Clef worker as soon as training starts

* Train Clef under the bf16 autocast it evaluates in when no precision is given, and keep ACCELERATE_MIXED_PRECISION in step for transformers 4.x

* Bound the Clef reload check by the logit scale, which varies run to run, and give its asserts messages

* Test that a plain LM decision model with float32 norms trains without a precision flag

* Bound the plain LM reload check by its measured spread across runs

* Score the plain LM reload check under the autocast serving uses

* Run the Clef head eagerly unless UNSLOTH_CLEF_COMPILE=1

Compiling the head costs minutes in every process, warm Inductor cache included, and
does not speed up a real backbone. Qwen3.5-2B, batch 8, 25 steps, same card per row:

  card       eager s/step  compiled s/step  compile cost per process
  L4         2.94          2.99             about 17 to 18 min
  G4         0.481         0.488            about 7 min
  A100       0.785         0.779            about 17 to 18 min
  T4         10.30         10.42-10.46      about 17 to 18 min
  Kaggle T4  10.47-10.48   10.46-10.53      about 16 to 17 min

Only the tiny test model, where the head is most of the work, gets faster compiled, so
no run length makes the old 5000-forward threshold pay off. The head now runs eagerly
by default, UNSLOTH_CLEF_COMPILE=1 opts in and 0 still forces it off. The threshold and
DecisionTrainer.train override that set it are removed.

* Autocast Clef inference in fp16 on GPUs without bf16

A plain language model loaded in fp16 on a T4 keeps fp32 norms, so predict, calibration
and serving ran its fp16 Linears on fp32 activations without autocast and failed with
"expected mat1 and mat2 to have the same dtype" (Colab T4 and Kaggle 2x T4, tiny Qwen3).
Inference now autocasts as Clef trains: fp16 there, bf16 where supported, never on
Unsloth's float32 path for Qwen3.5. Both T4s pass the decision tests with this change.

* Refuse decision training on MLX before the Clef GPU check, so Apple Silicon users see the MLX limit

* Add the on-disk contract for decision model GGUF exports

* Export Clef and Laya decision models to GGUF with their served temperatures

* Export decision models to GGUF from the Studio Export page

* Add the on-disk contract for decision GGUF exports

* Serve Clef decision models through Studio's llama.cpp

Ports the native llama-server worker from unslothai#12770 (by wasimysaid) onto the Laya/Clef runtime: GGUF companions for clef-flash and clef, current GGUF exports of fine-tune folders, a systemone_backend setting (auto, llama.cpp, pytorch) and systemone_native_ctx, image input through llama.cpp, idle unload, GPU arbiter and training coordination, and answers rebuilt with the PyTorch formatter.

* Show the Decision API runtime and let the owner pick it

* Keep the file mode when rewriting decision GGUF metadata and export.json

* Fingerprint stock Clef checkpoints, which have no Unsloth decision config

* Warn that k-quants move decision model probabilities more than q8_0

* Use the shared decision GGUF export contract from the serving side

* Write export.json in the exporter and read exports from the run folder

* List Laya decision runs in the Export page checkpoint list

* Translate the Decision API runtime and media strings in every locale

* Harden decision GGUF export: stale source folders, old quantizers, Laya head length, cleanup on cancel

save_pretrained_gguf adopts the save directory as the export source only when its
fingerprint matches the merged weights, so an in-memory calibration is not served
against the stale folder. k-quants are refused before the merge when the llama.cpp
folder predates b11443, and the quantizer output is captured even with
print_output=True so the hint still fires. Laya exports write the head length
PyTorch serves. Temp folders carry the pid, SIGTERM unwinds the export, and a later
export removes folders left by a killed process.

* Report only a current decision export on the Export page and expand ~ in its path

decision_preview listed export.json as existing even when the run folder had changed
since or its GGUF files were gone. It now requires a matching layout and fingerprint
and lists only quantizations whose files exist. The export worker expands ~ before
the eligibility check and the export.

* Judge GGUF parity by probability difference, answers and NLL, not ECE

ECE bins by the top answer and broke ties by dict order, so near-uniform answers
moved it. Ties now break by a fixed option order and ECE is reported only. Q8_0 on
the calibrated Clef fine-tune gets a 0.05 tolerance, BF16 and F16 stay at 0.01.

* Allow 0.02 BF16 parity at the 0.25 temperature floor in the real GGUF test

* Harden native Clef serving: image errors, GPU claims and Auto fallback

- Map llama.cpp's HTTP 500 "Failed to load image or audio file" to a 422
  input error instead of retiring the server; accept only PNG and JPEG
  and decode-check each image with PIL before dispatch.
- Release the Decision API GPU claim after a slow close only when no
  llama.cpp GPU load is in progress and no GPU server is resident.
- Answer a chat load refused by a busy decision server with 409 and
  Retry-After 5 instead of 500.
- Under Auto, keep text on PyTorch when another model owns the GPU or
  when only the PyTorch checkpoint is cached; images and forced
  llama.cpp keep the native path.
- Retry an over-long state on PyTorch only where PyTorch can serve Clef.
- Pass the server key through a 0600 --api-key-file under the auth
  directory and give each server its own log file; both are removed on
  close, the log kept when the server exited by itself.

* Reload a re-exported Clef GGUF and keep a CPU decision server during training

Key the native target of a local Clef folder on its served GGUF files, so a
re-export replaces a resident llama-server instead of serving the old weights.
Evict only a GPU-resident Clef when a request waits for a training run, so a
llama.cpp server on CPU keeps serving.

* Keep a decision GGUF export listed when publishing fails, and pass the load credential to adapter merges

* Trim comments in the decision-from-LM code and tests

* Trim comments in the LLM decision model training code and tests

* Trim comments in the decision GGUF export and native serving tests

* Serve ggml-org's GGUF-only decision models through llama.cpp

Add Kev 0.8B/4B/9B, lev, Bespoke Nimble 9B v3, OpenJev, Laya GGUF and
Julia-1 to the Decision API catalog as gguf-layout entries whose only
backend is llama.cpp, pinned to their current ggml-org commits. A forced
PyTorch runtime answers 400, a missing or decision-less llama-server 503.
Their answers are llama.cpp's own, checked and passed through, since the
Clef formatter is Clef's reference only. A pinned GGUF also counts as
cached when another snapshot holds the same LFS blob, so a settings
download of main serves the pinned file.

* Trim comments in the GGUF-only Decision API entries

* Scope the Laya and Clef availability checks to the PyTorch catalog entries

* Fix decision-from-LM loading options, schema augmentation edge cases and mixture sizes

- 4-bit plus full finetuning no longer installs a bitsandbytes config
- revision, local_files_only and subfolder reach the plain LM load (CPU too)
- a renamed question never overwrites another; one-level scores get no threshold
- canonical_row copies before subsampling; the mixture returns n_rows exactly
- the training script sizes sources after unavailable ones drop out, decontaminates
  typed-decisions, and runs on CPU-only torch

* Fix Clef full finetuning checkpoints, adapter base revisions, GPT-2 style backbones and the decision toggle rollback

- reopening adapters with full_finetuning = True is refused instead of training only the head
- the base revision a plain LM loaded from is saved with the adapters and used on reload
- full finetuning checkpoints keep the exact head and restore through load_best_model_at_end
- backbones without .model (GPT-2) resolve their decoder through base_model
- a failed as_decision config request turns Train as decision model back off

* Bind decision adapter exports to the authorized base, pass the caller's token to the GGUF eligibility probe, and cap decoded image size

- an adapter folder whose two configs name different bases, or another base than the
  route authorized and scanned, is refused before anything loads
- the base config probe for an adapter-only Clef uses the load's token and offline mode
- Decision API images over 4096 x 4096 pixels are refused before they reach llama.cpp

* Drop a stray assertion left by the merge in the from-LM tests

---------

Co-authored-by: Nilay Yadav <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Etherl <[email protected]>
@danielhanchen danielhanchen self-assigned this Oct 11, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Thank you for the PR and for all the work on native Clef decisions, @wasimysaid!

We are going to close this one because it has been superseded on main:

If you think something from this PR is still missing on main, for example pinning a scoped download to an immutable revision, please open a small focused PR for that piece against current main and we will gladly review it. Thanks again for the contribution!

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.

3 participants