Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 25 additions & 5 deletions CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -292,11 +292,22 @@ in-actor `nil` return (a retired pattern), degraded mode (unqualified).

**Vision-Capable Model**:
A model whose on-disk config declares image input (the Qwen3.5-family
`vision_config`); text-only checkpoints do not. A fixed property of the model as
downloaded — distinct from **Vision Mode**, which is whether that capability is
currently loaded. The PARO family is vision-capable.
`vision_config`) and whose catalog entry carries no **Text-Only Override**;
text-only checkpoints do not. Fixed for a downloaded model — distinct from
**Vision Mode**, which is whether that capability is currently loaded. Every
**PARO Checkpoint** in the catalog declares image input.
_Avoid_: "vision model" (ambiguous with the loaded container), "multimodal" (there
is no audio/video input path), "supports images" as a per-request flag.
is no audio/video input path), "supports images" as a per-request flag,
"declares vision" as a synonym (declaration is one of the two inputs).

**Text-Only Override**:
A catalog entry's declaration that its checkpoint, although it declares image
input, is served as text-only: no image affordances, the text-class load, no
image keying. The catalog withholding a capability the checkpoint has — never the
checkpoint lacking it.
_Avoid_: "vision disabled" (collides with the global vision opt-out, a user
setting), "text-only model" (that is a checkpoint without `vision_config`),
"unsupported vision" (the capability exists; it is withheld).

**Vision Mode**:
Whether a **Vision-Capable Model** is currently loaded as its image-able VLM
Expand Down Expand Up @@ -1916,8 +1927,17 @@ field), model config / `config.json` dict (a source, not the value), ModelFinger
(separate). "Model identity" vs "flop profile" — the latter is one field of the
former.

**PARO Checkpoint**:
A checkpoint whose weights are quantized with pairwise-rotation INT4 (the
`paroquant` quantization method), whatever its base architecture — dense or
sparse-MoE, any Qwen generation. Recognized by its quantization method, never by
name or size.
_Avoid_: "PARO model" / "PARO family" as an architecture (it is a weight format
spanning architectures), "z-lab model" (the publisher, not the format), "AWQ
model" (PARO extends AWQ's layout with rotations; the two are not interchangeable).

**Prepared Checkpoint**:
The once-converted MLX-native form of a PARO checkpoint, stored beside the
The once-converted MLX-native form of a **PARO Checkpoint**, stored beside the
original so later loads skip the AutoAWQ conversion; rotation parameters remain
runtime state loaded verbatim — nothing semantic is baked into the artifact.
Stale or unreadable artifacts self-heal by re-conversion.
Expand Down
19 changes: 19 additions & 0 deletions docs/adr/0058-dflash2-mma8-pipeline-adaptive-width.md
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,25 @@ arithmetic (fewer encode boundaries, single-grid streaming): canonical
contention)**, bs3f 34.2 — stacking finally moved the launch-bound
short-round arm.

**2026-09-03 addendum — stacking is for plain `QuantizedLinear` only.**
The stacking helpers admitted their members with `as? QuantizedLinear`,
which also admits subclasses. ParoQuant's `RotateQuantizedLinear` is one:
its forward rotates and channel-scales the input before the quantized
matmul, so folding its `weight`/`scales` into a plain stacked layer kept
the weights and dropped the rotations. First seen the day the
Qwen3.8-27B PARO checkpoint (a text-only load, so the draft paired) went
through the lever: every stacked block decoded garbage (`3333…`), the
bench's greedy identity ruler read 0.2% acceptance, and
`DFLASH2_STACK_GATEUP=0` restored coherent output at once. The guard is
now an exact class check (`plainQuantizedLinear(_:)`): the uniform quant
still stacks all 128 groups; a PARO target stacks only what is plain
(its drafter side is unaffected). Same lesson as R44 in a different
coat — a lever is only bitwise-neutral for the layer class it was
priced on. A load-time depth guard was added in the app beside it
(`DFlash2Support.geometryMatches`): the class check pairs every Qwen3.5
dense size, but the draft only reads the layer depth it was distilled
for.

