Skip to content

Feature/gemma 4 inference aha moment - #3

Merged
solderzzc merged 14 commits into
mainfrom
feature/gemma-4-inference-aha-moment
Apr 4, 2026
Merged

solderzzc merged 14 commits into
mainfrom
feature/gemma-4-inference-aha-moment

Conversation

@solderzzc

Copy link
Copy Markdown
Member

No description provided.

davidkoski and others added 14 commits March 26, 2026 08:32
* fix unreliable tests

- fixes ml-explore#119
- make the random weight model and tokenizer behave in a predictable way
* add missing context/toolcall parameters

- see ml-explore#139
…ler (ml-explore#147)

* perf: eliminate CPU←GPU sync in penalty processors for 35% faster generation

All three penalty processors (RepetitionContext, PresencePenaltyContext,
FrequencyPenaltyContext) called `token.item(Int.self)` in `didSample()`,
forcing a CPU←GPU synchronization on every generated token. This broke
the `asyncEval()` pipelining in `TokenIterator`, preventing the GPU from
working ahead on the next token while the current one was being returned.

Fix: Replace Swift `[Int]` token buffers with GPU-resident ring buffers
(`MLXArray`). Update positions via `MLX.where` mask operations that stay
entirely on GPU. No `.item()` or `.asArray()` calls remain in the
hot path.

Benchmarked on Qwen3.5-4B (248K vocab, topK=20, presencePenalty=1.5):
- Peak tok/s: 70 → 95 (+35%)
- Aggregate tok/s across 14 scenarios: 34.6 → 57.2 (+65%)

The improvement comes from restoring async GPU pipelining — the GPU can
now compute the next token's forward pass while the current token is
being returned to the caller.

* perf: optimize TopPSampler with argPartition for topK sampling

When topK is set (e.g., 20) and much smaller than vocabulary size
(e.g., 248K), use argPartition O(V) to find top-K candidates instead
of argSort O(V log V) on the entire vocabulary. Then sort only the K
candidates O(K log K) for cumulative probability filtering.

Also switch from take() to takeAlong() throughout to preserve
input dimensions and avoid squeeze/unsqueeze shape issues.

* style: fix swift-format formatting in penalty processors
* refactor: address PR review — align sampling with Python mlx-lm

- Remove Sendable from LogitProcessor (MLXArray is not Sendable)
- Extract TokenRing struct to deduplicate ring buffer across penalty processors
- Use MLXArray.arange() (GPU primitive) computed once in init
- Replace softmax with logSoftmax, work in log-prob space throughout
- Apply filters in Python mlx-lm order: top_p → min_p → top_k
- Each filter operates on full vocabulary matching mlx_lm.sample_utils
- Use putAlong for O(V) scatter instead of double argSort in applyTopP

* Mirror mlx-lm top-k masking semantics

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Add copy() to KVCache protocol and all implementations

Add an independent deep-copy method to enable reusing a prefix cache
across multiple ChatSession instances without reloading from disk.

- Add copy() requirement to KVCache protocol
- Implement on KVCacheSimple, RotatingKVCache, QuantizedKVCache,
  ChunkedKVCache, ArraysCache, MambaCache, and CacheList
- Guard against empty state in all copy() methods to avoid fatalError
  from state setters that reject empty arrays
- Preserve leftPadding in ArraysCache/MambaCache copies
- Add CacheList array-based initializer to support copy()
- Change ArraysCache.leftPadding from private to internal for
  subclass access in MambaCache.copy()

Tests:
- testCacheCopyIsIndependent: parameterized across 6 cache types,
  verifies copy has same state and mutation of copy leaves original
  unchanged
- testCacheCopyOnEmptyCache: verifies copy of unpopulated cache
  does not crash
- testCacheListCopyIsIndependent: verifies CacheList with
  heterogeneous sub-caches copies independently

* Bump mlx-swift dependency to 0.31.1

Picks up the fix for array[.ellipsis] returning self instead of a
copy (ml-explore/mlx-swift#367), plus mlx 0.31.1 C++ updates.
…#151)

* Add KVCache initializers and cache access to ChatSession

Adds two new initializers that accept a pre-built [KVCache], plus
currentCache() and saveCache(to:) methods, addressing the gap noted
in issue #123 where loadPromptCache() had no path back into ChatSession.

Use case: prefix caching. Build a KVCache from a long shared context
(system prompt + document) once, save it to disk, and restore it across
multiple sessions to skip re-prefilling the same tokens each time.

New API:

  // Initialize with a restored cache
  ChatSession(_ model: ModelContainer, cache: [KVCache], ...)
  ChatSession(_ model: ModelContext, cache: [KVCache], ...)

  // Read the live cache after generation
  func currentCache() async -> [KVCache]?

  // Save the live cache to disk (.safetensors)
  func saveCache(to url: URL) async throws

The .kvcache branch in streamMap already handles an injected cache
correctly — it uses the array directly without re-initializing,
so no changes to generation logic are required.

* Add tests for history session and clear() cache behavior

* Add LocalizedError conformance to ChatSessionError and document saveCache lock behavior

* Remove redundant thread-safety comment from saveCache

* Make cache parameter consuming and improve cache init docs

- Mark cache parameter as `consuming` to prevent reuse of shared
  mutable KVCache references across sessions
- Reorder parameters so `instructions` comes before `cache`, matching
  the history initializer pattern
- Warn that passing instructions when the cache already encodes a
  system prompt will produce incoherent output
- Document that currentCache() references must not be used concurrently
  with active generation
- Fix currentCache() to avoid mutable captured var (reduces Sendable
  warnings)
- Fix ambiguous init reference in saveCache() doc comment
* Add model-defined pooling fallback for embedding models

* Use takeAlong for last-token pooling
The generation loop was breaking on the first tool call, canceling the
stream, and losing the rest. Now it drains the stream, collects all
tool calls, dispatches them, and restarts with all tool results.

Skips dispatch if the consumer has canceled (Task.isCancelled).
No change to the streamDetails path.

Fixes ml-explore#134.
…es (ml-explore#165)

* switch to swift 6 -- prevent concurrency issues, fix concurrency issues

- some concurrency issues snuck in for test support
- fix and prevent more from coming in by switching Package to swift 6
- depends on ml-explore/mlx-swift#379

* pick up mlx-swift with fix for save_safetensors concurrency issue
* Decouple from tokenizer and downloader packages

MLX Swift LM currently has two fundamental problems:

- Model loading is tightly coupled to the Hugging Face Hub. A Hub client is required even when loading models from a local directory.
- Model loading performance with Swift Transformers lags far behind the Python equivalent, typically taking several seconds in Swift versus a few hundred milliseconds in Python.

This PR implements the following solutions:

- Swift Transformers is replaced with Swift Tokenizers, a streamlined and optimized fork that focuses purely on tokenizer functionality, with no Hugging Face dependency and no extraneous Core ML code. This unlocks a 10x to 15x speedup in model loading times.
- The Downloader protocol abstracts away the model hosting provider, making it easy to use other providers such as ModelScope or define custom providers such as downloading from storage buckets.
- Swift Hugging Face, a dedicated client for the Hub, is used in an optional module. No Hugging Face Hub code is bundled for users who don't need it.

The `hub` parameter (previously `HubApi`) has been replaced with `from` (any `Downloader` or `URL` for a local directory). Functions that previously defaulted to `defaultHubApi` no longer have a default – callers must either pass a `Downloader` explicitly or use the convenience methods in `MLXLMHuggingFace` / `MLXEmbeddersHuggingFace`, which default to `HubClient.default`.

For most users who were using the default Hub client, adding `import MLXLMHuggingFace` or `import MLXEmbeddersHuggingFace` and using the convenience overloads is sufficient.

Users who were passing a custom `HubApi` instance should create a `HubClient` instead and pass it as the `from` parameter. `HubClient` conforms to `Downloader` via `MLXLMHuggingFace`.

- `tokenizerId` and `overrideTokenizer` have been replaced by `tokenizerSource: TokenizerSource?`, which supports `.id(String)` for remote sources and `.directory(URL)` for local paths.
- `preparePrompt` has been removed. This shouldn't be used anyway, since support for chat templates is available.
- `modelDirectory(hub:)` has been removed. For local directories, pass the `URL` directly to the loading functions. For remote models, the `Downloader` protocol handles resolution.

`loadTokenizer(configuration:hub:)` has been removed. Tokenizer loading now uses `AutoTokenizer.from(directory:)` from Swift Tokenizers directly.

`replacementTokenizers` (the `TokenizerReplacementRegistry`) has been removed. Use `AutoTokenizer.register(_:for:)` from Swift Tokenizers instead.

The `defaultHubApi` global has been removed. Hugging Face Hub access is now provided by `HubClient.default` from the `HuggingFace` module.

- `downloadModel(hub:configuration:progressHandler:)` → `Downloader.download(id:revision:matching:useLatest:progressHandler:)`
- `loadTokenizerConfig(configuration:hub:)` → `AutoTokenizer.from(directory:)`
- `ModelFactory._load(hub:configuration:progressHandler:)` → `_load(configuration: ResolvedModelConfiguration)`
- `ModelFactory._loadContainer`: removed (base `loadContainer` now builds the container from `_load`)

---------

Co-authored-by: David Koski <dkoski@apple.com>
* Unify RoPE application across all models with applyRotaryPosition helper

Replace verbose conditional rope offset patterns across 45 model files
with a single `applyRotaryPosition(rope, to:, cache:)` helper function.

This is a pure refactoring with no behavior change for single-request
inference. The helper centralizes the `cache?.offset ?? 0` pattern,
reducing boilerplate and making models ready for future batch-aware
RoPE dispatch.

Key changes:
- Add RoPEApplication.swift with the applyRotaryPosition helper
- Migrate 45 model attention layers to use the unified helper
- SmolLM3: Replace custom SmolLM3PositionEmbedding protocol with
  standard RoPELayer; add ArrayOffsetLayer conformance to NoPE
- Internlm2: Add OffsetLayer/ArrayOffsetLayer conformance to
  DynamicNTKScalingRoPE; extract computeBase helper
- NanoChat: Wrap MLXFast.RoPE in NanoChatRoPE class conforming to
  RoPELayer protocols
- Phi3: Remove PositionalEncoding enum; use RoPELayer directly
- GPTOSS: Unify quantized and regular rope paths
- Gemma3nText: Change rope type from OffsetLayer to RoPELayer

https://claude.ai/code/session_01R2RLMzHoCdxLzQUKRczD8G

* Fix Gemma3Attention rope type: OffsetLayer -> RoPELayer

The applyRotaryPosition helper requires ArrayOffsetLayer conformance.
Change the stored property type to RoPELayer (OffsetLayer & ArrayOffsetLayer)
to match what initializeRope() already returns.

https://claude.ai/code/session_01R2RLMzHoCdxLzQUKRczD8G

---------

Co-authored-by: Claude <noreply@anthropic.com>
* Add speculative decoding
- Speculative decoding (Evaluate.swift)
- copy() protocol added to KVCache
- RoPEApplication refactor across all models (46 files, minor boilerplate)
- Decouple from tokenizer/downloader (new BenchmarkHelpers, IntegrationTestHelpers)
- chatSession multiple tool calls, embedding pooling fixes
- skills/ references added

Conflicts resolved in favour of our fork:
- Package.swift: kept local mlx-swift path + swift-transformers (not upstream remote URL)
- ModelConfiguration.swift: kept our preparePrompt/lazyLoad params
@solderzzc
solderzzc merged commit e8c474d into main Apr 4, 2026
@solderzzc
solderzzc deleted the feature/gemma-4-inference-aha-moment branch April 4, 2026 22:35
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.

8 participants