Repository navigation
Serve decision models through llama.cpp in Studio, and export them to GGUF - #12939
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
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.
|
@codex review |
|
@codex security review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5f125427f9
ℹ️ 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".
| FINGERPRINT_FILES = { | ||
| "clef": ("unsloth_decision_config.json", "joint_head_config.json", "joint_head.safetensors"), | ||
| "laya": ("rl_agent_config.json", "model.safetensors"), |
There was a problem hiding this comment.
Include all trained Clef weights in the export fingerprint
For Clef exports this fingerprint covers only the decision config and joint head, omitting both merged backbone shards (model*.safetensors) and adapter weights (adapter_model.safetensors). If the backbone or LoRA is retrained while the head remains unchanged, served_files() still considers the old GGUF current, so Studio silently serves predictions from stale weights instead of falling back to PyTorch or requiring a re-export.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing the fingerprint: every save writes the joint head and the decision config again (a trained head never stays byte-identical, and Studio records each run in the config), so a retrain or recalibration already changes it. Adding the adapter or merged shards would also make save_pretrained then save_pretrained_gguf on one folder always stale, since the adapter folder and the merged export hold different files.
| try: | ||
| from huggingface_hub import hf_hub_download | ||
| return _read_json(Path(hf_hub_download(base, "config.json"))) | ||
| except Exception: |
There was a problem hiding this comment.
Pass the export credential to the base-config probe
When exporting an adapter whose base is private or gated and not already cached, this eligibility probe downloads config.json without the hf_token supplied to load_checkpoint; consequently the load fails as ineligible before FastDecisionModel.from_pretrained can use the valid caller credential. It can also consult an ambient token when the caller explicitly requested anonymous access, so the token and local_files_only policy need to be threaded through this probe.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in be66cdf: the base config probe takes the load's token and local_files_only, threaded from Studio's load and the export worker.
| with Image.open(BytesIO(raw)) as image: | ||
| # By content, as stb_image reads it: a mislabelled JPEG still decodes. | ||
| if image.format not in _IMAGE_TYPES.values(): | ||
| return False | ||
| image.verify() |
There was a problem hiding this comment.
Reject images with excessive decoded dimensions
The request limits only the compressed byte count, while Image.verify() checks file integrity without imposing a pixel or decoded-memory limit; Pillow's decompression-bomb threshold also starts with a warning rather than an exception. A highly compressible PNG with roughly 100 million pixels can therefore fit well below 4 MiB, pass this check, and make llama.cpp's stb decoder allocate hundreds of megabytes, multiplied across the four allowed images, allowing a request to exhaust memory or kill the private server.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in be66cdf: images over 4096 x 4096 decoded pixels are refused with a 422 before they reach llama.cpp (an 8192 x 8192 PNG under 4 MiB is the regression test).
…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
There was a problem hiding this comment.
🛡️ Codex Security Review
Here are some automated security review suggestions for this pull request.
Reviewed commit: 5f125427f9
ℹ️ About Codex security reviews in GitHub
This is an experimental Codex feature. Security reviews are triggered when:
- You comment "@codex security review"
- A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review
Once complete, Codex will leave suggestions, or a comment if no findings are found.
| return self._load_decision_checkpoint( | ||
| str(Path(checkpoint_path).expanduser()), *decision, token = token | ||
| ) |
There was a problem hiding this comment.
🛡️ Codex Security Review
Security: Preserve the authorized decision-adapter base
On a multi-user CPU-only Studio, an authenticated managed account can craft a Clef adapter whose adapter_config.json names an allowed base while unsloth_decision_config.json names an owner's local model or an unscanned repository. The route authorizes and scans only the first base, but this new branch drops base_model; GGUF export later prefers the second and loads and merges it into the caller's writable project directory. Pass the authorized base through, reject mismatched metadata, and scan the exact resolved load target.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in be66cdf: an adapter export is refused before anything loads when its two configs name different bases, or when the base it would load is not the base the route authorized and scanned.
…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
…'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
# Conflicts: # unsloth/models/decision.py
|
@codex review |
1 similar comment
|
@codex review |
# Conflicts: # studio/backend/tests/test_decision_training.py # studio/frontend/src/i18n/locales/ar.ts # studio/frontend/src/i18n/locales/de.ts # studio/frontend/src/i18n/locales/en.ts # studio/frontend/src/i18n/locales/es.ts # studio/frontend/src/i18n/locales/fr.ts # studio/frontend/src/i18n/locales/hi.ts # studio/frontend/src/i18n/locales/it.ts # studio/frontend/src/i18n/locales/ja.ts # studio/frontend/src/i18n/locales/ko.ts # studio/frontend/src/i18n/locales/pt-br.ts # studio/frontend/src/i18n/locales/ru.ts # studio/frontend/src/i18n/locales/zh-CN.ts # unsloth/models/decision.py
There was a problem hiding this comment.
💡 Codex Review
unsloth/studio/backend/routes/settings.py
Lines 704 to 709 in 09fd2ac
For native catalog entries, download_plan() adds the immutable companion revision, but this response model has no revision field, so Pydantic drops it and the frontend download manager fetches the named files from main. Once a GGUF repository updates main, the download button retrieves different blobs that _cached_blob() rejects against the pinned hashes; the plan remains uncached and an offline user cannot serve the model they just downloaded. Preserve the revision through the API and download that commit rather than the moving branch.
ℹ️ 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".
| def _select_gguf(checkpoint: Checkpoint, questions, preference: str) -> Checkpoint: | ||
| from .native_worker import request_gap | ||
|
|
||
| if preference == "pytorch": |
There was a problem hiding this comment.
Allow GGUF-only models on no-torch installations
On an installation created with --no-torch, selecting or enabling any of these new GGUF-only models is rejected before this native path runs: systemone_settings.validate() still applies runtime_unavailable_reason() to every local model, and that function unconditionally reports missing PyTorch. This defeats the GGUF-only installation mode even though NativeClefAgent and llama.cpp do not require torch; scope that validation to PyTorch/Laya targets instead.
Useful? React with 👍 / 👎.
| def clef_device() -> str: | ||
| """Where a llama.cpp Clef runs: the chosen device, else the GPU when there is one (CPU needs ~22 GB RAM).""" | ||
| if device_locked() or _owner_setting(DEVICE_KEY) in DEVICES: | ||
| return get_device() | ||
| return "gpu" if gpu_available() else "cpu" |
There was a problem hiding this comment.
Report the device that native decisions actually use
On a fresh GPU installation with no systemone_device row, get_device() returns and exposes cpu to the settings UI, but this branch ignores that resolved value and makes every native GGUF server use the GPU. The UI therefore shows CPU while the first request claims GPU memory, and because CPU is already selected the user cannot explicitly choose it without first toggling to GPU. Represent the implicit choice as Auto or return the same effective device that clef_device() will use.
Useful? React with 👍 / 👎.
| if len(free) == len(devices): | ||
| return devices[max(range(len(free)), key = lambda i: free[i][1])] |
There was a problem hiding this comment.
Preserve visibility order when choosing the GPU
When CUDA_VISIBLE_DEVICES reorders multiple cards (for example 1,0), llama.cpp enumerates child-visible devices in that order, while _get_gpu_free_memory() returns rows sorted by physical index. Equal list lengths therefore do not prove positional alignment, and indexing devices by the maximum-free row can select the opposite physical GPU, potentially loading a large Clef model onto the smaller or busier card. Map the memory rows through the visibility order instead of pairing the two lists positionally.
Useful? React with 👍 / 👎.
| const runtimeChoice = | ||
| isClefDecisionModel(settings.model) || !!current?.llamaCppOnly; |
There was a problem hiding this comment.
Show runtime controls for environment-configured Clef
When UNSLOTH_SYSTEMONE_MODEL points to a local Clef checkpoint, the backend resolves it as the laya-local checkpoint with layout="clef", but that name is neither recognized by isClefDecisionModel() nor present in settings.models. Consequently runtimeChoice is false and the new Auto/llama.cpp/PyTorch selector is hidden, even though this checkpoint can have a local GGUF export and supports both runtimes. Base this decision on backend-provided layout/runtime capability rather than the catalog name alone.
Useful? React with 👍 / 👎.
| target, reason = select(checkpoint, images, questions) | ||
| if checkpoint.layout != "laya": | ||
| _fallback_reason = reason |
There was a problem hiding this comment.
Clear native fallback reasons when switching to Laya
After Auto falls back from a Clef GGUF to PyTorch, _fallback_reason is retained globally; switching settings to a Laya model unloads the agent but does not clear it, and Laya requests skip this assignment. Once Laya is loaded, _systemone_response() sees matching loaded_model and reports the stale Clef reason (for example, “The GGUF is not downloaded”) as Laya's current status indefinitely. Clear the reason on unload/model changes or assign it for every routed layout.
Useful? React with 👍 / 👎.
…, 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
…yUI merges (#12958) Each of these PRs was green on its own; the repo-wide guards they now trip landed or tightened alongside them. The risky-loader baseline and the parallel-isolation entry for the same merges are in #12954. - test_source_read_encoding: pass encoding="utf-8" in test_decision_gguf_real.py (#12939) and test_comfy_file_detection.py (#12878). - test_every_long_lived_spawner_consults_the_shutdown_latch: native_worker.py (#12939) gates before the spawn and rereads the latch in _wait_ready after adopt_pid, so it belongs in the guarded set. Add a test that pins the race it closes: a latch set during the spawn kills the new server and removes its key file. - test_export_owner_single_mode_preserves_operation_and_status_bytes: #12939 added the optional decision field to the export status response, null for any other model. The byte-for-byte expectation from #10588 now includes it.
Stacked on #12876 (base
decision-llm-studio). Builds on the native worker and media handling from #12770 by @wasimysaid, ported onto the #12876 runtime with fixes for image errors, GPU ownership and the Auto fallback.What this adds
unslothai/llama.cppprebuilts (b11443-mix-*) already include upstream Clef text, Clef vision (mmproj) and Laya support behind/v1/systemone. The Decision API now starts a privatellama-serverfor a Clef model when a GGUF is available and the binary reportsdecisionsin/v1/models.x-unsloth-decision-backend.clef-flash/clefentries gain pinned GGUF companions (ggml-org/Clef-Flash-GGUF,ggml-org/Clef-GGUF, Q8_0 + mmproj).main; serving resolves the pinned revision and, offline, accepts a cached copy only when its blob hash equals the pinned file.model.save_pretrained_gguf(dir, tokenizer, quantization_method = "q8_0" | "bf16" | "f16" | "q4_k_m" | [...])andpush_to_hub_gguffor Clef (Qwen3.5 backbones) and Laya.clef.decision.temperature.*/ Laya keys and verifies them after quantization; for Laya it also writes the served head length.<run>/gguf/{model-<Q>.gguf, mmproj-<Q>.gguf, export.json}.export.jsonrecords a fingerprint of the files the served probabilities depend on, so retraining or recalibrating makes an old export stale; Studio then ignores it and serves PyTorch.Parity (B200, Unsloth prebuilt
b11443-mix-d65395f,linux-x64-cuda13-newer)FastDecisionModel.predict-ub 16384Q8_0 is the default. Strongly calibrated models amplify rounding, so BF16 or F16 is the choice when tight parity matters; Q4_K_M is offered but not recommended for Clef.
Extra VRAM over the weights for the llama.cpp server at
-ub8192 / 16384 / 32768: +1.8 / +3.9 / +8.8 GB. The context (default 16384) is a setting.End to end
Fresh
./install.sh --localof this branch in Chromium: fine-tuned and calibrated Clef-Flash run listed on the Export page, Q8_0 export from the UI, selected in Settings > Decision API (Auto shows "Runtime: llama.cpp, reads text and images"), text and image requests answered withx-unsloth-decision-backend: llama.cpp. After recalibrating the run, the export is reported stale and Auto serves PyTorch, matchingpredictexactly.Tests
tests/test_decision_gguf.py(temperature writer, buckets, folded and unfolded head, idempotence, eligibility, stale source, cleanup on cancel, old llama.cpp refusal);tests/test_decision_gguf_real.py(GPU, real converter and server).studio/backend/tests/test_decision_native.py,test_decision_native_gpu.py(stub and real llama-server: routing table, forced modes, flags, capability detection, error mapping, idle unload, GPU claims, image handling),test_systemone.py,test_export_decision_backend.py,test_export_decision_routes.py,test_decision_training.py.Not covered
--no-repackon AMX CPUs (passed automatically); CPU latency for a 16k-token state against the 300 s request timeout was not measured.