Skip to content

Train any text or vision LLM as a Clef decision model from Studio, with FastDecisionModel.predict and adapter saves - #12876

Merged
danielhanchen merged 101 commits into
mainfrom
decision-llm-studio
Oct 7, 2026
Merged

danielhanchen merged 101 commits into
mainfrom
decision-llm-studio

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

Stacked on #12772 (decision models from a plain language model), which builds on #12585; the base branch is #12772's, so the diff here is only the new work.

This PR makes any text or vision LLM trainable as a Clef style decision model from Unsloth Studio, adds FastDecisionModel.predict, and adds a small adapter plus head save next to the existing merged Clef save.

What it adds

Library

  • FastDecisionModel.from_pretrained on a model that is neither a Laya nor a Clef checkpoint now attaches a fresh Clef joint schema head by default, with no decision_head argument. This default path loads the backbone through _pin_device_map like every other Clef load, so it stays on one device unless the caller passes a device_map.
  • FastDecisionModel.predict(model, tokenizer, state, questions) answers one Decision API request for Laya, Clef and converted LLMs at the calibrated temperatures. Each answer is the Decision API answer (choice and confidence, score and legend, or noul) plus "answer" (the option, True or False for noul, the level for score) and "probabilities" over every option. For Clef it reads states up to 16,384 tokens, the same as Studio's Decision API, and it flags a prompt as truncated only when the state was actually cut (an exact fit is not truncated). Studio's Clef runtime now answers through the same function.
  • save_pretrained on a LoRA Clef model 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 Clef layout. DecisionTrainer checkpoints a Clef model as adapters plus its float32 head and resumes from them.
  • The Clef head runs eagerly by default; UNSLOTH_CLEF_COMPILE=1 compiles it. On Qwen3.5-2B (25 steps, every arm on the same card, 0 graph breaks) compiling never paid off: L4 2.94 vs 2.99 s/step, A100 0.785 vs 0.779, RTX PRO 6000 0.481 vs 0.488, T4 10.30 vs 10.42, for 7 to 18 minutes of compile in every process even with a warm cache.
  • Clef inference autocasts fp16 on GPUs without bf16 (T4), as it trains there. A plain LLM loaded in fp16 on a T4 kept float32 norms and failed in predict, calibration and Studio serving with float != c10::Half.
  • build_dataset reports how many inputs were cut at max_seq_length, and merged saves no longer copy the download cache (.cache/huggingface) into the output folder.

Studio

  • A decision run on a model that is not a Laya or Clef checkpoint trains the LLM with a fresh Clef head (decision_layout: "llm") using its own recipe (llm_decision_defaults.yaml) and QLoRA. The model config route answers as_decision: true for text and vision LLMs.
  • The Train page gets a "Train as Decision model" choice for text and vision LLMs. It applies the LLM decision recipe, keeps QLoRA and the recipe's context length, and is hidden for Laya, Clef, audio and embedding models.
  • The finished run is a Clef folder, so the existing Clef runtime serves it through the Decision API. The runtime also serves adapter plus head folders on their base model.

Credit to #12796

The predict() API, the adapter plus head save, and the Studio Train page flow (the decision choice, the recipe, the backend as_decision answer) come from @NilayYadav's #12796, ported onto the Clef joint schema head. Thank you!

What was not taken is #12796's per-question decision head (one backbone row per question, followed by a 2-layer transformer head over every token). We ran both heads with the same data, backbone and LoRA settings (LocalLLaMA/typed-decisions, 5,600 training decisions, 2,000 test decisions, QLoRA r16, 3 epochs, 2 seeds per arm, B200):

Qwen3.5-2B #12796 per-question head Clef joint schema head
Test accuracy 79.2% 78.7%
Paired accuracy difference (seed 3407), 95% CI +1.1 pt [-0.45, +2.55]
ECE after its own calibration 0.152 0.026
NLL of gold 0.571 0.480
Backbone tokens, 3 epochs 4.94 M 2.94 M
Inference, 4 questions over a ~8k token state 304 to 430 ms, +2.78 GB 123 to 125 ms, +0.69 GB

On Qwen3.5-4B accuracy was 80.9% vs 79.9% (paired +0.35 pt, CI [-1.0, +1.65]) and ECE 0.167 vs 0.037. Accuracy is a tie on both sizes. The Clef head reads the state once per record instead of once per question, so it processes about 40% fewer backbone tokens in training and stays flat in latency and memory as questions and state length grow, while the per-question head grows with questions times state length and by default truncates states beyond about 1.5k tokens. The Clef head also saves in Cloudflare's Clef layout, which their own loader reads. Most of the calibration gap came from #12796's soft-target calibrator rather than its head (rescored with the hard-label calibrator its ECE drops to 0.046), so the head choice rests on cost and format, not accuracy.

