Skip to content

feat(qwen2): consolidate text decoder into MLXLMCommon namespace (WS-C #4) - #175

Merged
ekryski merged 1 commit into
alphafrom
ek/wsc4-qwen2-consolidation
May 8, 2026
Merged

ekryski merged 1 commit into
alphafrom
ek/wsc4-qwen2-consolidation

Conversation

@ekryski

@ekryski ekryski commented May 6, 2026 •

Copy link
Copy Markdown
Owner

Fourth of 8 model-family consolidation PRs from issue #168. Highest-
leverage consolidation in the sprint — 4 targets were carrying
independent copies of essentially the same Qwen 2 layer stack:

  • MLXLLM/Models/Qwen2.swift — the canonical Qwen 2 LLM
  • MLXVLM/Models/Qwen2VL.swift — Qwen 2 Vision-Language
  • MLXVLM/Models/Qwen25VL.swift — Qwen 2.5 Vision-Language
  • MLXVLM/Models/FastVLM.swift — Apple's FastVLM (uses Qwen 2 backbone)

What's shared

  • Qwen2.LayerArgs — adapter struct (same pattern as Mistral 3 feat(mistral3): consolidate text decoder into MLXLMCommon namespace (WS-C #3) #174)
  • Qwen2.Attention — uses applyRotaryPosition; supports linear-scaling RoPE. The dead mropeSection field that Qwen2VL / Qwen25VL computed but never read in the language-side attention is dropped.
  • Qwen2.MLP
  • Qwen2.DecoderLayer
  • Qwen2.ModelInner — supports inputEmbedding for VLM vision-fusion

Per-target wrappers

  • MLXLLM/Models/Qwen2.swift: Qwen2Model: LLMModel, optional Linear lm_head or tied embedding. Configuration retains all original fields + new var layerArgs accessor.
  • MLXVLM/Models/Qwen2VL.swift, Qwen25VL.swift, FastVLM.swift: Language.LanguageModel shrinks to wrap Qwen2.ModelInner. Each TextConfiguration adds a var layerArgs: Qwen2.LayerArgs adapter. Preemptive prefill-sync eval() barriers added to all three VLM prepare methods (mirroring PR #172).

Net diff: +352 / -704 lines (~352-line reduction across 5 files).

Verification

  • swift build clean across MLXLMCommon, MLXLLM, MLXVLM
  • swift test --configuration release: 203/204 (the 1 "failure" is the env-driven InferenceBenchmark.benchmark() scaffold; pre-existing).
  • LLM smoke mlx-community/Qwen2.5-7B-Instruct-8bit --method simple (MLX_BENCH_PROMPT="What is your name?"): "I am Qwen, a large language model from Alibaba Cloud." (35 tok/s)
  • VLM smoke deferred — no cached Qwen2VL / Qwen25VL / FastVLM checkpoints locally. Build-pass + LLM smoke confirm the shared-type wiring is correct (the three VLM consumers have identical LanguageModel patterns now). Reviewer should run a Qwen 2 / 2.5 VL / FastVLM smoke before merge if available.

…#4, issue #168)

Lifts the Qwen 2 text-decoder layer stack into a public `Qwen2`
namespace under `MLXLMCommon/Models/Qwen2.swift`. Four targets
consume the shared types:
- MLXLLM/Models/Qwen2.swift
- MLXVLM/Models/Qwen2VL.swift
- MLXVLM/Models/Qwen25VL.swift
- MLXVLM/Models/FastVLM.swift

The four targets had FOUR independent copies of essentially the same
code (Attention, MLP, *DecoderLayer, *Model). Highest-leverage
consolidation in the sprint.

Adapter pattern (same as Mistral 3): each target's TextConfiguration
adds a computed `var layerArgs: Qwen2.LayerArgs` accessor. Configs
stay separate (different field-name conventions and Qwen-2.5-specific
fields like slidingWindow); shared layer classes take the adapter.

Shared:
- `Qwen2.LayerArgs` (adapter)
- `Qwen2.Attention` (uses applyRotaryPosition; supports linear-scaling
  RoPE — the dead `mropeSection` field that 2 of the 3 VLMs computed
  but never used is dropped)
- `Qwen2.MLP`
- `Qwen2.DecoderLayer`
- `Qwen2.ModelInner` (supports `inputEmbedding` for VLM vision-fusion)

Per-target wrappers:
- LLM `Qwen2Model: LLMModel` (optional Linear lm_head or tied embed)
- VLM `Language.LanguageModel` (3 instances; same pattern as LLM but
  returns `LMOutput`); preemptive prefill-sync `eval()` barriers added
  to all three VLM `prepare` methods.

Net diff: +352 / -704 (~352-line reduction across 5 files).

Verification:
- swift build clean across MLXLMCommon, MLXLLM, MLXVLM
- swift test --configuration release: 203/204 (1 pre-existing
  benchmark scaffold failure)
- LLM smoke `mlx-community/Qwen2.5-7B-Instruct-8bit --method simple`
  with explicit "What is your name?" prompt:
  "I am Qwen, a large language model from Alibaba Cloud." (35 tok/s)
- VLM smoke deferred (no cached Qwen2VL / Qwen25VL / FastVLM
  checkpoints locally); build-pass + LLM smoke confirm the shared-
  type wiring is correct.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@github-actions github-actions Bot added the feature New feature (auto-applied from feat: prefix) label May 6, 2026
@ekryski ekryski added enhancement New feature or request and removed feature New feature (auto-applied from feat: prefix) labels May 8, 2026
@ekryski
ekryski merged commit 107da77 into alpha May 8, 2026
5 checks passed
@ekryski
ekryski deleted the ek/wsc4-qwen2-consolidation branch May 8, 2026 00:26
@github-actions github-actions Bot added the feature New feature (auto-applied from feat: prefix) label Nov 24, 2026
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…#175)

* style: format DiffusionGemmaVisionOracleTests.swift

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: format DiffusionGemmaFactoryTests.swift

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: run bit-exact reference tests only on reference hardware

Nine DiffusionGemma tests compare float bits with frozen references.
On the hosted macos-26 runner (Apple M1 VM) they differ in the low bits,
with no change in shape, dtype or sign. Add a `.referenceHardware`
Swift Testing trait that runs a test only when MLX_REFERENCE_HARDWARE=1,
and mark the nine tests with it. Elsewhere they report as skipped with
the reason. No assertion, tolerance or reference changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: gate only the bit comparisons of mixed DiffusionGemma tests

Three gated tests also held checks that pass on any hardware. Split them
so only the bit-for-bit comparison is gated:

- prefixIdentityTokensOwnerAndEmptyStateFailClosed() runs its
  fail-closed probes on all hardware. The donor-logits bit comparison
  moves to failClosedProbesLeaveDonorLogitsBitExact().
- nativeFactoryLoadsExactStateAndReleasesItsModel() keeps the load and
  model-release checks on all hardware. The logits bit comparison moves
  to nativeFactoryDenoiseMatchesReferenceBits().
- The two parameterized vision tests run their bf16 case on all
  hardware. The fp32 case moves to a separate gated test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: gate only the reference comparisons of three more DiffusionGemma tests

Split the three tests that were still gated whole, so their checks that
pass on any hardware run everywhere:

- chunkedSessionBoundsPrefillAndCanCancelAfterPrefill() keeps the
  prefill bounds, the complete flag, the counters, cancel, the emitted
  checkpoint and the released cache for widths 1, 3 and 7. The KV and
  logits bit comparisons move to chunkedSessionMatchesIndependentNativeReference().
- sharedWeightsConditioningKeepsCommittedCacheState() keeps the fixture
  checks, both cache positions and the unchanged encoder KV after the
  provisional canvas. The reference comparisons stay in
  sharedWeightsConditioningAndCommittedCacheMatchReference().
- committedPrefixRestoreKeepsPositionsAfterDonorRetirement() keeps the
  token count, retained bytes, donor release and both positions. The
  reference comparisons stay in
  committedPrefixRestoreIsExactAfterDonorAppendAndRetirement().

Each pair shares one helper. The fixture reference, case-count and
parameter-count checks of the block and fp32 vision fixtures also run
everywhere now, in blockOracleFixtureIsPinned() and fp32FixtureIsPinned().
CONTRIBUTING.md says which comparisons the gate covers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: format HistoricalWindowCheckpointTests.swift

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: size the slot-cap request from what the ledger accepts

slotCapLeavesRoomForServing() sized its request from bytesReserved.
bytesReserved includes the paged pool's physical-floor overhead, which a
request's target KV replaces when it reserves. The overhead depends on
the buffer sizes the MLX allocator returns: a 36,864-byte segment gets a
49,152-byte buffer, or a 65,536-byte buffer reused from the process-wide
cache. When earlier work left 64 KiB buffers in the cache, the capped
arm left more than 5.5 windows of real slack instead of half a window,
and the uncapped arm's reservation fit.

Find the largest request the ledger accepts beside the capped set with
trial reservations, then take half a window off it. The assertions do
not change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request feature New feature (auto-applied from feat: prefix)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant