Skip to content

Serve decision models through llama.cpp in Studio, and export them to GGUF - #12939

Merged
danielhanchen merged 136 commits into
mainfrom
decision-llamacpp
Oct 7, 2026
Merged

danielhanchen merged 136 commits into
mainfrom
decision-llamacpp

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

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

  1. Studio serves decision models through its bundled llama.cpp. Unsloth's unslothai/llama.cpp prebuilts (b11443-mix-*) already include upstream Clef text, Clef vision (mmproj) and Laya support behind /v1/systemone. The Decision API now starts a private llama-server for a Clef model when a GGUF is available and the binary reports decisions in /v1/models.
    • Backend setting: Auto (default), llama.cpp, PyTorch. Auto uses llama.cpp when the model has a current GGUF and the binary supports it, otherwise the existing PyTorch path.
    • Auto stays on PyTorch when another model owns the GPU or when only the PyTorch checkpoint is downloaded, so existing setups see no new download and no new GPU conflict.
    • Images are served by llama.cpp only (the PyTorch Clef path is text-only). PNG and JPEG are decode-checked before dispatch; an unreadable image is a 422, never a server restart.
    • A state longer than the llama.cpp context returns a clear 422 with the token limit; under Auto it is retried on PyTorch where PyTorch can serve Clef.
    • Same answer envelope on both backends (confidence, score, legend, noul are rebuilt with the PyTorch formatter). Every response carries x-unsloth-decision-backend.
    • The server joins Studio's GPU arbiter (training, chat, image and video loads evict or wait on it like any other owner), unloads after 5 minutes idle, takes its API key from a 0600 file, and logs per server.
    • Built-in clef-flash / clef entries gain pinned GGUF companions (ggml-org/Clef-Flash-GGUF, ggml-org/Clef-GGUF, Q8_0 + mmproj).
    • Every other decision GGUF ggml-org publishes becomes a llama.cpp-only Decision API entry: Kev 0.8B / 4B / 9B, lev, Bespoke-Nimble 9B v3, OpenJev 27B (images), Laya-GGUF and Julia-1. Each is pinned to a revision with file hashes; under the PyTorch runtime they answer a clear 400 naming the runtime to pick. Their answers are llama.cpp's own, validated against the request (the Clef formatter only applies to Clef).
    • A Settings download fetches the repo's main; serving resolves the pinned revision and, offline, accepts a cached copy only when its blob hash equals the pinned file.
  2. Decision fine-tunes export to GGUF with calibration intact.
    • Library: model.save_pretrained_gguf(dir, tokenizer, quantization_method = "q8_0" | "bf16" | "f16" | "q4_k_m" | [...]) and push_to_hub_gguf for Clef (Qwen3.5 backbones) and Laya.
    • The upstream converter drops Unsloth's per-question-type and per-option-count temperatures, and an unfolded head temperature. The export writes the temperatures PyTorch actually serves into clef.decision.temperature.* / Laya keys and verifies them after quantization; for Laya it also writes the served head length.
    • Output is <run>/gguf/{model-<Q>.gguf, mmproj-<Q>.gguf, export.json}. export.json records 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.
    • Studio Export page: decision runs (Clef and Laya) are listed, export to GGUF with quant choice, and the run is immediately usable in the Decision API.

Parity (B200, Unsloth prebuilt b11443-mix-d65395f, linux-x64-cuda13-newer)

Case Quant Max prob diff vs FastDecisionModel.predict Same answers
Stock Clef-Flash, text + image + 10k-token state, -ub 16384 Q8_0 0.0057 all
Calibrated Clef fine-tune, exported by this PR Q8_0 0.0018 all
Same, temperature written at the 0.25 floor BF16 0.0105 all
Same file with the temperature keys removed (negative control) BF16 0.252 no
Sharply calibrated Clef-Flash fine-tune (score temperature 0.52), via Studio Q8_0 0.045 8/8
Same model BF16 0.0047 8/8
Laya fine-tune F16 / Q8_0 0.0015 / 0.0031 all
Stock Clef-Flash Q4_K_M 0.137 6/8

