Repository navigation
feat: add ParoQuant (pairwise rotation quantization) support - #164
Conversation
|
It is not appropriate to pre-rotate the weights. The purpose of the rotations is to make the weights more quantization-friendly. If you rotate the weights then dequantize them the rotation will have no effects at all. |
|
@liang2kl Thank you for pointing this out I've removed the pre-rotation and results improved significantly. On our 14-scenario tool-calling agent benchmark (file edits, multi-step instructions, exact string matching). The Qwen 3.5 4B PARO now outperforms standard 8-bit quantization on scenarios passed, duplicate rate, throughput, and memory which is a great result. I believe there's still room to squeeze more decode performance out of this, so I'll keep iterating. Thanks again for the feedback! |
Add support for loading PARO-quantized models (AutoAWQ format) with pairwise Givens rotation. Pre-rotates weights at load time to eliminate per-token rotation kernel dispatch, yielding +23% generation throughput. Key changes: - RotateQuantizedLinear: Metal rotation kernel + weight pre-rotation - ParoQuantLoader: AWQ conversion, loading, disk caching of pre-rotated weights - Qwen35: in_proj_b/a fusion via sanitize for single matmul dispatch Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The sanitize-based fusion only concatenated .weight but not .scales and .biases, leaving the fused module unquantized and causing shape mismatches when loading standard quantized Qwen3.5 checkpoints. Reverts to separate in_proj_b / in_proj_a modules from the base branch. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
PARO checkpoints store in_proj_b + in_proj_a as a single fused in_proj_ba key. Add sanitize logic to split it back into separate in_proj_b / in_proj_a weights (and scales/biases if quantized). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
On hybrid models (e.g. Qwen 3.5 mixing attention + Mamba layers), cache[0] is a MambaCache with offset=0. The guard failed and no layers got quantized. Now finds the first KVCacheSimple entry instead. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add 8 unit tests covering pair packing, AutoAWQ conversion, quantization round-trip, and pre-rotation equivalence. Document the channel-scales asymmetry (diag(s²) factor) on callAsFunction for future maintainers. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Remove Hub/Tokenizers imports from MLXLMCommon and accept a TokenizerLoader parameter instead, matching the new architecture from ml-explore#118. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2f3e290 to
40932b9
Compare
| /// `nonisolated(unsafe)` — kernel creation is idempotent (same tile size always produces | ||
| /// the same compiled kernel), so concurrent stores are benign. Same pattern as | ||
| /// `GatedDeltaKernelManager` in the existing codebase. | ||
| nonisolated(unsafe) private var kernelCache: [Int: MLXFast.MLXFastKernel] = [:] |
There was a problem hiding this comment.
This has to use locks to protect it -- callers will be multithreaded.
There was a problem hiding this comment.
kernelCache behind NSLock, same pattern as AbstractModelRegistry
| nonisolated(unsafe) static let shiftsArray = MLXArray(shifts.map { Int64($0) }).reshaped( | ||
| 1, 1, 8) | ||
| nonisolated(unsafe) static let reorderIndices = MLXArray(inverseReorder.map { Int32($0) }) |
There was a problem hiding this comment.
I think this is doable, but only if the arrays are evaluated. Two threads can't consume unevaluated arrays safely.
We would want lazy eval, so this may need to be done with some locks and computed properties.
There was a problem hiding this comment.
Are these only used at model load time (for unpacking)? I wonder if we even need to cache these? Maybe just make a function to return them?
That way they are deallocated when not used and I suspect that these are pretty cheap to create and dispose of during loading. That would be cleaner all around, unless you have measurements showing that this is needed.
There was a problem hiding this comment.
Dropped the static AWQ arrays, rebuilt inline in unpackAndReorder load-time only
| } | ||
|
|
||
| // Split pre-fused in_proj_ba → in_proj_b + in_proj_a | ||
| // (PARO checkpoints store these as a single fused key) |
There was a problem hiding this comment.
Are there other models that might use this technique? Does this belong as library code in the ParoQuantLoader or ParoQuantizedLinear?
There was a problem hiding this comment.
moved out of Qwen35.sanitize into splitFusedMambaProjections in ParoQuantLoader
| // Rotation parameters — discovered by Module reflection for update(parameters:) | ||
| let theta: MLXArray | ||
| let pairs: MLXArray | ||
| let channel_scales: MLXArray // swiftlint:disable:this identifier_name |
There was a problem hiding this comment.
This can be done using @ParameterInfo(key: "channel_scales") and a normal swift variable name.
| private var cached: CachedRotation? | ||
| private var cachedParams: MLXArray? |
There was a problem hiding this comment.
Modules cannot have any eval-time generated state, see #157.
There was a problem hiding this comment.
Fixed no eval-time state, derived arrays are private _-prefixed fields, populated once by a new prepareDerivedRotationState() that the loader runs between update(parameters:) and eval(model)
| if batch != cachedBatch { | ||
| cachedParams = MLXArray([Int32(batch), Int32(c.dim), Int32(c.krot), Int32(groupSize)]) | ||
| cachedBatch = batch |
There was a problem hiding this comment.
The model will be used in a multi-threaded context, so no mutation is allowed at eval-time.
Addresses PR ml-explore#164 review comment C1. `kernelCache` was marked `nonisolated(unsafe)` with a rationale that concurrent stores are benign — they're not. `Dictionary` mutation under concurrent access is a data race, and callers can hit `getRotationKernel` from multiple tasks via `ModelContainer.perform { ... }`. Wrap the read-modify-write in `NSLock.withLock` using the same pattern as `AbstractModelRegistry` / `ModelAdapterTypeRegistry` / `Tokenizer`. Contention is practically nil — only two tile sizes (1 and 4) are ever requested, so the lock is contended exactly twice per process before the cache saturates. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Addresses PR ml-explore#164 review comment C2. `AWQ.shiftsArray` and `AWQ.reorderIndices` were stored as `nonisolated(unsafe) static let` MLXArrays — unsafe because concurrent consumers could race on unevaluated promises, and unnecessary because the arrays are tiny (8 elements each) and only touched inside `unpackAndReorder`, which runs once per weight tensor at model load time. Rebuild both arrays inline inside `unpackAndReorder`. Negligible allocation cost (~48 bytes per call across ~150 calls for Qwen3.5-9B), fully dominated by the weight-tensor math that follows. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Addresses PR ml-explore#164 review comment C3. The stored property was named `channel_scales` with a swiftlint disable pragma so the Swift name would match the checkpoint key. The repo's convention (e.g. `LoRA+Layers.swift` `lora_a`/`lora_b`) is to give the property a Swift-idiomatic name and use `@ParameterInfo(key:)` to preserve the checkpoint key. Switch to that pattern. In the initialiser, assign through `_channelScales.wrappedValue` so the `@ParameterInfo(key: "channel_scales")` metadata survives init. Replacing the wrapper (`self._channelScales = .init(wrappedValue: ...)`) drops the `key:` argument and makes Module reflection fall back to the Swift property name `channelScales`, which isn't in the checkpoint — `update(parameters: verify: [.allModelKeysSet, .shapeMismatch])` then throws `keyNotFound` on real model load. Same pattern documented in `Libraries/MLXLMCommon/Documentation.docc/porting.md`. No checkpoint-compatibility change — the on-disk key stays `channel_scales`. Only the Swift call sites see `channelScales`. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Addresses PR ml-explore#164 review comment C4 (the big one). The previous implementation kept a mutable `cached: CachedRotation?` plus a `cachedBatch` / `cachedParams` pair that were all populated on the first forward pass. Under multi-threaded inference — the model container pattern the framework supports — that's a data race, and it's exactly the class of "Modules cannot have eval-time generated state" problem referenced in ml-explore#157. Redesign: - Add `prepareDerivedRotationState()` on `RotateQuantizedLinear`. It computes `cos θ`, `sin θ`, packed pair indices, and flattened channel scales from the loaded checkpoint parameters, stores them in private underscore-prefixed fields, and `eval(...)`s the four tensors so they materialise outside any forward pass's graph. - Store the derived tensors as `private var _cosTheta / _sinTheta / _packedPairs / _scalesFlat`. Underscore-prefixed private fields are skipped by Module reflection (`Documentation.docc/porting.md` "Computed vs Loaded Parameters"), so they don't participate in weight loading — the loader's `verify: [.allModelKeysSet, .shapeMismatch]` stays strict. - `ParoQuantLoader.loadParoQuantModel` calls the finalize method between `model.update(parameters:)` and the IO-layer quantisation pass. - Forward pass reads the derived fields directly. No mutation, no caches, no `cachedBatch` gating. The 4-int32 `params` kernel argument is now rebuilt per call — 16 bytes, negligible next to the kernel launch itself. Also add `testRotateQuantizedLinearConcurrentSafe` (the L4 gate): `DispatchQueue.concurrentPerform` fires 8 parallel forward passes through a single layer, alternating batch=1 and batch=4 so both tile sizes race into `kernelCache` on the first iteration. Regression proof for C1 and C4 together. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Addresses PR ml-explore#164 review comment C5. The `in_proj_ba` → `in_proj_b` / `in_proj_a` split was landing inside `Qwen35TextModel.sanitize`, but the fused-projection layout is a PARO-specific detail (AutoAWQ-Mamba concatenation), not a property of Qwen3.5 proper. Keeping it in the generic model file means every Qwen3.5 consumer drags the PARO-specific code path around. Move the split into a new `splitFusedMambaProjections` helper in ParoQuantLoader, invoked after AutoAWQ conversion and before `model.sanitize`. The helper is a no-op for checkpoints that don't have fused `in_proj_ba` keys (e.g. non-Mamba layouts), and idempotent when the expected split keys already exist. The generic Qwen35 model now carries no PARO-specific logic. The VLM Qwen35 path reaches the same loader, so both containers benefit. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Addresses PR ml-explore#164 review comment C6 (JaeminKim-amoz). The previous `FileManager.default.enumerator(at:)` recursed into subdirectories, which would pull in nested `.safetensors` files — e.g. a stray HF snapshot cache under the checkpoint dir, or any directory a user extracted into the model folder. Replace with `contentsOfDirectory(at:)` so we only look at files directly inside the passed-in directory. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
@davidkoski thanks for the detailed review Verified on 4B PARO and 9B PARO inside BenchLocal no perf or memory regression.
|
davidkoski
left a comment
There was a problem hiding this comment.
Changes look good, thank you!
#471) feat(paroquant): MoE architecture support, prepared checkpoint caching, and rotation kernel optimizations ### MoE Support & Architecture - **PairwiseRotation & RotateSwitchGLU:** Extracted standalone `PairwiseRotation` module and implemented `RotateSwitchGLU` to support MoE PARO models (e.g., Qwen3.6-35B-A3B). - **MoE Loader Pipeline:** Added passes to stack per-expert AWQ weights, remap shared rotations, and patch switch GLU layers without mutating dense paths. - **Conversion Robustness:** Dropped theta-filter to convert un-partnered expert weights, match scales/biases to checkpoint float dtype, and optimized prefix matching from $O(N \cdot M)$ to $O(1)$. ### Performance - **Pre-Gather MoE Rotation:** Moved `gate_up` rotation before expert gather/sort, reducing row-rotation overhead by $1/\text{topK}$. - **Simdgroup Rotation Kernel:** Rewrote the Metal rotation kernel for `groupSize == 128` to execute in a single simdgroup with `simdgroup_barrier` (with generic fallback for other sizes), delivering up to 2x speedup. - **GatedDelta Fusion:** Compile-fused the 6-kernel elementwise decay gate chain into a single dispatch. - **Prepared Checkpoints:** Added background caching of converted weights to `prepared_checkpoint.safetensors` with self-healing validation manifests, cutting warm-load times significantly. ### Fixes & Cleanups - Unified `RotationDerivedState` and batched GPU evaluation across all rotation modules at load time. - Froze `PairwiseRotation` parameters to allow fused weighted reduction in `SwitchGLU`. - Fixed tool-call format and chat convention resolution in `loadParoQuantModel`. - Fixed volume free-space detection for disk persistence on CI runners. Refs #208, #209, #220, #424, #471
…follow-up) (ml-explore#471) feat(paroquant): MoE architecture support, prepared checkpoint caching, and rotation kernel optimizations ### MoE Support & Architecture - **PairwiseRotation & RotateSwitchGLU:** Extracted standalone `PairwiseRotation` module and implemented `RotateSwitchGLU` to support MoE PARO models (e.g., Qwen3.6-35B-A3B). - **MoE Loader Pipeline:** Added passes to stack per-expert AWQ weights, remap shared rotations, and patch switch GLU layers without mutating dense paths. - **Conversion Robustness:** Dropped theta-filter to convert un-partnered expert weights, match scales/biases to checkpoint float dtype, and optimized prefix matching from $O(N \cdot M)$ to $O(1)$. ### Performance - **Pre-Gather MoE Rotation:** Moved `gate_up` rotation before expert gather/sort, reducing row-rotation overhead by $1/\text{topK}$. - **Simdgroup Rotation Kernel:** Rewrote the Metal rotation kernel for `groupSize == 128` to execute in a single simdgroup with `simdgroup_barrier` (with generic fallback for other sizes), delivering up to 2x speedup. - **GatedDelta Fusion:** Compile-fused the 6-kernel elementwise decay gate chain into a single dispatch. - **Prepared Checkpoints:** Added background caching of converted weights to `prepared_checkpoint.safetensors` with self-healing validation manifests, cutting warm-load times significantly. ### Fixes & Cleanups - Unified `RotationDerivedState` and batched GPU evaluation across all rotation modules at load time. - Froze `PairwiseRotation` parameters to allow fused weighted reduction in `SwitchGLU`. - Fixed tool-call format and chat convention resolution in `loadParoQuantModel`. - Fixed volume free-space detection for disk persistence on CI runners. Refs ml-explore#208, ml-explore#209, ml-explore#220, ml-explore#424, ml-explore#471
…e#164) * ci: build the fork and run its Metal test suites Add the Fork Tests workflow. It builds the package on a macos-26 runner, builds the full MLX Metal library with cmake, copies it next to the test binaries, and runs six CBv2 paged suites one step each. A suite step fails when the suite executes zero tests or skips a test. Port the scripts from d-inference and add them to fork.yaml. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * ci: remove the empty GPU listing from Fork Tests system_profiler SPDisplaysDataType prints nothing on the hosted macos-26 VM. The CPU, memory and disk lines stay. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * ci: select the newest release of Xcode 26 in Fork Tests Pick the newest Xcode_26.x app whose name is only a version number. Beta and release candidate apps are left out, so a new beta on the runner image cannot change CI without a pull request. The step still fails when the selected Swift is older than 6.3. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * ci: correct the Metal library notes in build-metallib.sh swift build makes no Metal library. The pinned mlx-swift excludes the MLX kernel sources and nojit_kernels.cpp from Cmlx, so SwiftPM builds MLX in JIT mode, and every MLX operation traps without a staged mlx.metallib. The partial 459-symbol library comes from xcodebuild, which this workflow does not use. State that the 10,000-symbol floor rejects a JIT-mode or incomplete cmake build. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * ci: key the SwiftPM cache on the commit and clean it before saving End the cache key with the commit SHA, as d-inference does, so each push to main saves a new entry. The prefix restore key still restores the newest entry for the same Xcode. Before the save, delete the staged mlx.metallib copies and the coverage data, so the cache keeps only SwiftPM output. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * ci: fix wording in the Fork Tests files - run-nested-suite.sh: the suites need no model weights, but one test needs DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST=1, which the caller sets. - fork-tests.yml: runs on main are not cancelled once they start. - Say "self-contained" instead of "hermetic" in the workflow and in fork.yaml. - fork.yaml: write the Fork Tests paragraph as one sentence per line, so later pull requests can add a sentence without touching the same lines. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * test: hold the hog in the waiting-queue backstop test testWaitingQueueBackstopEmitsCanonicalQueueFullMarker polled every 5 ms for the hog request to show as running, but the hog finished its 60 scripted tokens in milliseconds. A late poll missed the window and the test failed after 10 s (Fork Tests run 36182132297, attempt 1). Set eventBufferCapacity to 4, as testDuplicateSubmitThrowsAndFirst- StreamStillDelivers does. The unread hog stream hits backpressure, so the hog pauses with its slot retained until the test drains it. The wait now also requires the hog to be paused. Only this test changes. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * style: format CBv2SchedulerLoopTests.swift Run swift format format with .swift-format on the whole file, so the format check of ml-explore#160 passes. It changes four places outside the backstop test: two nested CBv2Request calls and three comment alignments in CBv2EngineLoopConfig arguments. No code changes. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * ci: run the scheduler loop suite through the no-skip runner Add a Fork Tests step that runs CBv2SchedulerLoopTests with scripts/run-nested-suite.sh, after the six Metal suites. The step fails when the class executes zero tests or skips a test, so CI runs the backstop fix instead of only compiling it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: make the capacity-loser scheduler test deterministic testCapacityLoserIsRequeuedNotErrored minted its two requests inside two async let children. Both children increment the unsynchronized CBv2SchedFixtures.nextID at the same time, so both requests can get the same id. The second submit then throws duplicateRequestID. XCTest reports the last error thrown during the test, which is the CancellationError from the cbv2SchedCollect watchdog sleep, so the failure showed as "CancellationError" at CBv2SchedulerTestSupport.swift:533. The test now mints and submits both requests on its own task. It also holds the step loop until both requests wait, so both requests compete for the single KV slot in the same step and the requeue always happens. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: release the step gate if a submit throws A defer releases suspendStepExecutionAtCountForTesting on the engine queue, so a throwing submit in testCapacityLoserIsRequeuedNotErrored cannot leave the step loop held. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>


Summary
Adds support for ParoQuant (ICLR 2026) INT4-quantized models. ParoQuant uses learned pairwise Givens rotations to suppress weight outliers before quantization, achieving ~2.4% accuracy improvement over standard AWQ on reasoning tasks.
What's included:
RotateQuantizedLinear— applies channel-scaling + pairwise Givens rotation to activations at runtime via Metal kernel, then feeds into standardquantizedMatmulParoQuantLoader— loads AutoAWQ-format checkpoints, converts weight layout, and patches rotation layers with their learned parameters (theta, pairs, channel_scales)in_proj_basplit in sanitize for PARO checkpoint compatibility, hybrid cache handling for mixed attention/Mamba layersAgent benchmark results
We run a 14-scenario tool-calling benchmark (file reads, edits, multi-step instructions, clarification requests) on Apple Silicon. Results are multi-run averages.
The 9B PARO outperforms 4.5-bit mixed-precision (OptiQ) on scenarios passed, duplicate rate, and throughput while using comparable memory.
Key finding: an earlier version pre-baked rotations into quantized weights for +23% throughput. This degraded structured output quality on the 9B model (5/14 passed, 11% dups). Applying rotation to activations at runtime instead — keeping weights in their original INT4 form — restored accuracy at a small throughput cost.
Test plan