Compare commits

..
Author SHA1 Message Date
grenadeandClaude Opus 5 bf1e80ed55 fix(qwen4_exp): 640 is not a whole number of k-quant blocks
CI / Config consistency (push) Successful in 11s
CI / Classify changes (push) Successful in 23s
CI / Format (push) Successful in 12s
CI / Clippy (push) Successful in 2m37s
CI / Test (push) Successful in 7m2s
CI / CUDA type-check (push) Successful in 19m17s
CI / Web (lint + typecheck + i18n + build) (push) Has been skipped
CI / Build cortex SRPM (push) Has been skipped
CI / Build neuron SRPM (push) Has been skipped
CI / Publish cortex to COPR (push) Has been skipped
CI / Publish neuron to COPR (push) Has been skipped
CI / Bump version in source (push) Has been skipped
The first real cold load on beast got through routing, resolved all
131 shards, parsed the config, reached decoder layer 0 — and died
there:

    quantize experts to Q4K: quantized tensor must have their last dim
    divisible by block size [2560, 640] 256

ggml quantises along the last dimension and a row must be a whole
number of blocks. `gate_up` reduces over `hidden_size` = 2560, which
is ten blocks of 256. `down_proj` reduces over `moe_intermediate_size`
= 640, which is two and a half. So `quant = "q4k"` could never have
loaded this model, on any card, whatever else was fixed first.

It is not an orientation mistake — `[2560, 640]` is the `[out, in]`
layout a `QMatMul` wants, and 640 is genuinely the reduction. The
constraint is the number itself. llama.cpp meets the same wall and
answers it the same way: substitute a 32-block type for the row that
will not divide. Q4_0 and Q4K are both 4.5 bpw, so the memory
arithmetic every placement decision rests on is unchanged; the trade
is quality, on one of the three expert matrices, against not loading
at all. A row that divides neither 256 nor 32 is an error, because
silently leaving those weights dense would be a memory surprise rather
than a mercy.

The substitution is decided once per layer from the shapes rather than
per expert -- 512 identical lines a layer would bury the one fact
worth reading.

The test uses the checkpoint's own widths, 2560 and 640, scaled down
only in expert count. The fixture that missed this was 256 in both
dimensions -- the narrowest a k-quant accepts -- so every row divided
and the two halves were indistinguishable. A test whose fixture cannot
express the failure is not evidence about it.

Refs #307, #315, #320.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015v1FQqShiRp9rrJEEcgNER
2026-09-06 20:59:39 +03:00
grenade a14d1af447 Merge branch 'fix/qwen4-exp-load-reporting-and-pool-trim'
build-prerelease / Resolve version stamps + change detection (push) Successful in 21s
build-prerelease / Lint (fmt + clippy) (push) Successful in 2m43s
build-prerelease / Build cortex binary (push) Has been skipped
build-prerelease / Package cortex RPM (push) Has been skipped
build-prerelease / Build helexa-bench binary (push) Has been skipped
build-prerelease / Build helexa-upstream binary (push) Has been skipped
build-prerelease / Build helexa-angels binary (push) Has been skipped
build-prerelease / Package helexa-bench RPM (push) Has been skipped
build-prerelease / Package helexa-upstream RPM (push) Has been skipped
build-prerelease / Build helexa-router binary (push) Has been skipped
build-prerelease / Build helexa-tools binary (push) Has been skipped
build-prerelease / Package helexa-angels RPM (push) Has been skipped
build-prerelease / Package helexa-router RPM (push) Has been skipped
build-prerelease / Package helexa-tools RPM (push) Has been skipped
build-prerelease / Build neuron-ada (push) Successful in 2m35s
build-prerelease / Build neuron-ampere (push) Successful in 2m36s
build-prerelease / Test (push) Successful in 10m54s
build-prerelease / Build neuron-blackwell (push) Successful in 14m28s
build-prerelease / Package helexa-neuron-ampere RPM (push) Successful in 1m7s
build-prerelease / Package helexa-neuron-ada RPM (push) Successful in 1m16s
build-prerelease / Package helexa-neuron-blackwell RPM (push) Successful in 4m8s
build-prerelease / Publish to rpm.lair.cafe (unstable) (push) Successful in 30s
2026-09-06 19:58:00 +03:00
grenadeandClaude Opus 5 f1af926c30 fix(qwen4_exp): route the arch on the path that actually loads it
CI / Config consistency (push) Successful in 12s
CI / Classify changes (push) Successful in 27s
CI / Web (lint + typecheck + i18n + build) (push) Has been skipped
CI / Format (push) Successful in 15s
CI / Clippy (push) Successful in 2m39s
CI / Test (push) Successful in 6m49s
CI / CUDA type-check (push) Successful in 19m10s
CI / Build cortex SRPM (push) Has been skipped
CI / Publish cortex to COPR (push) Has been skipped
CI / Build neuron SRPM (push) Has been skipped
CI / Publish neuron to COPR (push) Has been skipped
CI / Bump version in source (push) Has been skipped
`2f2f306c` added qwen4_exp to `DENSE_SUPPORTED_MODEL_TYPES` and to
`candle::load_arch_dense`. That is the CPU fallback. Every CUDA load
goes through the device worker's own `load_dense_inner`, which had no
arm for it — so on a GPU host the model passed preflight and then hit

    unrouted supported model_type 'qwen4_exp' — DENSE_SUPPORTED_MODEL_TYPES
    and load_dense_inner must stay in sync

in about 200 ms, having read none of the 360 GB. The bail's own comment
is the specification this violated, and it was written before there was
a second loader to violate it.

The arm mirrors the CPU one, and the job now carries the parsed
`quant`. It has to: the worker load never had a quant parameter, so
even a routed qwen4_exp would have loaded BF16 experts — 241.6 GB of
them, measured from the checkpoint's own safetensors headers, against
a 32.6 GB card. In-situ quantisation reaching only the CPU path is the
same defect #320 fixed one layer up, and it would have looked like
#320's fix had not worked.

The test asserts every model_type the preflight admits has an arm here,
by driving a bare `{"model_type": ...}` at the loader and requiring the
failure to be anything other than "unrouted". Adding a name to the list
with no loader behind it now fails in CI rather than on a GPU host at
load time — which is the only place the difference between the two
loaders was observable.

