Skip to content

Ek/thinking eos - #1

Merged
ekryski merged 6 commits into
ek/consolidatedfrom
ek/thinking-eos
Mar 29, 2026
Merged

ekryski merged 6 commits into
ek/consolidatedfrom
ek/thinking-eos

Conversation

@ekryski

@ekryski ekryski commented Mar 29, 2026

Copy link
Copy Markdown
Owner

Proposed changes

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

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)

ekryski added 6 commits March 29, 2026 12:41
- ThinkingEOSSuppressionProcessor prevents premature EOS during thinking
- Expanded tool call integration tests for Qwen3.5 edge cases
- Fixed Qwen3.5 chat template test assertions
Models like Qwen3.5 and Nemotron tokenize </think> as multiple tokens
(e.g., <, /think, >) rather than a single special token. The original
single-token trigger never fires for these models.

Add a new initializer that accepts a triggerSequence (array of token IDs).
The processor maintains a rolling buffer of recent tokens and fires the
suppression window when the buffer matches the full sequence.

Both initializers are backward-compatible — single-token trigger still
works for models with </think> as a special token.
The existing ThinkingEOSSuppressionProcessor uses token-level detection
(single ID or sequence match) to trigger EOS suppression after </think>.
This fails for models where </think> tokenizes differently in context
vs standalone (e.g., BOS prefix from encode()).

EOSSuppressionTrigger is a reference-type (class) processor that gets
triggered externally by the generation loop when it detects </think>
via text matching. This is more reliable because:
1. No dependency on tokenizer.encode() matching generation tokens
2. The text-based BudgetClassifier already reliably detects </think>
3. Class reference allows mutation from outside the generate() function
Two critical bugs fixed:

1. Logit indexing: logits[eosId] was indexing the batch dimension (dim 0)
   instead of the vocabulary dimension (dim 1) for 2D logits [1, V].
   This meant EOS logits were never actually set to -inf, so the model
   kept sampling EOS tokens after </think>. Fixed to use logits[0..., eosId]
   for 2D arrays.

2. Thread safety: EOSSuppressionTrigger is a reference type (class) shared
   between the generation loop (consumer) and TokenIterator (producer).
   Added NSLock to protect triggered/tokensSinceTrigger state.

Also fixed the same 2D indexing bug in ThinkingEOSSuppressionProcessor.
@ekryski
ekryski merged commit 8f788d4 into ek/consolidated Mar 29, 2026
TheTom referenced this pull request in TheTom/mlx-swift-lm Apr 5, 2026
don't need ninja as we don't have a cmake build
TheTom referenced this pull request in TheTom/mlx-swift-lm Apr 5, 2026
ekryski added a commit that referenced this pull request Apr 10, 2026
Documents what asyncEval actually does internally:
- Graph DFS traversal (~0.5ms)
- Topological sort BFS (~0.3ms)
- Tape execution with Metal encoding (~8-9ms)
- Memory pressure check that BLOCKS if active_memory > memory_limit

The memory pressure blocker is likely the #1 source of the ~8ms stall:
asyncEval stops encoding and waits for GPU to free memory mid-loop.
Memory limit = min(1.5 × recommendedMaxWorkingSetSize, 0.95 × systemRAM).

Adds comprehensive 'How to Make It Faster' summary with 5 optimization
pillars: reduce weight reads, reduce ops, adaptive command buffers,
CPU/GPU overlap, and fixing the asyncEval memory pressure blocking.
Includes theoretical floor (2.5ms/400tok/s), achievable target
(4-5ms/200-250tok/s), and current state (12ms/80-90tok/s).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@ekryski
ekryski deleted the ek/thinking-eos branch April 16, 2026 23:23
ekryski added a commit that referenced this pull request Apr 20, 2026
Decode-loop ICB orchestrator now drives the override path for
every per-step scalar that used to be mutated inside a persistent
AB (SDPA N, RoPE offset, gather indices, K/V write positions).
Matched to the mlx + mlx-swift submodule bumps that lift those
values out of the AB into kernel slot 1 bindings, so
`replay(overrides:)` rewires slot 1 per step via the tag-binding
path — race-free with in-flight GPU work.

Per-step wiring:
- icbSdpaNBinding(layer:) names registered on every live SDPA
  handle before recordWithBindings; each replay step installs a
  fresh MLXArray([Int32(tk)]) override per layer, dedup'd by
  value (layers sharing T_k share one allocation).
- icbRopeOffsetBinding (single shared name) registered on every
  live RoPE / RoPE-freqs handle; each step installs one
  MLXArray([ropePosition]) override.
- icbGatherIndicesBinding registered on the 3 gather_front_ab
  handles the orchestrator already pushes before recording; each
  step installs one override for the current input-token buffer.

