Skip to content

Studio: train decision models built on Qwen, Llama and Gemma - #12796

Closed
NilayYadav wants to merge 6 commits into
unslothai:mainfrom
NilayYadav:train-decision-models-from-llms
Closed

NilayYadav wants to merge 6 commits into
unslothai:mainfrom
NilayYadav:train-decision-models-from-llms

Conversation

@NilayYadav

Copy link
Copy Markdown
Collaborator

Builds on #12585. Draft until that merges and this is rebased on it. The first commit here is #12585's; the last 5 are new.

Adds training decision models from LLMs like Qwen3.5, Llama and Gemma 4, in Python and on the Studio Train page, and serving them from the Decision API.

model, tokenizer = FastDecisionModel.from_pretrained("unsloth/Qwen3.5-4B", load_in_4bit = True)
model = FastDecisionModel.get_peft_model(model, r = 16, lora_alpha = 16)
items, report = FastDecisionModel.build_dataset(dataset, tokenizer, model)
DecisionTrainer(model = model, processing_class = tokenizer, train_dataset = items, args = args).train()
FastDecisionModel.predict(model, tokenizer, state, questions)

The LLM reads the input, the question and each option, and a small head picks the answer. Training, calibration and the dataset format are the same as Laya's. In Studio, set Train as to Decision model on any text or vision LLM.

Results on typed-decisions (one L4):

Model Accuracy VRAM
Qwen3.5-4B 81% 5.5GB
Llama 3.2 3B 79% 4.1GB
Gemma 4 E4B 77% 14.4GB
Laya 77% 2.5GB

52% less VRAM and 3.4x faster than plain Hugging Face 4-bit training.

Notebook: unslothai/notebooks#380

@NilayYadav NilayYadav changed the title Train your own decision models from any LLM Studio: train decision models built on Qwen, Llama and Gemma Oct 6, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Most of the red checks here come from this PR. Two do not:

From this PR:

  1. Source lint, workflow-trigger lint and Repo tests (CPU, rest) all fail on the risky-loader gate: unsloth/models/decision.py:75 loads a module with importlib.util.spec_from_file_location, which is not in scripts/risky_loaders_baseline.json. Either import it by a written-out module name, or, if the path is trusted, run python scripts/lint_risky_loaders.py --update and replace the new entry's "REVIEW ME" reason with why it is safe.
  2. Repo tests (CPU, studio) fails tests/python/test_accelerator_skip_guards.py::test_no_test_lets_a_loader_infer_the_device_from_a_spoofed_probe at test_decision_model.py:674: PeftModel.from_pretrained() is called with no torch_device=. The CPU runners spoof the CUDA probe process-wide, so PEFT would pick a CUDA device that is not there. Pass the device explicitly, for example torch_device = "cuda" if has_real_accelerator() else "cpu" as the guard's message suggests.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 7, 2026
…th FastDecisionModel.predict and adapter saves (unslothai#12876)

* 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

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

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

* 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

* 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 added a commit to danielhanchen/unsloth-staging-review that referenced this pull request Oct 7, 2026
… GGUF (#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/unsloth#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/unsloth#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 #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]>
@NilayYadav NilayYadav closed this Oct 10, 2026
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.

2 participants