Refs #307, #315, #320.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015v1FQqShiRp9rrJEEcgNER
2026-09-06 19:36:46 +03:00
grenadeandClaude Opus 5 430b6be62b fix(neuron): let the loaded model answer for itself, and give the pool back
CI / Test (push) Blocked by required conditions
CI / Config consistency (push) Successful in 9s
CI / Classify changes (push) Successful in 21s
CI / Web (lint + typecheck + i18n + build) (push) Has been skipped
CI / CUDA type-check (push) Successful in 19m23s
CI / Format (push) Successful in 12s
CI / Clippy (push) Successful in 2m41s
CI / Build cortex SRPM (push) Has been cancelled
CI / Build neuron SRPM (push) Has been cancelled
CI / Publish cortex to COPR (push) Has been cancelled
CI / Publish neuron to COPR (push) Has been cancelled
CI / Bump version in source (push) Has been cancelled
Three things the first qwen4_exp cold load would have got wrong, none
of which the load itself has to reach to matter.

The single-GPU path decided prefix-snapshot capability by matching
config.json's model_type against a list of two, while
ModelArch::supports_kv_snapshot had grown to three. So qwen4_exp
loaded with snapshots reported unavailable and batched decode silently
off — the work that landed the snapshot was reachable only through a
list somewhere else that nobody had reason to look at. The dense load
reply now carries the arch's own answer (DenseLoad), taken while the
model is still in hand on the worker thread, which is the only place
that can be asked. The TP path still re-derives it; that is correct
for the two archs it serves today and it is commented as the hazard it
is, because #319 will add a third.

Nothing built a context profile for qwen4_exp either, so derive_limit
had no physics and the model would have advertised the static prompt
cap. The profile is the qwen3_5 one plus a term: the QSA indexer keeps
a second cache on every full-attention layer, 12 x 1 x 128 x 2 bytes =
3 KiB/token beside the main cache's 24. Advertising against the main
cache alone overstates what the card can hold by an eighth, which is
the #281 failure mode. The test drives both builders off the
checkpoint's verbatim config.json and asserts each declines the
other's, since the load path now tries them in turn.

And a load that fails part-way left its bytes in cudarc's pool. The
image path learned this at the benjy cold-swap and trims after every
load and drop; the text path never did. A dense load that runs out of
VRAM has typically allocated tens of gigabytes first, and the model
that was evicted to make room for it needs them back — so LoadGguf,
LoadDense, DropArch and DropTp now trim the way LoadImage and
DropImage always have.

