Repository navigation
Train any text or vision LLM as a Clef decision model from Studio, with FastDecisionModel.predict and adapter saves - #12876
Conversation
…memory test on a real CUDA device
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.
… on CPU when causal_conv1d is installed
…les, honour a cancel during calibration
# Conflicts: # studio/backend/core/training/worker.py
…ure into its head
…-op accumulation wrapper
|
This PR is based on
|
|
@codex review |
There was a problem hiding this comment.
💡 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".
| if kwargs.get("decision_head") is None and _is_plain_lm( | ||
| model_name, subfolder, token, revision, local_files_only | ||
| ): | ||
| kwargs["decision_head"] = "clef" |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| backbone = PeftModel.from_pretrained( | ||
| backbone, str(folder), is_trainable = not full_finetuning | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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") |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Fixed in a35f141: the base revision is kept in the decision config and the adapter config, and reloads use it.
| 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); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| # 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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)) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
|
@codex review |
1 similar comment
|
@codex review |
# Conflicts: # tests/test_decision_from_lm.py # tests/test_decision_model.py # unsloth/models/decision.py # unsloth/models/decision_from_lm.py
…, 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
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_pretrainedon a model that is neither a Laya nor a Clef checkpoint now attaches a fresh Clef joint schema head by default, with nodecision_headargument. This default path loads the backbone through_pin_device_maplike every other Clef load, so it stays on one device unless the caller passes adevice_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_pretrainedon a LoRA Clef model writes only the adapters, the joint head and the configs;from_pretrainedputs them back on the base model.save_pretrained_mergedstays the Cloudflare compatible Clef layout.DecisionTrainercheckpoints a Clef model as adapters plus its float32 head and resumes from them.UNSLOTH_CLEF_COMPILE=1compiles 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.predict, calibration and Studio serving withfloat != c10::Half.build_datasetreports how many inputs were cut atmax_seq_length, and merged saves no longer copy the download cache (.cache/huggingface) into the output folder.Studio
decision_layout: "llm") using its own recipe (llm_decision_defaults.yaml) and QLoRA. The model config route answersas_decision: truefor text and vision LLMs.Credit to #12796
The
predict()API, the adapter plus head save, and the Studio Train page flow (the decision choice, the recipe, the backendas_decisionanswer) 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):
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
Tests
NVIDIA B200, torch 2.13.0+cu130, transformers 5.17.0.
test_decision_model.py,test_decision_from_lm.py,test_decision_clef_head.py,test_decision_datasets.pyin one processtest_decision_serving.py,test_decision_training.py,test_decision_training_route.pynode --test tests/*decision*.test.tsnpm run typecheckcleanOn an A100 the tiny Qwen3.5 case of
test_decision_from_lm.pyhits 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.