**R44 addendum — the trajectory-sensitivity constraint.** Fusing the
GDN q/k RMS norms into the scan kernel (mathematically exact, f32
instead of eager's bf16 intermediate roundings, spec==AR MATCH by
Expand Down
42 changes: 28 additions & 14 deletions scripts/graft_mtp_head.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@
Writes `model-mtp-head.safetensors` into the quant dir and rewrites
`model.safetensors.index.json` (a backup of the original index is kept as
`model.safetensors.index.json.pre-mtp`).

Single-file checkpoints without an index (the z-lab PARO releases ship one
`model.safetensors`) get the extra shard only: every loader that matters —
the app's `checkpointShipsMTPHead` header scan, the vendor weight loader,
and the PARO loader's `sourceURLs` — enumerates `*.safetensors` in the
directory when no index exists, so no index is fabricated. Note the PARO
loader's Prepared Checkpoint manifest covers every source shard, so the
graft invalidates it and the next load re-converts once.
"""

import argparse
Expand Down Expand Up @@ -79,12 +87,15 @@ def main() -> int:
args = ap.parse_args()

index_path = args.quant_dir / "model.safetensors.index.json"
if not index_path.exists():
sys.exit(f"no index at {index_path}")
index = json.loads(index_path.read_text())
already = [k for k in index["weight_map"] if k.startswith("mtp.")]
index = json.loads(index_path.read_text()) if index_path.exists() else None
already = [
k
for shard in sorted(args.quant_dir.glob("*.safetensors"))
for k in read_header(shard)
if k.startswith("mtp.")
]
if already:
print(f"index already has {len(already)} mtp.* entries; nothing to do")
print(f"directory already has {len(already)} mtp.* entries; nothing to do")
return 0

tensors = extract_mtp_tensors(args.bf16_shard)
Expand All @@ -96,15 +107,18 @@ def main() -> int:
write_safetensors(out_shard, tensors)
print(f"wrote {out_shard} ({out_shard.stat().st_size / 1e6:.0f} MB)")

shutil.copy2(index_path, index_path.with_suffix(".json.pre-mtp"))
for name in tensors:
index["weight_map"][name] = args.shard_name
if "metadata" in index and "total_size" in index["metadata"]:
index["metadata"]["total_size"] += sum(
len(t["bytes"]) for t in tensors.values()
)
index_path.write_text(json.dumps(index, indent=2))
print(f"patched {index_path.name} (+{len(tensors)} entries)")
if index is None:
print("no index in the quant dir (single-file checkpoint); shard-only graft")
else:
shutil.copy2(index_path, index_path.with_suffix(".json.pre-mtp"))
for name in tensors:
index["weight_map"][name] = args.shard_name
if "metadata" in index and "total_size" in index["metadata"]:
index["metadata"]["total_size"] += sum(
len(t["bytes"]) for t in tensors.values()
)
index_path.write_text(json.dumps(index, indent=2))
print(f"patched {index_path.name} (+{len(tensors)} entries)")

# Round-trip verification: re-read what we wrote.
check = read_header(out_shard)
Expand Down
31 changes: 31 additions & 0 deletions tesseract/Features/Agent/DFlash2Support.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,37 @@ nonisolated enum DFlash2Support {
model is MLXLLM.Qwen35Model || model is Qwen35TextModel
}

/// Depth of the loaded target's layer stack when it pairs
/// (``pairsWithTarget(_:)``), `nil` otherwise. Every pairable class
/// reports its depth through `KVCacheDimensionProvider`.
static func targetLayerCount(_ model: any LanguageModel) -> Int? {
guard pairsWithTarget(model) else { return nil }
return (model as? KVCacheDimensionProvider)?.kvHeads.count
}

/// The draft checkpoint's configuration — the geometry facts
/// (`num_target_layers`, `target_layer_ids`) without the weights.
static func draftConfiguration(directory: URL) throws -> DFlash2Configuration {
let data = try Data(contentsOf: directory.appendingPathComponent("config.json"))
return try JSONDecoder.json5().decode(DFlash2Configuration.self, from: data)
}

/// Whether a draft was distilled for a target of this depth. The class
/// check admits every Qwen3.5 dense size and every PARO checkpoint of
/// the family, but the draft reads hidden states at fixed
/// `target_layer_ids` of a `num_target_layers`-deep stack: bound to a
/// shallower target it would index past the end, to a deeper one it
/// would read layers it never saw. Both are a silent-garbage or trap
/// outcome, so the pairing is refused at load instead.
static func geometryMatches(
targetLayerCount: Int,
draftNumTargetLayers: Int,
draftTargetLayerIds: [Int]
) -> Bool {
targetLayerCount == draftNumTargetLayers
&& draftTargetLayerIds.allSatisfy { $0 < targetLayerCount }
}

// MARK: - Loading

/// Load + 4-bit quantize the draft (reference: `nn.quantize(draft,
Expand Down
24 changes: 19 additions & 5 deletions tesseract/Features/Agent/LLMActor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -769,29 +769,43 @@
guard let directory = DFlash2Support.draftDirectory(storageRoot: storageRoot) else {
return // draft not downloaded — the common case, stay silent
}
let pairs = await container.perform { context in
DFlash2Support.pairsWithTarget(context.model)
let targetLayers = await container.perform { context in
DFlash2Support.targetLayerCount(context.model)
}
guard pairs else {
guard let targetLayers else {
Log.agent.info(
"DFlash2 draft: loaded target class pairs with no DFlash2 draft — off")
return
}
do {
// Geometry comes from config.json, so a mismatched draft is
// refused before its weights are read.
let draftConfig = try DFlash2Support.draftConfiguration(directory: directory)
guard
DFlash2Support.geometryMatches(
targetLayerCount: targetLayers,
draftNumTargetLayers: draftConfig.numTargetLayers,
draftTargetLayerIds: draftConfig.dflash.targetLayerIds)
else {
Log.agent.notice(
"DFlash2 draft: distilled for a \(draftConfig.numTargetLayers)-layer target, "
+ "loaded target has \(targetLayers) layers — off")
return
}
let draft = try DFlash2Support.loadDrafter(directory: directory)
// Same-input QMM stacking (bitwise-exact, ledger R40/R47) on both
// sides of the speculative pair. Non-matching layer classes
// (PARO quant, VLM) fail the QuantizedLinear casts and no-op.
// sides of the speculative pair. Only plain QuantizedLinear folds
// (`plainQuantizedLinear`); a PARO target stacks fewer blocks.
if ProcessInfo.processInfo.environment["DFLASH2_STACK_GATEUP"] != "0" {
let stackedTarget = await container.perform { context in
let n = dflash2StackGateUpProjections(model: context.model)
if n > 0 { MLX.GPU.clearCache() }

Check warning on line 802 in tesseract/Features/Agent/LLMActor.swift

View workflow job for this annotation

GitHub Actions / test

'clearCache()' is deprecated: renamed to 'Memory.clearCache'
return n
}
var stackedDraft = 0
if let draftModule = draft as? Module {

Check warning on line 806 in tesseract/Features/Agent/LLMActor.swift

View workflow job for this annotation

GitHub Actions / test

conditional cast from 'any DFlash2DrafterModel' to 'Module' always succeeds
stackedDraft = dflash2StackGateUpProjections(model: draftModule)
if stackedDraft > 0 { MLX.GPU.clearCache() }

Check warning on line 808 in tesseract/Features/Agent/LLMActor.swift

View workflow job for this annotation

GitHub Actions / test

'clearCache()' is deprecated: renamed to 'Memory.clearCache'
}
Log.agent.notice(
"DFlash2 same-input stacking: target=\(stackedTarget) draft=\(stackedDraft) blocks"
Expand Down
17 changes: 12 additions & 5 deletions tesseract/Features/Models/ModelCatalog.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,18 @@ nonisolated enum ModelCatalog {
return false
}

/// The single vision-detection rule, applied to an on-disk model directory:
/// the Qwen3.5 family with a `vision_config` block (via `ModelIdentity`).
/// Pure given the directory; memoization is the caller's — the download
/// manager holds the per-id cache.
nonisolated static func isVisionCapable(directory: URL) -> Bool {
/// What the checkpoint on disk declares: the Qwen3.5 family with a
/// `vision_config` block (via `ModelIdentity`). An observation, not the
/// capability — that is ``isVisionCapable(definition:directory:)``.
nonisolated static func checkpointDeclaresImageInput(directory: URL) -> Bool {
ModelIdentity(directory: directory).imageKeying != nil
}

/// The **Vision-Capable Model** rule: the checkpoint declares image input
/// *and* the catalog entry carries no **Text-Only Override**. Pure given
/// its inputs; memoization is the caller's — the download manager holds
/// the per-id cache.
nonisolated static func isVisionCapable(definition: ModelDefinition, directory: URL) -> Bool {
!definition.textOnlyOverride && checkpointDeclaresImageInput(directory: directory)
}
}
28 changes: 25 additions & 3 deletions tesseract/Features/Models/ModelDefinition.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ struct ModelDefinition: Identifiable, Sendable {
let sizeDescription: String
let dependencies: [String]
var companionFiles: [CompanionFile] = []
/// The **Text-Only Override** (CONTEXT.md): the entry withholds the image
/// input its checkpoint declares, so the app serves it text-only — no
/// image affordances, the text-class load, no image keying. Today's use is
/// the two Qwen3.8-27B entries: DFlash2 pairs only with the MLXLLM text
/// classes, and a vision-mode load would silently never speculate. Lifted
/// by map #457 once the VLM wrapper hosts the MLXLLM engine (#459).
var textOnlyOverride: Bool = false

var cacheSubdirectory: String? {
guard case .huggingFace(let repo, _, _) = source else { return nil }
Expand Down Expand Up @@ -242,24 +249,39 @@ extension ModelDefinition {
sizeDescription: "~16 GB",
dependencies: []
),
ModelDefinition(
id: "qwen3.8-27b-paro",
displayName: "Qwen3.8-27B PARO",
description:
"Dense 27B agent built on Qwen3.8 with pairwise-rotation INT4 (near-FP16 accuracy). Served text-only for now so the DFlash2 draft engages; image input returns with #457. Requires a high-memory Mac (48 GB+ recommended); the first load writes a ~19 GB Prepared Checkpoint beside the download.",
category: .agent,
source: .huggingFace(
repo: "z-lab/Qwen3.8-27B-PARO",
requiredExtension: "safetensors"
),
sizeDescription: "~19 GB",
dependencies: ["qwen3.8-27b-dflash2-draft"],
textOnlyOverride: true
),
ModelDefinition(
id: "qwen3.8-27b",
displayName: "Qwen3.8-27B (MLX 4bit)",
description:
"Dense 27B agent from the Qwen3.8 generation (uniform 4-bit MLX, vision-capable). Requires a high-memory Mac (48 GB+ recommended). Ships as qwen3_5.",
"Dense 27B agent from the Qwen3.8 generation (uniform 4-bit MLX). Served text-only: its legacy tensor layout loads as the text class, which is also what the DFlash2 draft pairs with; image input returns with #457. Requires a high-memory Mac (48 GB+ recommended). Ships as qwen3_5.",
category: .agent,
source: .huggingFace(
repo: "mlx-community/Qwen3.8-27B-4bit",
requiredExtension: "safetensors"
),
sizeDescription: "~16 GB",
dependencies: ["qwen3.8-27b-dflash2-draft"]
dependencies: ["qwen3.8-27b-dflash2-draft"],
textOnlyOverride: true
),
ModelDefinition(
id: "qwen3.8-27b-dflash2-draft",
displayName: "Qwen3.8-27B DFlash2 Draft",
description:
"Block-parallel speculative-decoding draft for Qwen3.8-27B (incoai/Qwen3.8-27B-DFlash2). Downloads alongside the target and accelerates decode ~3× at greedy and sampling presets alike. Never usable on its own.",
"Block-parallel speculative-decoding draft for Qwen3.8-27B (incoai/Qwen3.8-27B-DFlash2). Downloads alongside either Qwen3.8-27B target and accelerates decode ~2× at greedy and sampling presets alike. Never usable on its own.",
category: .draft,
source: .huggingFace(
repo: "incoai/Qwen3.8-27B-DFlash2",
Expand Down
6 changes: 4 additions & 2 deletions tesseract/Features/Models/ModelDownloadManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,10 @@ final class ModelDownloadManager: ObservableObject {
/// Capability Memo**. Replaces the stranded `ModelVisionCapability` class.
func isVisionCapable(_ id: String) -> Bool {
if let cached = visionCache[id] { return cached }
guard isDownloaded(id), let directory = modelPath(for: id) else { return false }
let capable = ModelCatalog.isVisionCapable(directory: directory)
guard isDownloaded(id), let directory = modelPath(for: id),
let definition = definitions.first(where: { $0.id == id })
else { return false }
let capable = ModelCatalog.isVisionCapable(definition: definition, directory: directory)
visionCache[id] = capable
return capable
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ nonisolated enum IntegrationSnapshotBuilder {
.map { definition in
let visionCapable =
modelDirectory(definition.id)
.map(ModelCatalog.isVisionCapable(directory:)) ?? false
.map { ModelCatalog.isVisionCapable(definition: definition, directory: $0) }
?? false
return IntegrationSnapshot.Model(
id: definition.id,
displayName: definition.displayName,
Expand Down
16 changes: 9 additions & 7 deletions tesseractTests/AgentGenerateParametersTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,15 @@ struct AgentGenerateParametersTests {
// Qwen3.8's card recommends temp 1.0 / top_p 0.95 / top_k 20 with
// presence_penalty 0.0 in thinking mode — must not fall through to
// the generic `qwen3` instruct profile (temp 0.7, presence 1.5).
let params = AgentGenerateParameters.forModel("qwen3.8-27b")
#expect(params.temperature == 1.0)
#expect(params.topP == 0.95)
#expect(params.topK == 20)
#expect(params.presencePenalty == nil)
#expect(params.repetitionPenalty == nil)
#expect(params.thinkingSafeguard.enabled == true)
for id in ["qwen3.8-27b", "qwen3.8-27b-paro"] {
let params = AgentGenerateParameters.forModel(id)
#expect(params.temperature == 1.0, "\(id)")
#expect(params.topP == 0.95, "\(id)")
#expect(params.topK == 20, "\(id)")
#expect(params.presencePenalty == nil, "\(id)")
#expect(params.repetitionPenalty == nil, "\(id)")
#expect(params.thinkingSafeguard.enabled == true, "\(id)")
}
}

@MainActor
Expand Down
Loading
Loading