Refs #307, #310, #281.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015v1FQqShiRp9rrJEEcgNER
2026-09-06 19:10:08 +03:00
grenade af40bac9b8 Merge branch 'fix/320-isq-reachable-and-log-levels'
build-prerelease / Resolve version stamps + change detection (push) Successful in 18s
build-prerelease / Build cortex binary (push) Has been skipped
build-prerelease / Package cortex RPM (push) Has been skipped
build-prerelease / Build helexa-bench binary (push) Has been skipped
build-prerelease / Build helexa-upstream binary (push) Has been skipped
build-prerelease / Package helexa-bench RPM (push) Has been skipped
build-prerelease / Package helexa-upstream RPM (push) Has been skipped
build-prerelease / Build helexa-angels binary (push) Has been skipped
build-prerelease / Package helexa-angels RPM (push) Has been skipped
build-prerelease / Build helexa-router binary (push) Has been skipped
build-prerelease / Build helexa-tools binary (push) Has been skipped
build-prerelease / Package helexa-router RPM (push) Has been skipped
build-prerelease / Package helexa-tools RPM (push) Has been skipped
build-prerelease / Lint (fmt + clippy) (push) Successful in 4m7s
build-prerelease / Test (push) Successful in 9m15s
build-prerelease / Build neuron-ampere (push) Successful in 2m11s
build-prerelease / Build neuron-ada (push) Successful in 2m14s
build-prerelease / Package helexa-neuron-ampere RPM (push) Has been skipped
build-prerelease / Package helexa-neuron-blackwell RPM (push) Has been skipped
build-prerelease / Build neuron-blackwell (push) Successful in 14m18s
build-prerelease / Package helexa-neuron-ada RPM (push) Successful in 1m6s
build-prerelease / Publish to rpm.lair.cafe (unstable) (push) Successful in 29s
2026-09-06 18:03:15 +03:00
grenade d5738bfb89 fix(neuron): read quant as ISQ when the repo has no GGUF (#320)
CI / Config consistency (push) Successful in 7s
CI / Classify changes (push) Successful in 14s
CI / Web (lint + typecheck + i18n + build) (push) Has been skipped
CI / Format (push) Successful in 10s
CI / Clippy (push) Successful in 2m36s
CI / Test (push) Successful in 9m44s
CI / CUDA type-check (push) Successful in 19m12s
CI / Build cortex SRPM (push) Has been skipped
CI / Publish cortex to COPR (push) Has been skipped
CI / Build neuron SRPM (push) Has been skipped
CI / Publish neuron to COPR (push) Has been skipped
CI / Bump version in source (push) Has been skipped
The single-GPU load paths treated a non-empty `quant` as "select the
GGUF whose filename contains this string", while the TP path treats the
same field as in-situ quantisation of safetensors. A model published
only as safetensors is therefore loadable quantised on two cards and
not on one, which is backwards — the single card is the one that needs
the quantisation.

Fall through to the dense loader (which applies ISQ) when the repo has
no GGUF at all but does have safetensors. A repo that does carry GGUFs
keeps the old behaviour exactly, including the old error when none of
them match: that case is a typo, not an ISQ request, and silently
turning it into a full-precision load would be a worse answer than the
error.

Also drop the per-model context-limit line from debug to trace. Every
input to it is fixed at load, so it repeats byte-identically on every
`GET /models` poll — roughly 8,600 lines a day per model saying the
same thing, on top of whatever you were actually reading the journal
for.

And set RUST_LOG=debug for neuron fleet-wide from deploy.yml, in the
model.conf drop-in it already manages. The code default is `info`,
which is too coarse to reconstruct a load or a routing decision after
the fact; before this, one host had `debug` because it was set there by
hand, and the others quietly did not. A verbosity you have to remember
to set is one you discover you did not have at the moment you needed
it. It sorts after local.conf, so the managed value wins.
2026-09-03 16:22:19 +03:00
grenade ecbfe22124 Merge branch 'feat/qwen4-exp-quantised-experts'
build-prerelease / Resolve version stamps + change detection (push) Successful in 13s
build-prerelease / Lint (fmt + clippy) (push) Successful in 2m45s
build-prerelease / Build cortex binary (push) Has been skipped
build-prerelease / Build helexa-bench binary (push) Has been skipped
build-prerelease / Package cortex RPM (push) Has been skipped
build-prerelease / Build helexa-upstream binary (push) Has been skipped
build-prerelease / Package helexa-bench RPM (push) Has been skipped
build-prerelease / Package helexa-upstream RPM (push) Has been skipped
build-prerelease / Build helexa-angels binary (push) Has been skipped
build-prerelease / Build helexa-router binary (push) Has been skipped
build-prerelease / Package helexa-angels RPM (push) Has been skipped
build-prerelease / Package helexa-router RPM (push) Has been skipped
build-prerelease / Build helexa-tools binary (push) Has been skipped
build-prerelease / Package helexa-tools RPM (push) Has been skipped
build-prerelease / Build neuron-ada (push) Successful in 2m27s
build-prerelease / Build neuron-ampere (push) Successful in 2m28s
build-prerelease / Test (push) Successful in 10m36s
build-prerelease / Build neuron-blackwell (push) Successful in 14m47s
build-prerelease / Package helexa-neuron-ampere RPM (push) Successful in 1m3s
build-prerelease / Package helexa-neuron-ada RPM (push) Successful in 1m11s
build-prerelease / Package helexa-neuron-blackwell RPM (push) Successful in 4m10s
build-prerelease / Publish to rpm.lair.cafe (unstable) (push) Successful in 24s
2026-09-02 19:52:10 +03:00
8 changed files with 530 additions and 53 deletions
+27 -15
View File
@@ -317,22 +317,36 @@ jobs:
# restart decision below, exactly like the drop-in.
neuron_toml_changed="${{ steps.neuronconf.outputs.changed }}"
# ── Desired per-model systemd drop-in ─────────────────────────
# model.conf carries NEURON_MAX_PROMPT_TOKENS so the context cap
# is deterministic per host and rolled out (with a restart) by
# ── Desired per-host systemd drop-in ──────────────────────────
# model.conf carries the environment neuron is started with, so
# it is deterministic per host and rolled out (with a restart) by
# this workflow, not hand-edited. It sorts after local.conf, so a
# deploy-managed value wins over any manual local override of the
# same variable. See doc/context-limits.md.
# same variable.
#
# RUST_LOG is fleet-uniform and unconditional. The code default
# is `info`, which is too coarse to diagnose a load or a routing
# decision after the fact, and before this it was `debug` on
# exactly one host because someone set it there by hand. A
# verbosity you have to remember to set is a verbosity you find
# out you did not have at the moment you needed it. Bumping a
# module (`debug,neuron::harness::candle=trace`) is a one-line
# change here, applied everywhere, with an audit trail.
#
# NEURON_MAX_PROMPT_TOKENS is per-host and stays conditional;
# see doc/context-limits.md.
conf=/etc/systemd/system/neuron.service.d/model.conf
config_changed=${neuron_toml_changed:-0}
rust_log="debug"
desired=$(printf '%s\n%s\n%s' \
"# Managed by .gitea/workflows/deploy.yml - do not edit by hand." \
"[Service]" \
"Environment=RUST_LOG=${rust_log}")
if [ -n "${max_prompt_tokens}" ]; then
desired=$(printf '%s\n%s\n%s\n%s' \
"# Managed by .gitea/workflows/deploy.yml - do not edit by hand." \
"# Per-model context cap; see doc/context-limits.md." \
"[Service]" \
desired=$(printf '%s\n%s' "${desired}" \
"Environment=NEURON_MAX_PROMPT_TOKENS=${max_prompt_tokens}")
[ "${desired}" = "$(cat "${conf}" 2>/dev/null || true)" ] || config_changed=1
fi
[ "${desired}" = "$(cat "${conf}" 2>/dev/null || true)" ] || config_changed=1
# ── Desired registry drop-in ──────────────────────────────────
# Every model fetch goes through rustingface rather than
@@ -411,15 +425,13 @@ jobs:
echo "installed=${installed} published=${latest:-unknown} pkg_changed=${pkg_changed} config_changed=${config_changed} — deploying"
# Write the drop-in (staged in gitea_ci's dir, installed root-owned).
# Guarded on max_prompt_tokens as well as config_changed: since
# a neuron.toml change also sets config_changed, an entry with
# no max_prompt_tokens would otherwise reach this with `desired`
# unset.
if [ "${config_changed}" -eq 1 ] && [ -n "${max_prompt_tokens}" ]; then
# `desired` is always set now that RUST_LOG is unconditional, so
# config_changed alone is the guard.
if [ "${config_changed}" -eq 1 ]; then
printf '%s\n' "${desired}" > /var/lib/gitea_ci/model.conf
sudo /usr/bin/install -o root -g root -m 0644 -D /var/lib/gitea_ci/model.conf "${conf}"
rm -f /var/lib/gitea_ci/model.conf
echo "applied ${conf}: NEURON_MAX_PROMPT_TOKENS=${max_prompt_tokens}"
echo "applied ${conf}: RUST_LOG=${rust_log} NEURON_MAX_PROMPT_TOKENS=${max_prompt_tokens:-<unset>}"
fi
# Staged 0600 in gitea_ci's own dir before install, so the token
+121 -4
View File
@@ -88,6 +88,51 @@ pub(crate) struct QuantizedExpert {
down: QMatMul,
}
/// The quantisation type actually usable for rows of `row` elements.
///
/// ggml quantises along the last dimension, and a row must be a whole
/// number of blocks. The k-quants (`Q2K`..`Q8K`) block on 256; the
/// older types block on 32. `qwen4_exp`'s `down_proj` reduces over
/// `moe_intermediate_size = 640`, which is 2.5 blocks of 256 — so a
/// `quant = "q4k"` load fails on the very first layer with
/// `quantized tensor must have their last dim divisible by block size
/// [2560, 640] 256`, having read 131 shards to get there.
///
/// Substituting a 32-block type for that half is what llama.cpp does
/// with the same constraint, and it costs almost nothing here: `Q4_0`
/// and `Q4K` are both 4.5 bpw, so the memory arithmetic the placement
/// decisions rest on is unchanged. The quality is a little worse per
/// bit — `Q4_0` has one scale per 32 values where `Q4K` has a
/// two-level hierarchy — which is a real trade, but it applies to one
/// of the three expert matrices and the alternative is not loading.
///
/// Errors rather than falls back further if the row will not even
/// divide 32: that is a config we do not understand, and silently
/// leaving those weights dense would be a memory surprise, not a
/// mercy.
pub(crate) fn quant_for_row(requested: GgmlDType, row: usize) -> candle_core::Result<GgmlDType> {
if row.is_multiple_of(requested.block_size()) {
return Ok(requested);
}
let fallback = match requested {
GgmlDType::Q2K | GgmlDType::Q3K | GgmlDType::Q4K => GgmlDType::Q4_0,
GgmlDType::Q5K => GgmlDType::Q5_0,
GgmlDType::Q6K | GgmlDType::Q8K => GgmlDType::Q8_0,
// Already a 32-block type: there is nothing coarser to fall
// back to, so this is the error case below.
other => other,
};
if row.is_multiple_of(fallback.block_size()) {
return Ok(fallback);
}
candle_core::bail!(
"cannot quantise a row of {row} elements as {requested:?} (block \
{}) or {fallback:?} (block {}): the row divides neither",
requested.block_size(),
fallback.block_size(),
)
}
impl Experts {
pub(crate) fn len(&self) -> usize {
match self {
@@ -101,6 +146,10 @@ impl Experts {
///
/// Takes the fused tensors by reference and drops nothing itself —
/// the caller owns the peak, and should hold one layer at a time.
///
/// The two halves may not end up the same dtype: see
/// [`quant_for_row`]. `qwen4_exp`'s `down_proj` reduces over 640,
/// which no k-quant can block.
pub(crate) fn quantize_banked(
gate_up: &Tensor,
down: &Tensor,
@@ -108,6 +157,22 @@ impl Experts {
dtype: GgmlDType,
) -> candle_core::Result<Self> {
let n = gate_up.dims()[0];
// Decided once, from the shapes, rather than per expert —
// every expert in a layer has the same two row widths, and
// 512 identical log lines per layer would bury the fact.
let gate_up_dtype = quant_for_row(dtype, gate_up.dims()[2])?;
let down_dtype = quant_for_row(dtype, down.dims()[2])?;
if gate_up_dtype != dtype || down_dtype != dtype {
tracing::info!(
requested = ?dtype,
gate_up_row = gate_up.dims()[2],
gate_up_dtype = ?gate_up_dtype,
down_row = down.dims()[2],
down_dtype = ?down_dtype,
"expert quantisation: a row width does not divide the requested \
block size; substituting a 32-block type for that half"
);
}
let mut out = Vec::with_capacity(n);
for e in 0..n {
let gu = gate_up.i(e)?;
@@ -122,16 +187,16 @@ impl Experts {
// sharing the parent's buffer. Round-tripping through a Vec
// is the part that actually allocates, and it is also where
// the f32 the quantiser wants comes from.
let q = |t: Tensor| -> candle_core::Result<QMatMul> {
let q = |t: Tensor, dtype: GgmlDType| -> candle_core::Result<QMatMul> {
let dims = t.dims().to_vec();
let vals = t.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()?;
let owned = Tensor::from_vec(vals, dims, t.device())?;
QMatMul::from_qtensor(QTensor::quantize(&owned, dtype)?)
};
out.push(QuantizedExpert {
gate: q(gu.narrow(0, 0, intermediate)?)?,
up: q(gu.narrow(0, intermediate, intermediate)?)?,
down: q(down.i(e)?)?,
gate: q(gu.narrow(0, 0, intermediate)?, gate_up_dtype)?,
up: q(gu.narrow(0, intermediate, intermediate)?, gate_up_dtype)?,
down: q(down.i(e)?, down_dtype)?,
});
}
Ok(Experts::Quantized(out))
@@ -622,6 +687,58 @@ mod tests {
/// a tiny fixture silently cannot be quantised at all, which is the
/// first thing that bites when this is tried on a toy model.
///
/// `qwen4_exp`'s real expert widths, which no k-quant can block.
///
/// `moe_intermediate_size` is 640, so `down_proj` is `[2560, 640]`
/// and its 640-element rows are 2.5 blocks of 256. The load died
/// on beast at decoder layer 0 with `quantized tensor must have
/// their last dim divisible by block size [2560, 640] 256`, after
/// resolving all 131 shards.
///
/// The fixture that missed it was 256 wide in both dimensions —
/// the smallest width a k-quant accepts — so every row divided
/// and the orientation could not matter. This one uses the
/// checkpoint's own numbers, scaled down only in expert count.
#[test]
fn the_real_expert_widths_quantise_despite_a_640_wide_reduction() {
assert_eq!(
quant_for_row(GgmlDType::Q4K, 2560).unwrap(),
GgmlDType::Q4K,
"gate_up reduces over hidden_size, which is 10 whole blocks"
);
assert_eq!(
quant_for_row(GgmlDType::Q4K, 640).unwrap(),
GgmlDType::Q4_0,
"down reduces over moe_intermediate_size, which is not"
);
assert_eq!(quant_for_row(GgmlDType::Q6K, 640).unwrap(), GgmlDType::Q8_0);
assert_eq!(
quant_for_row(GgmlDType::Q8_0, 640).unwrap(),
GgmlDType::Q8_0
);
// 100 divides neither 256 nor 32.
assert!(quant_for_row(GgmlDType::Q4K, 100).is_err());
// And the whole path runs at those widths.
let (n_experts, hidden, inter) = (2usize, 2560usize, 640usize);
let gate_up = randn(&[n_experts, inter * 2, hidden]);
let down = randn(&[n_experts, hidden, inter]);
let quantised = Experts::quantize_banked(&gate_up, &down, inter, GgmlDType::Q4K)
.expect("the real widths must quantise");
let xs = randn(&[2, hidden]);
let got = quantised.forward_one(0, &xs).expect("forward");
assert_eq!(got.dims(), &[2, hidden]);
assert!(
got.flatten_all()
.unwrap()
.to_vec1::<f32>()
.unwrap()
.iter()
.all(|v| v.is_finite()),
"a substituted dtype must still produce finite output"
);
}
/// The assertion is relative error against the dense output, with a
/// noise baseline: a q8_0 expert should be close, a q4k expert
/// looser, and both far nearer the truth than an unrelated expert
+89 -22
View File
@@ -1349,7 +1349,7 @@ impl LlamaDense {
/// value. New entries land alongside a new `ModelArch` variant + a
/// dispatch branch in `load_arch_dense` (plus, for TP, a parallel
/// pattern in `tp_qwen3.rs`).
const DENSE_SUPPORTED_MODEL_TYPES: &[&str] = &[
pub(crate) const DENSE_SUPPORTED_MODEL_TYPES: &[&str] = &[
"llama",
"qwen3",
"qwen3_5",
@@ -2885,6 +2885,59 @@ impl CandleHarness {
Ok((tokenizer_path, arch))
}
/// Whether this spec's `quant` names a GGUF the repo actually has.
///
/// `quant` is overloaded (#320): the TP path reads it as in-situ
/// quantisation of safetensors, while the single-GPU paths read it
/// as "select the GGUF whose filename contains this string". A repo
/// with no GGUF at all cannot mean the second, so rather than fail
/// with an error about a file that was never going to exist, the
/// same string is read the way the TP path reads it.
///
/// This is deliberately narrow. A repo that *does* carry GGUFs keeps
/// the old behaviour exactly, including the old error when none of
/// them match the requested quant — that case is a typo, not an ISQ
/// request, and turning it into a silent 360 GB dense load would be
/// a worse answer than the error.
async fn quant_selects_a_gguf(
&self,
spec: &ModelSpec,
source_id: &cortex_core::source::ModelSourceId,
) -> Result<bool> {
let Some(quant) = spec.quant.as_deref().filter(|q| !q.is_empty()) else {
return Ok(false);
};
let api = self.hf_api_for(&source_id.scheme)?;
let info = api
.model(source_id.repo_path())
.info()
.await
.with_context(|| format!("fetch HF repo info for {source_id}"))?;
let names: Vec<String> = info
.siblings
.iter()
.map(|s| s.rfilename.to_lowercase())
.collect();
let any_gguf = names.iter().any(|n| n.ends_with(".gguf"));
if any_gguf {
return Ok(true);
}
let any_safetensors = names.iter().any(|n| n.ends_with(".safetensors"));
if any_safetensors {
tracing::info!(
model = %source_id,
quant = %quant,
"no GGUF in this repo; reading `quant` as in-situ quantization of \
the safetensors (#320)"
);
return Ok(false);
}
anyhow::bail!(
"repo {source_id} has neither a GGUF nor safetensors; `quant = {quant:?}` \
cannot be satisfied"
)
}
/// Resolve a model spec to local GGUF and tokenizer file paths via
/// hf-hub. Downloads on first use; subsequent calls are cached.
async fn resolve_files(
@@ -3869,7 +3922,7 @@ impl Harness for CandleHarness {
context_profile,
) = if let Some(w) = &worker {
// CUDA path: resolve, then load in the worker.
if spec.quant.is_some() {
if self.quant_selects_a_gguf(spec, &source_id).await? {
let (gguf_path, tokenizer_path) = self.resolve_files(spec, &source_id).await?;
let handle = w
.load_gguf(gguf_path, spec.model_id.clone())
@@ -3893,36 +3946,38 @@ impl Harness for CandleHarness {
let (config_path, tokenizer_path, safetensors_paths) =
self.resolve_dense_files(spec, &source_id).await?;
let meta = VisionMeta::from_config_path(&config_path);
// Prefix snapshots (#11) exist only for the in-tree
// qwen3_5 arch — which serves BOTH its model_types
// (qwen3_5 and the flat-config qwen3_next MoE family);
// the worker holds the ModelArch so the async side
// decides from config.json instead.
let snapshot_capable = matches!(
config_model_type(&config_path).as_deref(),
Some(super::arch::qwen3_5::MODEL_TYPE)
| Some(super::arch::qwen3_5::MODEL_TYPE_NEXT)
);
// Context-limit physics (#67): single-GPU → world_size 1.
// `None` for non-qwen3_5 dense archs.
// `None` for dense archs with no profile builder — they
// fall back to the static prompt cap.
let context_profile =
super::context_limit::profile_from_qwen3_5_config(&config_path, 1);
let handle = w
.load_dense(config_path, safetensors_paths, spec.model_id.clone())
super::context_limit::profile_from_qwen3_5_config(&config_path, 1).or_else(
|| super::context_limit::profile_from_qwen4_exp_config(&config_path, 1),
);
// In-situ quantisation (#320) reaches the worker load
// too, not just the CPU one — parsed here because
// `spec` does not cross the channel.
let isq = super::quant::parse_quant_string(spec.quant.as_deref())?;
let load = w
.load_dense(config_path, safetensors_paths, spec.model_id.clone(), isq)
.await
.map_err(|e| anyhow::anyhow!("worker load_dense: {e:#}"))?;
// Prefix snapshots (#11): the built model answers for
// itself on the way back, rather than the async side
// re-deriving the answer from `config.json`. See
// `DenseLoad` — the re-derivation is what silently
// dropped batched decode for qwen4_exp.
(
tokenizer_path,
None,
Some(handle),
Some(load.handle),
meta,
snapshot_capable,
load.supports_kv_snapshot,
context_profile,
)
}
} else {
// CPU path: legacy spawn_blocking + Arc<Mutex<ModelArch>>.
let (tokenizer_path, arch) = if spec.quant.is_some() {
let (tokenizer_path, arch) = if self.quant_selects_a_gguf(spec, &source_id).await? {
self.load_arch_gguf(spec, &source_id, &device).await?
} else {
self.load_arch_dense(spec, &source_id, &device).await?
@@ -4740,6 +4795,13 @@ impl CandleHarness {
image_token_id: vision_meta.image_token_id,
image_grid_factor: vision_meta.image_grid_factor,
spec: spec.clone(),
// Snapshot capability re-derived from `config.json`
// rather than asked of the loaded shard. Correct today —
// `TP_SUPPORTED_MODEL_TYPES` is exactly these two — but it
// is the same shape as the bug `DenseLoad` fixed on the
// single-GPU path, so whoever adds an arch here (#319)
// must add it in both places or lose batched decode
// silently.
prefix_cache: self.new_prefix_cache(matches!(
config_model_type(&config_path).as_deref(),
Some(super::arch::qwen3_5::MODEL_TYPE)
@@ -6291,9 +6353,14 @@ struct VisionMeta {
}
/// Peek at `config.json` for its `model_type`. Best-effort — `None`
/// on any read/parse error. The load path uses this to decide prefix-
/// snapshot capability for worker-held models the async side can't
/// inspect directly.
/// on any read/parse error.
///
/// Only the TP load path still asks: the single-GPU path takes the
/// arch's own answer off the load reply (`DenseLoad`) rather than
/// re-deriving it here, which is what stopped the two from drifting.
/// The TP path has the same hazard and not yet the same cure — see
/// the note at its call site.
#[cfg(feature = "cuda")]
fn config_model_type(config_path: &std::path::Path) -> Option<String> {
let text = std::fs::read_to_string(config_path).ok()?;
let v: serde_json::Value = serde_json::from_str(&text).ok()?;
+139 -3
View File
@@ -252,6 +252,85 @@ pub fn profile_from_qwen3_5_config(config_path: &Path, world_size: u32) -> Optio
})
}
/// Bytes of **QSA indexer** cache one token adds, per card (#307).
///
/// `qwen4_exp` keeps a second cache beside the main one: on every
/// full-attention layer the indexer stores the raw index key,
/// `indexer_kv_heads * indexer_head_dim` wide, in the compute dtype
/// (`arch::qwen4_exp::qsa::Indexer::key_cache`). Keys only — the
/// indexer scores blocks, it does not attend them — so there is no
/// `2 *` here.
///
/// It does not shard: `indexer_kv_heads` is 1, so a TP rank holds the
/// whole thing however wide the world is. At the checkpoint's 12
/// full-attention layers x 1 head x 128 dims that is 3 KiB/token on
/// top of the main cache's 24 — the surcharge the epic's original
/// arithmetic omitted, and it grows with context exactly as the main
/// cache does.
pub fn indexer_bytes_per_token(
n_full_attn_layers: usize,
indexer_kv_heads: usize,
indexer_head_dim: usize,
dtype_bytes: usize,
) -> u64 {
(n_full_attn_layers * indexer_kv_heads * indexer_head_dim * dtype_bytes) as u64
}
/// Build a [`ContextProfile`] from a `qwen4_exp` `config.json` — the
/// sibling of [`profile_from_qwen3_5_config`] for the other hybrid
/// arch. Returns `None` for any other `model_type` or an unparseable
/// config.
///
/// Same shape of physics, one term more: the per-token cost is the
/// main KV cache **plus** the QSA indexer's, because both grow per
/// token and both come out of the same card. Advertising against the
/// main cache alone would overstate what is servable by about an
/// eighth, which is the class of error #281 is about.
///
/// `layer_types` is always populated by the time `from_config_json`
/// returns (it fills the array from `full_attention_interval` when the
/// checkpoint omits it), so counting it is authoritative here.
pub fn profile_from_qwen4_exp_config(
config_path: &Path,
world_size: u32,
) -> Option<ContextProfile> {
let text = std::fs::read_to_string(config_path).ok()?;
if !super::arch::qwen4_exp::config::is_qwen4_exp(&text) {
return None;
}
let cfg = super::arch::qwen4_exp::config::Config::from_config_json(&text).ok()?;
let tc = &cfg.text_config;
let n_full_attn_layers = tc
.layer_types
.iter()
.filter(|t| t.as_str() == "full_attention")
.count();
// A model with no full-attention layer has no growing cache, and
// the derivation divides by this. Nothing in the family looks like
// that, so treat it as a config we do not understand rather than
// inventing an unbounded context.
if n_full_attn_layers == 0 {
return None;
}
let kv_bytes_per_token_per_card = kv_bytes_per_token(
n_full_attn_layers,
tc.num_key_value_heads,
tc.head_dim,
KV_CACHE_DTYPE_BYTES,
world_size,
) + indexer_bytes_per_token(
n_full_attn_layers,
tc.indexer_kv_heads,
tc.indexer_head_dim,
KV_CACHE_DTYPE_BYTES,
);
Some(ContextProfile {
max_position_embeddings: tc.max_position_embeddings,
kv_bytes_per_token_per_card,
world_size,
})
}
/// Round a token count down to a clean boundary so the advertised limit
/// doesn't jitter by a handful of tokens as live VRAM / the throughput
/// EMA wobble between polls.
@@ -375,9 +454,15 @@ pub fn derive_limit(
// Observability (#126): every input and intermediate term, so a
// surprising advertised limit is diagnosable from the journal
// instead of re-deriving by hand. DEBUG — this runs on every
// `GET /models` poll (a few lines per poll cycle).
tracing::debug!(
// instead of re-deriving by hand.
//
// TRACE, not debug: this runs on every `GET /models` poll and every
// input is fixed at load, so the line is byte-identical each time —
// about 8,600 a day per model at a 10s poll. It is worth having when
// reasoning about a context ceiling and worth nothing the rest of
// the time, and at debug it buries the lines that are not routine
// (#320).
tracing::trace!(
max_pos = profile.max_position_embeddings,
kv_bytes_per_token_per_card = profile.kv_bytes_per_token_per_card,
free_tightest_mb,
@@ -418,6 +503,57 @@ pub fn derive_limit(
#[cfg(test)]
mod tests {
/// The advertised limit for `qwen4_exp` must price both caches.
///
/// The main KV cache is 12 full-attention layers x 2 kv heads x 256
/// dims x 2 (K and V) x 2 bytes = 24 KiB/token, and the QSA indexer
/// adds 12 x 1 x 128 x 2 bytes = 3 KiB on top. Counting only the
/// first would advertise ~12.5% more context than the card can
/// hold — the failure mode #281 exists to stop, and the one the
/// epic's own arithmetic made before the indexer cache was found.
///
/// Driven from the checkpoint's verbatim `config.json`, so a field
/// that changes shape upstream fails here rather than in
/// production.
#[test]
fn a_qwen4_exp_profile_counts_the_indexer_cache_too() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.json");
std::fs::write(&path, super::super::arch::qwen4_exp::config::SHIPPED).unwrap();
let profile = profile_from_qwen4_exp_config(&path, 1)
.expect("the shipped config.json must yield a profile");
assert_eq!(profile.max_position_embeddings, 262_144);
assert_eq!(
profile.kv_bytes_per_token_per_card,
24 * 1024 + 3 * 1024,
"main KV plus the indexer's second cache"
);
}
/// The two hybrid archs must not answer for each other: whichever
/// builder runs first has to decline a config it does not own, or
/// the load path's `or_else` chain silently prices one model with
/// the other's physics.
#[test]
fn the_profile_builders_decline_each_others_configs() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.json");
std::fs::write(&path, super::super::arch::qwen4_exp::config::SHIPPED).unwrap();
assert!(
profile_from_qwen3_5_config(&path, 1).is_none(),
"the qwen3_5 builder must decline a qwen4_exp config"
);
let path = dir.path().join("other.json");
std::fs::write(&path, r#"{"model_type": "qwen3_next"}"#).unwrap();
assert!(
profile_from_qwen4_exp_config(&path, 1).is_none(),
"the qwen4_exp builder must decline everything else"
);
}
/// The deploy's smoke probe must not set the advertised context.
///
/// 19 tokens in 130 ms reads as ~145 tok/s on a host that measures
@@ -17,7 +17,9 @@ use crate::harness::arch::snapshot::KvCacheSnapshot;
use crate::harness::candle::ModelArch;
#[cfg(feature = "cuda")]
use crate::harness::device_worker::jobs::TpHandle;
use crate::harness::device_worker::jobs::{ArchHandle, ImageHandle, ImageInput, Job, KvSnapshotId};
use crate::harness::device_worker::jobs::{
ArchHandle, DenseLoad, ImageHandle, ImageInput, Job, KvSnapshotId,
};
use crate::harness::image::ZImagePipeline;
#[cfg(feature = "cuda")]
use crate::harness::tp::TpLeaderModel;
@@ -131,17 +133,44 @@ pub(crate) fn run(device_index: u32, rx: Receiver<Job>, poisoned: Arc<AtomicBool
} => {
let result = load_gguf_inner(&state.device, &gguf_path, &model_id)
.map(|arch| insert_arch(&mut state, Box::new(arch)));
// Same reasoning as `LoadImage`: release load-time
// transients before serving, and — on the failure
// path — give back whatever the partial load had
// allocated before it gave up. Without this a load
// that OOMs leaves its bytes in the pool, where the
// driver still counts them against the next load.
trim_device_pool(&state);
let _ = reply.send(result);
}
Job::LoadDense {
config_path,
safetensors_paths,
model_id,
quant,
reply,
} => {
let result =
load_dense_inner(&state.device, &config_path, &safetensors_paths, &model_id)
.map(|arch| insert_arch(&mut state, Box::new(arch)));
let result = load_dense_inner(
&state.device,
&config_path,
&safetensors_paths,
&model_id,
quant,
)
.map(|arch| {
// Ask the model, once, while it is still in
// hand. See `DenseLoad`.
let supports_kv_snapshot = arch.supports_kv_snapshot();
let handle = insert_arch(&mut state, Box::new(arch));
DenseLoad {
handle,
supports_kv_snapshot,
}
});
// As for `LoadGguf`. It matters more here: a dense
// load that runs out of VRAM part-way has typically
// allocated tens of gigabytes first, and the evicted
// model waiting to be restored needs them back.
trim_device_pool(&state);
let _ = reply.send(result);
}
Job::DropArch { handle, reply } => {
@@ -158,6 +187,14 @@ pub(crate) fn run(device_index: u32, rx: Receiver<Job>, poisoned: Arc<AtomicBool
// the end of the arm; calling drop() explicitly just
// makes the intent visible.
drop(removed);
// Return the freed blocks to the system rather than
// the stream-ordered pool, so the next load actually
// sees the VRAM — `DropImage` has done this since the
// benjy cold-swap, and an unload is an unload whatever
// modality asked for it.
if was_present {
trim_device_pool(&state);
}
tracing::debug!(
device_index,
handle = handle.0,
@@ -374,6 +411,13 @@ pub(crate) fn run(device_index: u32, rx: Receiver<Job>, poisoned: Arc<AtomicBool
let was_present = removed.is_some();
drop(removed);
state.tp_kv_snapshots.retain(|(h, _), _| *h != handle);
// As `DropArch`: this is only the leader's shard —
// the other ranks free theirs in their own processes
// — but the leader's is the one sharing a card with
// whatever loads next.
if was_present {
trim_device_pool(&state);
}
tracing::debug!(
device_index,
tp_handle = handle.0,
@@ -895,6 +939,7 @@ fn load_dense_inner(
config_path: &std::path::Path,
safetensors_paths: &[std::path::PathBuf],
model_id: &str,
quant: Option<candle_core::quantized::GgmlDType>,
) -> anyhow::Result<ModelArch> {
use anyhow::Context;
use candle_core::DType;
@@ -988,6 +1033,36 @@ fn load_dense_inner(
.context("build Qwen3-Next dense model")?;
Ok(ModelArch::Qwen3_5Dense(model))
}
"qwen4_exp" => {
// Qwen3.8-Flash-Next. Mirrors the CPU path in
// `candle::load_arch_dense` — same config type, same
// sharded backend, same in-situ quantisation.
//
// ISQ is not optional for this architecture: the routed
// experts are 241.6 GB at BF16 (measured from the
// checkpoint's own headers), against 32.6 GB of card. A
// load without a `quant` will fail on memory rather than
// on anything this code can say (#315, #252).
let cfg = crate::harness::arch::qwen4_exp::config::Config::from_config_json(&cfg_text)
.context("parse qwen4_exp config.json")?;
let sharded_vb = unsafe {
candle_nn::var_builder::ShardedSafeTensors::var_builder(
safetensors_paths,
dtype,
device,
)
.context("build ShardedVarBuilder for qwen4_exp")?
};
let model = crate::harness::arch::qwen4_exp::model::Qwen4ExpForCausalLM::load(
&cfg,
dtype,
quant,
device,
&sharded_vb,
)
.context("build qwen4_exp model")?;
Ok(ModelArch::Qwen4Exp(Box::new(model)))
}
other => anyhow::bail!(
"unrouted supported model_type '{other}' — \
DENSE_SUPPORTED_MODEL_TYPES and load_dense_inner \
@@ -1669,3 +1744,42 @@ fn drain_poisoned(job: Job, device_index: u32) {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Every architecture the preflight admits must have a loader arm
/// on **this** path, not only on the CPU one in
/// `candle::load_arch_dense`.
///
/// There are two dense loaders — the worker's (every CUDA load)
/// and candle's (the CPU fallback) — and one list gating both.
/// `qwen4_exp` was added to the list and to the CPU loader, so it
/// passed preflight and then hit the "unrouted supported
/// model_type" bail here: on a GPU host the model was
/// unloadable, in about 200 ms, having read nothing. The bail's
/// own comment said the two must stay in sync; nothing checked.
///
/// A bare `{"model_type": ...}` reaches the arm and then fails on
/// the typed parse, which is fine — this asserts only that an arm
/// exists to fail in.
#[test]
fn every_supported_dense_model_type_has_a_loader_arm() {
let dir = tempfile::tempdir().unwrap();
for model_type in crate::harness::candle::DENSE_SUPPORTED_MODEL_TYPES {
let path = dir.path().join(format!("{model_type}.json"));
std::fs::write(&path, format!(r#"{{"model_type": "{model_type}"}}"#)).unwrap();
let msg =
match load_dense_inner(&candle_core::Device::Cpu, &path, &[], model_type, None) {
Ok(_) => panic!("a bare config must not build a model"),
Err(e) => format!("{e:#}"),
};
assert!(
!msg.contains("unrouted"),
"`{model_type}` is in DENSE_SUPPORTED_MODEL_TYPES but load_dense_inner \
has no arm for it: {msg}"
);
}
}
}
@@ -19,6 +19,27 @@ use tokio::sync::oneshot;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ArchHandle(pub u64);
/// What a dense load hands back: the handle, plus what the arch it
/// built says about itself.
///
/// The async side cannot ask the model anything — it lives in the
/// worker's slab and never crosses the channel — so anything the
/// serving path needs to know has to ride back on the reply. Prefix
/// snapshot support (#11) is the first such fact, and it is here
/// rather than re-derived from `config.json` because that is exactly
/// how it went wrong: the async side matched a list of `model_type`
/// strings that `ModelArch::supports_kv_snapshot` had since grown
/// past, so `qwen4_exp` loaded with batched decode silently off.
/// A capability the arch answers for itself cannot drift from the
/// arch.
#[derive(Debug, Clone, Copy)]
pub struct DenseLoad {
pub handle: ArchHandle,
/// [`crate::harness::candle::ModelArch::supports_kv_snapshot`], as
/// answered by the model that was actually built.
pub supports_kv_snapshot: bool,
}
/// Opaque handle to a `TpLeaderModel` stored in the worker thread's
/// state slab. Same shape as [`ArchHandle`] but in a separate
/// namespace so the two slabs can coexist without ambiguity. Phase 3
@@ -107,7 +128,11 @@ pub enum Job {
config_path: PathBuf,
safetensors_paths: Vec<PathBuf>,
model_id: String,
reply: oneshot::Sender<Result<ArchHandle>>,
/// In-situ quantisation (#320): the catalogue's `quant`,
/// already parsed. `None` loads at the checkpoint dtype.
/// Archs that cannot quantise in situ ignore it.
quant: Option<candle_core::quantized::GgmlDType>,
reply: oneshot::Sender<Result<DenseLoad>>,
},
/// Remove the model from the slab and drop it. The `Drop` runs on
/// the worker thread so CUDA tensors release their memory on the
@@ -51,7 +51,7 @@ use tokio::sync::oneshot;
#[cfg(feature = "cuda")]
pub use jobs::TpHandle;
pub use jobs::{ArchHandle, ImageHandle, Job, KvSnapshotId};
pub use jobs::{ArchHandle, DenseLoad, ImageHandle, Job, KvSnapshotId};
/// Errors returned by `DeviceWorkerHandle` submit methods.
#[derive(Debug, thiserror::Error)]
@@ -221,7 +221,8 @@ impl DeviceWorkerHandle {
config_path: std::path::PathBuf,
safetensors_paths: Vec<std::path::PathBuf>,
model_id: String,
) -> Result<ArchHandle, WorkerError> {
quant: Option<candle_core::quantized::GgmlDType>,
) -> Result<DenseLoad, WorkerError> {
if self.poisoned.load(Ordering::Acquire) {
return Err(WorkerError::Poisoned {
device_index: self.device_index,
@@ -233,6 +234,7 @@ impl DeviceWorkerHandle {
config_path,
safetensors_paths,
model_id,
quant,
reply: reply_tx,
})
.map_err(|_| WorkerError::Gone {
@@ -1243,9 +1245,11 @@ mod tests {
fixture.join("config.json"),
vec![fixture.join("model.safetensors")],
"qwen3_next-tiny".into(),
None,
)
.await
.expect("load tiny fixture");
.expect("load tiny fixture")
.handle;
let prompts: [&[u32]; 3] = [&[1, 2, 3], &[4, 5], &[7, 3, 2, 5, 6]];
let steps: [&[u32]; 3] = [&[11, 12, 13], &[9, 8, 7], &[21, 22, 23]];
+3 -1
View File
@@ -1261,9 +1261,11 @@ mod tests {
fixture.join("config.json"),
vec![fixture.join("model.safetensors")],
"qwen3_next-tiny".into(),
None,
)
.await
.expect("load fixture");
.expect("load fixture")
.handle;
let admission_cfg = AdmissionConfig {
max_in_flight: 3,