Skip to content

Fix LFM2.5 VL tools - #139

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
viktike:LFM25VL
Mar 10, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
viktike:LFM25VL

Conversation

@viktike

@viktike viktike commented Mar 10, 2026

Copy link
Copy Markdown
Contributor

The model's chat template never received the list of tools from the request, so it never called one.

Proposed changes

Please include a description of the problem or feature this PR is addressing. If there is a corresponding issue, include the issue #.

This chat template expects tools: https://huggingface.co/mlx-community/LFM2.5-VL-1.6B-4bit/blob/main/chat_template.jinja
Since Pythonic tool parser is already implemented, this made sense.

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

The model's chat template never received the list of tools from the request, therefor never called one.

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good and it also looks like a lot of models are missing this (not all support tools of course).

@davidkoski
davidkoski merged commit a4a7247 into ml-explore:main Mar 10, 2026
2 checks passed
davidkoski added a commit that referenced this pull request Mar 10, 2026
@davidkoski davidkoski mentioned this pull request Mar 10, 2026
2 of 4 tasks
davidkoski added a commit that referenced this pull request Mar 26, 2026
davidkoski added a commit that referenced this pull request Mar 26, 2026
* add missing context/toolcall parameters

- see #139
TheTom referenced this pull request in TheTom/mlx-swift-lm Apr 5, 2026
The model's chat template never received the list of tools from the request, therefor never called one.
TheTom referenced this pull request in TheTom/mlx-swift-lm Apr 5, 2026
* add missing context/toolcall parameters

- see ekryski#139
solderzzc added a commit to SharpAI/mlx-swift-lm that referenced this pull request Aug 26, 2026
* feat: implement the DSA lightning indexer (stage 2)

Follow-up to #111's stage 1 (dual-cache dense attention). Implements the
sparse indexer that restricts attention to the top index_topk cached
positions past that threshold, per mlx_lm's deepseek_v32.py /
glm_moe_dsa.py reference.

## What's new