Pre-record correctness fix:
- Before entering pin.record, call
  Stream.synchronizeAllGpuStreams() — `defaultStream.synchronize()`
  only drains ONE stream, while GPT-OSS 20B hits stream index 0
  ~2250x per token for secondary-stream work. MLX_DECODE_STREAM_AUDIT=1
  confirmed those writes overlap with the record step and caused
  the "step-3 ICB diverges from live" bug called out in
  icb-decode-loop-checkpoint-2026-04-19.md (hypothesis #1). With
  this drain in place, record-replay tokens match live exactly
  through all replay steps under greedy sampling.

Post-replay sync kept:
- `Stream.defaultStream(.gpu).synchronize()` after
  `replay(overrides:)` stays on by default. The proposal's claim
  that the sync could be dropped once per-step state moved to
  override-bound bindings turns out to be wrong: `setKernelBuffer`
  on the recorded ICB's commands mutates the ICB in place, and
  Metal does NOT snapshot the ICB at executeCommandsInBuffer
  time — in-place mutation races the GPU's command reads. Without
  the sync, identical inputs yield different token streams across
  runs (empirically verified). Opt-out via
  MLX_ICB_POST_REPLAY_SYNC=0 for experimentation.

Throughput on GPT-OSS 20B 4-bit, M1 Max, greedy (3 runs each):
- Live baseline (plain AB):   48.7 / 49.7 / 49.8 tok/s, coherent
- Decode-loop ICB (this):     44.5 / 42.2 / 44.4 tok/s, coherent

Up from ~42 tok/s pre-refactor (incoherent). Still ~5 tok/s
behind plain because the sync is required and the ~2ms/step
overhead (useResource sweep, override MLXArray alloc, 180
setKernelBuffer calls) is inherent to the ICB+override model.
Double-buffering would not beat plain — GPU is the bottleneck
and live already hits the GPU ceiling. See
benchmarks/notes/icb-decode-loop-checkpoint-2026-04-19.md +
icb-persistent-ab-refactor-proposal.md for the full analysis.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski added a commit that referenced this pull request May 6, 2026
#1, issue #168)

Lift the Gemma 3 text-decoder layer stack into a public
`Gemma3` namespace under `MLXLMCommon/Models/Gemma3.swift`.
Both targets now consume the shared types:

  Libraries/MLXLMCommon/Models/Gemma3.swift  ←  shared
    - public enum Gemma3
    - public struct Gemma3.TextConfiguration   (handles flat + nested
                                                `text_config` JSON)
    - public class  Gemma3.Attention           (uses applyRotaryPosition;
                                                supports BatchPositionedKVCache
                                                via the helper)
    - public class  Gemma3.MLP
    - public class  Gemma3.TransformerBlock
    - public class  Gemma3.Backbone            (embed → N blocks → norm,
                                                accepts `inputs` OR
                                                `inputEmbedding` for
                                                vision-fusion)

  Libraries/MLXLLM/Models/Gemma3.swift        ← (renamed from
                                                Gemma3Text.swift)
    - thin Gemma3TextModel: LLMModel wrapper
    - back-compat typealias for Gemma3TextConfiguration

  Libraries/MLXVLM/Models/Gemma3.swift        ← stripped 350+ lines
    - drops the duplicated private Attention/MLP/TransformerBlock/
      GemmaModel
    - LanguageModel now wraps Gemma3.Backbone, adds Linear-or-
      QuantizedLinear lm_head dispatch + final-logit softcapping
    - drops the dead `hasQuantizedLmHead` quant gate (per issue #170
      cleanup — quantization is applied via the top-level
      `quantize(model:)` block in Load.swift driven by
      `BaseConfiguration.PerLayerQuantization`)
    - shared-namespace references qualified with `MLXLMCommon.` to
      disambiguate from the local `public class Gemma3` outer model
    - prepare gains the same hard `eval(cacheArrays + [result.logits])`
      barrier as Gemma 4 VLM (issue #169 fix in 4f6c9b7) — the
      pre-consolidation private `GemmaModel` happened to mask the
      prefill-sync issue; the consolidated Backbone surfaces it the
      same way Gemma 4 VLM did

Net diff: +542 / -347 lines (~200-line reduction net of the new
namespace file).

Verification (alpha @ this commit):
- `swift build` clean across MLXLMCommon, MLXLLM, MLXVLM.
- `swift test --configuration release` = 203/204 (the 1 failure is
  the env-driven InferenceBenchmark scaffold, pre-existing).
- `gemma-3-1b-it-qat-4bit --method simple` →
  "Hello! I'm Gemma..." (121 tok/s)
- `gemma-3-4b-it-qat-4bit --method simple` →
  "Hello! My name is Gemma..." (83 tok/s)
- `gemma-3-4b-it-qat-4bit --method vision` →
  "Okay, here's a description of the image:..." (89 tok/s, validation
  passes — keyword "dog" in 200-token output)
- `gemma-3-1b --method summarization 1024 --kv affine4` →
  "The..." continuation (124 tok/s)
- `gemma-3-4b --method summarization 1024 --kv affine4` →
  "Okay, here's a summary..." (42 tok/s)

Closes WS-C #1 of issue #168 sprint plan.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski added a commit that referenced this pull request May 8, 2026
feat(gemma3): consolidate text decoder into MLXLMCommon namespace (WS-C #1)
ekryski added a commit that referenced this pull request May 12, 2026
Spec was originally written as a multi-phase plan with phase 1 (protocol)
landing first and phases 2 (kernel) / 3 (iterator) deferred to follow-ups.
The actual implementation consolidated phases 1-3 into PR #143 with a
4-repo native-kernel chain (mlx#26 → mlx-c#14 → mlx-swift#25 → mlx-swift-lm#143).

Status header now reflects:
  - Phases 1+2+3: DONE, GDN coverage (Qwen 3.5 / 3.6) live.
  - Phase 4 (DFlash iterator): DEFERRED — picks up when spec 015 phase 1 merges.
  - Phase 5 (PrefixKVCache): DEFERRED — picks up on spec 017's branch.
  - Mamba / Mamba 2: opted out via canStateReplay=false; future-work options
    ranked in §"Mamba / Mamba 2 follow-up (post-MVP)".

Risks section audited against the actual implementation — every risk now
has an explicit "mitigated" or "deferred + how" note:
  - #1 fp32 numerical equivalence: mitigated via state-in-fp32 throughout
    the recurrence; 4 equivalence tests lock it.
  - #2 memory pressure cap: no longer needed after Option A's per-round
    recording (50ba77f); 30 entries per round, not 360.
  - #3 Mamba variants: opted out cleanly; future work documented.
  - #4 spec-006 hierarchy: integration complete, no friction.
  - #5 masked-timestep correctness: kernel adopts 3217e15 pattern from
    day 1; verified at gated_delta_replay.metal:200-216. Gap noted:
    masked-replay unit test deferred (no live caller passes mask != nil).
  - #6 branchless discipline: c9f992e pattern adopted.
  - #7 NEW — off-by-one in iterator → protocol translation: documented
    with the fix and its bench impact (35B-A3B D=12 acceptance 34% → 92%).

Files-touched table rewritten with final paths + the 4-repo chain split.
Iterator-changes pseudo-code updated to match the shipped single-dispatch
shape (helper routes full vs partial accept internally) and the +1
translation is now called out explicitly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski added a commit that referenced this pull request May 12, 2026
Spec was originally written as a multi-phase plan with phase 1 (protocol)
landing first and phases 2 (kernel) / 3 (iterator) deferred to follow-ups.
The actual implementation consolidated phases 1-3 into PR #143 with a
4-repo native-kernel chain (mlx#26 → mlx-c#14 → mlx-swift#25 → mlx-swift-lm#143).

Status header now reflects:
  - Phases 1+2+3: DONE, GDN coverage (Qwen 3.5 / 3.6) live.
  - Phase 4 (DFlash iterator): DEFERRED — picks up when spec 015 phase 1 merges.
  - Phase 5 (PrefixKVCache): DEFERRED — picks up on spec 017's branch.
  - Mamba / Mamba 2: opted out via canStateReplay=false; future-work options
    ranked in §"Mamba / Mamba 2 follow-up (post-MVP)".

Risks section audited against the actual implementation — every risk now
has an explicit "mitigated" or "deferred + how" note:
  - #1 fp32 numerical equivalence: mitigated via state-in-fp32 throughout
    the recurrence; 4 equivalence tests lock it.
  - #2 memory pressure cap: no longer needed after Option A's per-round
    recording (50ba77f); 30 entries per round, not 360.
  - #3 Mamba variants: opted out cleanly; future work documented.
  - #4 spec-006 hierarchy: integration complete, no friction.
  - #5 masked-timestep correctness: kernel adopts 3217e15 pattern from
    day 1; verified at gated_delta_replay.metal:200-216. Gap noted:
    masked-replay unit test deferred (no live caller passes mask != nil).
  - #6 branchless discipline: c9f992e pattern adopted.
  - #7 NEW — off-by-one in iterator → protocol translation: documented
    with the fix and its bench impact (35B-A3B D=12 acceptance 34% → 92%).

Files-touched table rewritten with final paths + the 4-repo chain split.
Iterator-changes pseudo-code updated to match the shipped single-dispatch
shape (helper routes full vs partial accept internally) and the +1
translation is now called out explicitly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski added a commit that referenced this pull request May 12, 2026
Spec 020 (state-replay rollback at the cache layer) landed 2026-05-11
via PR #143 + the 4-repo cross-repo native kernel chain. Updates the
implementation plan to reflect:

  - Tier 1 row #5: ✅ SHIPPED with measured wins (Qwen3.5-35B-A3B-4bit
    D=12 adapt+strict 1.64× baseline at 92% accept).
  - Tier 2 row #10a (Spec 030 MTP): Variant A on hybrid Qwen no longer
    waits on Tier 1 — unblocked.
  - Tier 3 row #11 (Spec 015 DFlash): phase 3 prerequisite landed —
    now blocked only on draft-model availability, not on the rollback
    primitive.
  - Dependency graph: 020's "downstream unblocks" inlined.
  - Decision point #1: gate passed (fp32 state throughout the GDN
    recurrence; 7 equivalence tests lock it).
  - Decision point #3: prerequisite landed.
  - Status snapshot: "Tier 1 work — state-replay #143 phases 2-3"
    line replaced with the shipped milestone; "remaining Tier 1 item"
    is now prefix cache #144 phase 1B alone.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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.

1 participant