Usage

from unsloth import FastDecisionModel, DecisionTrainer

model, tokenizer = FastDecisionModel.from_pretrained("unsloth/Qwen3.5-2B", max_seq_length = 4096, load_in_4bit = True)
model = FastDecisionModel.get_peft_model(model, r = 16, lora_alpha = 16)
items, report = FastDecisionModel.build_dataset(dataset, tokenizer, model)
train, held = FastDecisionModel.split_holdout(items)
DecisionTrainer(model = model, processing_class = tokenizer, train_dataset = train, args = args).train()
FastDecisionModel.calibrate(model, tokenizer, held)

FastDecisionModel.predict(model, tokenizer, state, questions)
model.save_pretrained("decision_adapters")               # adapters + head
model.save_pretrained_merged("decision_model_16bit")     # Cloudflare Clef layout

Tests

NVIDIA B200, torch 2.13.0+cu130, transformers 5.17.0.

Suite Result
GPU, test_decision_model.py, test_decision_from_lm.py, test_decision_clef_head.py, test_decision_datasets.py in one process 99 passed
CPU, the same four files 86 passed, 12 skipped
Studio test_decision_serving.py, test_decision_training.py, test_decision_training_route.py 114 passed, 1 skipped (tensorboard not installed)
Frontend node --test tests/*decision*.test.ts 39 passed; npm run typecheck clean
Colab T4 and Kaggle T4 x2, decision library tests 4 of 4 passed

On an A100 the tiny Qwen3.5 case of test_decision_from_lm.py hits a Triton shared memory limit in the fla gated delta rule kernel (180,744 bytes needed, 166,912 available), which comes from main's fla autotuner path, not from this PR.

Live checks (before the #12772 merge): Studio trained unsloth/Qwen3.5-0.8B (a vision LLM) as a decision model from the Train page through the API, saved a Clef folder, and served it through the Decision API with sensible answers (job completed in 3 minutes, Decision API 200). The unslothai/notebooks#380 call sequence ran unchanged on a GPU through training, calibration, predict and the merged save.

NilayYadav and others added 30 commits October 3, 2026 04:15
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.
# Conflicts:
#	studio/backend/core/training/worker.py
@danielhanchen

Copy link
Copy Markdown
Member Author

This PR is based on decision-models-from-lm, not main, so its checks run against that branch:

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 7, 2026
@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: 684807d864

ℹ️ 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 +1751 to +1754
if kwargs.get("decision_head") is None and _is_plain_lm(
model_name, subfolder, token, revision, local_files_only
):
kwargs["decision_head"] = "clef"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Gate automatic conversion on a compatible backbone

Any plain checkpoint is now automatically routed through the Clef wrapper, but ClefDecisionModel.forward unconditionally accesses backbone.model (and optionally .language_model). Common valid causal-LM classes such as GPT2LMHeadModel expose .transformer instead, so FastDecisionModel.from_pretrained("gpt2") can construct successfully and then fail on the first evaluation, prediction, or training forward. Restrict this auto-conversion to supported backbone layouts or resolve the model's decoder through an architecture-independent interface.

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 a35f141: the decoder resolves through base_model when the backbone has no .model (GPT-2). A tiny GPT-2 now predicts end to end, and Llama 3.2, Gemma 3/4, Phi-4-mini and Mistral convert, train and predict.

Comment thread unsloth/models/decision.py Outdated
Comment on lines +936 to +938
backbone = PeftModel.from_pretrained(
backbone, str(folder), is_trainable = not full_finetuning
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Make full fine-tuning unfreeze adapter checkpoints

When a saved Clef adapter is reopened with full_finetuning=True, this passes is_trainable=False to PEFT. PEFT freezes the base when attaching LoRA and this flag also freezes the adapter, leaving only the decision head trainable; the run is nevertheless marked and reported as full fine-tuning. This silently changes the requested experiment into head-only training, so the adapter must be merged/unloaded and the base unfrozen, or this mode must be rejected for adapter checkpoints.

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 a35f141: full_finetuning on an adapter folder is refused with a pointer to save_pretrained_merged instead of silently training only the head.

Comment on lines +1169 to +1172
if config.get("base_model"):
adapter = json.loads(adapter_config.read_text(encoding = "utf-8"))
adapter["base_model_name_or_path"] = config["base_model"]
adapter_config.write_text(json.dumps(adapter, indent = 2), encoding = "utf-8")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve the pinned base revision in adapter saves

When the original language model was loaded with a non-default revision, the saved decision configuration records only the repository name, and this rewrite likewise sets only base_model_name_or_path. Reloading the adapter therefore resolves the repository's current default revision rather than the exact weights on which the head and LoRA were trained; after the branch moves this can silently change predictions or fail with incompatible tensor shapes. Persist the requested base revision in the adapter metadata and use it when reloading.

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 a35f141: the base revision is kept in the decision config and the adapter config, and reloads use it.

Comment on lines +1232 to +1237
setTrainAsDecision: (trainAsDecision) => {
if (get().trainAsDecision === trainAsDecision) return;
set({ trainAsDecision });
const { selectedModel } = get();
// Reloading the model's defaults switches the whole recipe, as picking a Laya model does.
if (selectedModel) void loadAndApplyModelDefaults(selectedModel);

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 Roll back the decision toggle when its config request fails

If the as_decision model-config request fails, this eagerly updated flag remains true while the catch path leaves modelType as text or vision. Readiness only blocks a config error when modelType === "decision", so the UI can still enable Start while showing “Decision model”; the payload then has is_decision: false and starts an ordinary language-model run. Restore the previous toggle state on request failure or include trainAsDecision in the readiness failure condition.

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 a35f141: a failed as_decision request turns Train as decision model back off, so the run cannot start as a plain LM under the decision label.

Comment on lines +2006 to +2007
# Over max_seq_length the end of the state is cut, never questions or options.
report["truncated"] = sum(len(item["input_ids"]) >= max_len for item in items)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge Distinguish exact-length inputs from truncated inputs

An encoded input can legitimately be exactly max_len tokens without any state being removed, but every such input is counted as truncated here and triggers the warning that its state was cut. This produces false truncation reports for boundary-sized training examples; use the same one-extra-token check used by _clef_truncated (or otherwise track whether build_sequence actually truncated) before incrementing the count.

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 only affects the count in an advisory warning, and an input exactly at max_seq_length is the boundary where a cut is most likely; nothing trains or serves differently.

Comment on lines +1439 to +1442
def _load_best_model(self):
if not getattr(self.model, "is_clef", False):
return super()._load_best_model()
_load_clef_checkpoint(self.model, Path(self.state.best_model_checkpoint))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reload full Clef checkpoints without the LoRA-only loader

For a full-finetuning Clef run, _save writes a merged checkpoint because the encoder has no peft_config, but load_best_model_at_end=True routes that checkpoint into _load_clef_checkpoint, which explicitly rejects every model without peft_config. Consequently an otherwise successful full-finetuning experiment crashes when Trainer tries to restore its best checkpoint; the same mismatch also prevents resuming these generated full checkpoints. Add a merged-checkpoint restore path or avoid advertising/saving resumable full checkpoints.

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 a35f141: full finetuning checkpoints keep the exact head and restore their merged weights, so load_best_model_at_end and resume work.

…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
…tyle 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
# Conflicts:
#	tests/test_decision_from_lm.py
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

Base automatically changed from decision-models-from-lm to main October 7, 2026 12:50
# Conflicts:
#	tests/test_decision_from_lm.py
#	tests/test_decision_model.py
#	unsloth/models/decision.py
#	unsloth/models/decision_from_lm.py
@danielhanchen
danielhanchen merged commit 4451666 into main Oct 7, 2026
@danielhanchen
danielhanchen deleted the decision-llm-studio branch October 7, 2026 12:52
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 7, 2026
…, unslothai#12939 (unslothai#12949)

* Decision models: follow-up fixes for mixture weights, offline head download, GGUF-only no-torch serving and GPU order

* Keep Vulkan device order and reject non-finite mixture weights

* Follow HIP visibility order for ROCm and keep the Clef fallback reason until Laya serves

* Report the fallback reason only for a resident Clef, and describe the Qwen3.5 precision path without a weight dtype

* Resolve UUID masks when choosing a GPU and detect GPUs through llama.cpp on no-torch installs

* Let ROCm fall back to CUDA_VISIBLE_DEVICES when choosing a GPU

* Skip the shebang llama-server stub tests on Windows

* Ask llama-server for its GPUs on no-torch installs, cached, and fix the idle unload test race

* Key the no-torch GPU probe cache by llama-server path and mtime

* Use a standalone ROCR_VISIBLE_DEVICES mask as the ROCm device order
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