Q8_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 -ub 8192 / 16384 / 32768: +1.8 / +3.9 / +8.8 GB. The context (default 16384) is a setting.

End to end

Fresh ./install.sh --local of 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 with x-unsloth-decision-backend: llama.cpp. After recalibrating the run, the export is reported stale and Auto serves PyTorch, matching predict exactly.

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.
  • Frontend: strict i18n parity across all 12 locales, typecheck.
  • Current run: Studio decision suites 304+ passed; library GGUF tests 35 passed; test differential vs the merge base: 163 FIXED, 0 HEAD_FAIL.

Not covered

  • Native serving for decision models on non-Qwen3.5 backbones (served by PyTorch; GGUF export refuses with a message).
  • Laya is exported to GGUF, but Studio keeps serving Laya on PyTorch.
  • Only B200 / Linux was run end to end. Other NVIDIA generations, AMD, macOS and Windows prebuilts were not exercised with decision models.
  • Kev 4B / 9B, lev, Nimble and OpenJev were exercised on a bare llama-server from the prebuilt (all 200, sensible answers) but not through Studio's route; Kev 0.8B, Laya-GGUF and Julia-1 were, and match the bare server exactly.
  • The CPU prebuilt needs --no-repack on AMX CPUs (passed automatically); CPU latency for a 16k-token state against the 300 s request timeout was not measured.

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
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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security 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: 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".

Comment on lines +34 to +36
FINGERPRINT_FILES = {
"clef": ("unsloth_decision_config.json", "joint_head_config.json", "joint_head.safetensors"),
"laya": ("rl_agent_config.json", "model.safetensors"),

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 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 👍 / 👎.

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 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.

Comment on lines +99 to +102
try:
from huggingface_hub import hf_hub_download
return _read_json(Path(hf_hub_download(base, "config.json")))
except Exception:

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 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 👍 / 👎.

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 be66cdf: the base config probe takes the load's token and local_files_only, threaded from Studio's load and the export worker.

Comment on lines +220 to +224
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()

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 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 👍 / 👎.

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 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

@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 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.

Comment on lines +779 to +781
return self._load_decision_checkpoint(
str(Path(checkpoint_path).expanduser()), *decision, token = token
)

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 Security Review

P2 Badge 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 👍 / 👎.

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 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
@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-llm-studio to main October 7, 2026 12:52
# 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

@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

class SystemOneDownloadPlan(BaseModel):
repo: Optional[str] = None
files: list[str]
size_bytes: int
cached: bool
error: Optional[str] = None

P2 Badge Download the pinned GGUF revision

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".

Comment on lines +303 to +306
def _select_gguf(checkpoint: Checkpoint, questions, preference: str) -> Checkpoint:
from .native_worker import request_gap

if preference == "pytorch":

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 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 👍 / 👎.

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 #12949 (ccf40aa).

Comment on lines +98 to +102
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"

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 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 👍 / 👎.

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 #12949 (ccf40aa).

Comment on lines +264 to +265
if len(free) == len(devices):
return devices[max(range(len(free)), key = lambda i: free[i][1])]

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 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 👍 / 👎.

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 #12949 (ccf40aa).

Comment on lines +364 to +365
const runtimeChoice =
isClefDecisionModel(settings.model) || !!current?.llamaCppOnly;

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 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 👍 / 👎.

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 #12949 (ccf40aa).

Comment on lines +1737 to +1739
target, reason = select(checkpoint, images, questions)
if checkpoint.layout != "laya":
_fallback_reason = reason

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 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 👍 / 👎.

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 #12949 (ccf40aa).

@danielhanchen
danielhanchen merged commit 15f715a into main Oct 7, 2026
@danielhanchen
danielhanchen deleted the decision-llamacpp branch October 7, 2026 13:00
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
danielhanchen added a commit that referenced this pull request Oct 7, 2026
…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.
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