- DeepseekV32Indexer: the lightning indexer (wq_b/wk/k_norm/weights_proj),
  scoring cached keys against the query and returning the top-k selection,
  or nil below index_topk (matching the reference's own inertness rule).
- DeepseekV32Attention: a DeepseekV3Attention-shaped attention block (same
  weight keys/shapes) plus the indexer, applying its selection as a
  boolean mask ANDed with the causal mask.
- Paired CacheList(main, indexer) caches per layer, matching FalconH1's
  established two-cache pattern and the reference's own
  CacheList(KVCache(), KVCache()) per layer. Both children are
  KVCacheSimple, so canTrimPromptCache/trimPromptCache keep working.
- DeepseekV32Model is now standalone rather than subclassing
  DeepseekV3Model — needed once its `model` property had to become a
  DeepseekV32ModelInner (paired-cache layers) rather than
  DeepseekV3ModelInner. Reuses DeepseekV3MLP/DeepseekV3MoE/MoEGate
  unchanged via args.v3Configuration; only attention/cache forked.
- indexer_rope_interleave is now decoded and honored (was silently
  ignored — dead JSON since stage 1 had no indexer to apply it to).
- sanitize keeps .indexer. weights (a real module now loads them);
  still drops .attn.compressor. (a separate, still-unimplemented
  long-range-compression feature some checkpoints in this family carry).

## Design decision: boolean mask instead of absorbed-MLA gather

The reference's DeepseekV32Attention decode path gathers only the
selected latent/rope entries because it keeps K/V in absorbed per-token
latent form until attention time. This port's DeepseekV3Attention-derived
structure (inherited unchanged from stage 1) materialises full per-head
K/V before attention, so instead of gathering, the top-k selection is
applied as a boolean mask over the existing dense SDPA call — masking
non-selected positions in a full attend-over-everything call is
numerically identical to attending only the gathered subset, just
without the compute/memory saving. This also means one code path is
correct for both prefill and decode, rather than the reference's
separate L==1/L>1 branches. Documented at length in the file header for
reviewer attention, per ml-explore#139's explicit callout that absorbed MLA is
where scrutiny should go.

## Tests (no real checkpoint — smallest glm_moe_dsa checkpoint is 308GB)

- Forward pass finite/shape-correct (existing, still passes unchanged).
- Sparse path engages past index_topk, stays finite, AND diverges from
  a same-weights dense run (proves the mask has a real effect, not just
  that nothing crashed).
- Inertness: below index_topk, output exactly matches a same-weights
  model whose index_topk is effectively infinite. Weights are shared via
  Module.update(parameters:) rather than MLXRandom.seed() reproduction —
  swift-testing runs tests concurrently by default, and seed() is
  global mutable state, so two reseed-then-construct calls raced with
  other tests' unseeded construction and were not reliably reproducible
  (verified empirically: passed in isolation, failed as part of the
  full suite).
- sanitize updated: indexer weights now kept, compressor still dropped.

All 130+ tests across the full mlx-swift-lm suite still pass (verified
locally — no regressions in DeepseekV3-derived or DeepseekV4 tests, the
latter being an unrelated but structurally similar architecture).

## Still open (out of scope here, flagged for follow-up)

- No real-weights verification yet (per #111/ml-explore#139: first real run should
  use avlp12/GLM-5.2-Alis-MLX-Dynamic-3.5bpw with --stream-experts).
- Quantized KV cache is not wired up for the new CacheList-based
  newCache override (matches stage 1's behavior — this was never wired
  for DeepseekV32Model regardless of stage).

* fix: address correctness bugs found in review of the DSA indexer PR

A code review found 5 confirmed issues in the DSA stage-2 implementation
(previous commit). Cross-checked each against FalconH1 (the established
CacheList precedent this code follows) to separate genuinely new bugs
from pre-existing limitations of the paired-cache pattern that FalconH1
already has too.

## Fixed (genuine bugs, not shared by FalconH1)

- **Critical**: the causal mask was built from `mainCache.offset` *after*
  `mainCache.update(...)` had already run — `KVCacheSimple.update`
  mutates `.offset` as its first side effect, so every mask built from it
  here was sized one batch too wide against the actual key count. This
  crashed on a broadcast/shape mismatch the moment any real (non-nil)
  cache was used past `index_topk` — every existing test passed
  `cache: nil`, which trivially collapses `mainCache?.offset ?? 0` to 0
  in both the buggy and correct forms, so nothing caught it. Fixed by
  capturing the offset once before the update call. Verified red/green:
  temporarily reintroducing the bug reproduces the exact predicted
  broadcast crash against the new real-cache test below.
- `newCache(parameters:)` now honors `parameters.maxKVSize`, building a
  `RotatingKVCache` pair instead of unbounded `KVCacheSimple` when set —
  this model doesn't get `KVCacheDimensionProvider`'s default behavior
  for free once its cache shape became a `CacheList` pair, so it has to
  be handled explicitly (FalconH1's own `newCache` has the identical gap
  and was not the pattern to follow here).
- `callAsFunction`'s `cache as? [CacheList]` cast silently discarded a
  type-mismatched cache and ran with no cache at all (a silent "the
  model forgot everything" failure, worse than a crash). Now fails
  loudly with a clear message instead.
- Efficiency: the sparse-mask branch recomputed a causal mask on every
  decode step (`L == 1`) even though a length-1 causal mask is provably
  a no-op there — skipped entirely instead of materialising and ANDing
  a mask that can never change the result.

## Documented, not fixed here (pre-existing, shared by FalconH1)

`attentionWithCacheUpdate(cache: nil, ...)` — needed because the cache
is manually pre-updated above to size the top-k mask — opts this model
out of TurboKV's compressed-history decode/prepend and
QuantizedKVCacheProtocol routing, both of which only engage on a
non-nil cache. Confirmed FalconH1 has the identical gap (it doesn't
even route through `attentionWithCacheUpdate` at all for its own
CacheList-paired attention). KV-quantization (`--kv-bits`) also
silently no-ops for any `CacheList`-based model, confirmed via
`maybeQuantizeKVCache`'s own comment ("MambaCache and CacheList don't
use traditional KV quantization"). Making the CacheList pattern itself
TurboKV/quantization-aware is a cross-cutting change affecting every
paired-cache model in the codebase, not scoped to this PR — documented
in code comments at the call site instead of silently left unexplained.

## Tests

- New: real (non-nil) cache test — prefill past index_topk in one call,
  then one decode step — exercising both offset-read sites the bug
  lived in. Red-green verified against the reintroduced bug.
- New: newCache honors maxKVSize, confirming RotatingKVCache for both
  cache-pair slots when set (and KVCacheSimple, the previous default,
  when not).
- Full suite: 132/132 passing (was 130 before this PR's tests, +2 here),
  zero regressions.

---------

Co-authored-by: Aegis AI Assistant <simba@aegis-ai.dev>
davidtai pushed a commit to davidtai/mlx-swift-lm that referenced this pull request Oct 6, 2026
…plore#139)

* feat(cbv2): per-request timing, cumulative step counters, step signposts

Export `CBv2RequestTiming` on the terminal `CBv2Usage` (numerics only:
nanosecond offsets from the engine enqueue instant plus step-participation,
prefill-chunk, MTP, pause, detok-delay and prefix-cache counters), stamped
on `CBv2ScheduledRequest` from the step's existing clock reads:

- enqueue: one `DispatchTime` read is the origin of every offset
- launch (`executeMixed` / `executeMTPRound`): admission, KV allocation
  and prefill-chunk stamps reuse `wallStartedNanos`; one-token prompts are
  decode-shaped but still counted as the row's prefill chunk
- finalize: ONE new unconditional read (readback-done) serves every
  per-row stamp (first token / prompt computed, batch rows, step latency,
  decode steps), the MTP accept walk, `finishedNanos` for finishes driven
  by that finalize, and the cumulative `stepWallNanosTotal`
- markAdmitted counts re-admissions; ensureKVState counts capacity
  requeues; setPaused accumulates paused time on the injectable clock
- prefix lookup is timed on the submit thread and rides `CBv2PrefixLookup`
  into enqueue; `applyAdoption` is timed once per adoption
- first-token detok delay is measured inside `CBv2OutputStream`'s own lock
  (armed by `reserveEmission`, read by the deferred `emit`) and folded into
  the usage at terminal delivery; the scheduler record is never written
  from the detokenization queue

`CBv2CapacitySnapshot` gains monotonic `stepWallNanosTotal` and
`decodeRowsTotal`, published under the existing gauges lock. `engineStep`
is wrapped in an `OSSignposter` "step" interval guarded by `isEnabled`.

`CBv2Usage.timing` is stored boxed: the Swift 6.3 runtime frees `async let`
result buffers above a size threshold out of order ("freed pointer was not
the last allocation"), reproduced on the unmodified engine by padding a
test result struct; keeping `CBv2Usage` one pointer larger avoids it.

No new locks, evals or per-row clock reads on the step path; hostSyncs
unchanged. Tests: `CBv2RequestTimingTests` (B=1, B=4, chunked/striped
prefill, stop-string path, preemption, backpressure, prefix hit, monotonic
counters, Equatable + numeric-only shape).

* fix(cbv2): order kv_allocated after admission, restore markAdmitted lookup, align MTP admission stamp

* fix(cbv2): share boundary clock reads, drop MTP vision allocation, saturate counters, count host syncs

* fix(cbv2): gate host-sync counting behind a test-enabled flag, drop racy core-test expectation

* fix(cbv2): count logprob and serial-verify syncs, share paused-finish clock read, one timing box per request, exact hasSpans

* fix(cbv2): count the MTP capture-fence fallback eval as a host sync

* perf: implement and validate GPT-OSS prefill and decode candidates

* perf: enable final-position prefill and bounded 20B expert fusion

* build: pin MLX Swift constant-cache and Metal integration

* fix: round-trip saved fused GPT-OSS checkpoint layouts

* fix: preserve fused checkpoint quantization policies on rollback

* build: pin MLX Swift with merged native dependencies

* build: pin stream-aware quantized constant cache fix

* build: pin merged MLX Swift optimizations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants