-
Notifications
You must be signed in to change notification settings - Fork 1.1k
[MLX] Add off-graph KV-cache flat runtime #21501
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
011bd32
[MLX] Add off-graph KV-cache flat runtime
kiymetakdemir 9c609a6
[MLX] Reshape the KV cache around per-layer policy and require kv_dtype
kiymetakdemir f96535c
[MLX] Require an explicit scale and switch exhaustively on mask kind
kiymetakdemir 1e895e4
[MLX] Validate the cache config and require layer_id
kiymetakdemir 83085d9
Merge branch 'main' into kv-cache-mlx-flat
kiymetakdemir File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| /* | ||
| * Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| * All rights reserved. | ||
| * | ||
| * This source code is licensed under the BSD-style license found in the | ||
| * LICENSE file in the root directory of this source tree. | ||
| */ | ||
|
|
||
| #pragma once | ||
|
|
||
| #include <optional> | ||
|
|
||
| #include "MLXExecutor.h" // Tensor, StreamOrDevice | ||
|
|
||
| namespace executorch { | ||
| namespace backends { | ||
| namespace mlx { | ||
|
|
||
| // The K/V window to attend over + how to mask it; the cache owns the semantic. | ||
| // `kind` mirrors MLX SDPA's mask forms (no mask / "causal" / explicit tensor). | ||
| // Will be added: a `window` on Causal (sliding-window -- the | ||
| // mask_mod axis) and a `softcap`/bias field (ALiBi, softcap -- the score_mod | ||
| // axis). | ||
| struct AttendSpec { | ||
| Tensor K; | ||
| Tensor V; | ||
| enum class Mask { None, Causal, Explicit } kind; | ||
| std::optional<Tensor> mask; // Explicit only | ||
| }; | ||
|
|
||
| // Tensor-typed op face of the off-graph KV cache, kept separate from the | ||
| // neutral CacheBase (which is tensor-free) so a cache can expose both without a | ||
| // diamond. ExecutionState holds one; nothing assigns it yet -- the registry | ||
| // that owns the cache and hands this pointer to the executor lands in a | ||
| // follow-up, until which exec_update_and_attend is unreachable. | ||
| class MLXCache { | ||
| public: | ||
| virtual ~MLXCache() = default; | ||
|
|
||
| // Write this step's K/V for `layer` at `position` (the run's logical start); | ||
| // return the window + mask kind. k/v are BHSD. `position` is a host int -- | ||
| // the caller reads it off the graph so the cache stays pure graph + integer | ||
| // bookkeeping. The cache owns the mask: a multi-token chain is Causal, a | ||
| // single decode token is None. | ||
| virtual AttendSpec update_and_fetch( | ||
| int layer, | ||
| int position, | ||
| const Tensor& k, | ||
| const Tensor& v, | ||
| StreamOrDevice s) = 0; | ||
| }; | ||
|
|
||
| } // namespace mlx | ||
| } // namespace backends | ||
| } // namespace executorch |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,175 @@ | ||
| /* | ||
| * Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| * All rights reserved. | ||
| * | ||
| * This source code is licensed under the BSD-style license found in the | ||
| * LICENSE file in the root directory of this source tree. | ||
| */ | ||
|
|
||
| #pragma once | ||
|
|
||
| #include <optional> | ||
| #include <stdexcept> | ||
| #include <string> | ||
| #include <vector> | ||
|
|
||
| #include "MLXCache.h" // AttendSpec, MLXCache | ||
| #include "MLXExecutor.h" // resolve_dtype | ||
|
|
||
| #include <executorch/extension/llm/cache/cache.h> | ||
| #include <executorch/extension/llm/cache/sequence_cache.h> | ||
|
|
||
| namespace executorch { | ||
| namespace backends { | ||
| namespace mlx { | ||
|
|
||
| namespace cache = ::executorch::extension::llm::cache; | ||
|
|
||
| // Per-layer K or V store, SDPA-major [1, H, slots, D] (cells on axis 2). The | ||
| // planner hands down physical runs (it has already applied any ring modulo), so | ||
| // the pool is layout-agnostic: flat and ring differ only in how many slots the | ||
| // layer asks for and how many runs a step produces. | ||
| class Pool { | ||
| public: | ||
| Pool(int slots, int H, int D, ::mlx::core::Dtype dtype) | ||
| : dtype_(dtype), | ||
| buf_(::mlx::core::zeros(::mlx::core::Shape{1, H, slots, D}, dtype)) {} | ||
|
|
||
| // Place `update` at the run's physical start, casting to the storage dtype if | ||
| // it differs. | ||
| void write(const cache::Run& run, const Tensor& update, StreamOrDevice s) { | ||
| const int H = static_cast<int>(buf_.shape(1)); | ||
| const int D = static_cast<int>(buf_.shape(3)); | ||
| if (run.start < 0 || run.start + run.len > slots()) { | ||
| throw std::runtime_error("Pool::write: run out of bounds"); | ||
| } | ||
| if (static_cast<int>(update.shape(2)) != run.len) { | ||
| throw std::runtime_error("Pool::write: update length != run length"); | ||
| } | ||
| if (static_cast<int>(update.shape(1)) != H || | ||
| static_cast<int>(update.shape(3)) != D) { | ||
| throw std::runtime_error("Pool::write: K/V heads/dim mismatch"); | ||
| } | ||
| const Tensor u = update.dtype() == dtype_ | ||
| ? update | ||
| : ::mlx::core::astype(update, dtype_, s); | ||
| buf_ = ::mlx::core::slice_update( | ||
| buf_, | ||
| u, | ||
| ::mlx::core::Shape{0, 0, run.start, 0}, | ||
| ::mlx::core::Shape{1, H, run.start + run.len, D}, | ||
| s); | ||
| } | ||
|
|
||
| // The run's cells, [start, start+len). Ring reads start mid-pool, so the run | ||
| // start matters here as much as it does for a write. | ||
| Tensor read(const cache::Run& run, StreamOrDevice s) const { | ||
| const int H = static_cast<int>(buf_.shape(1)); | ||
| const int D = static_cast<int>(buf_.shape(3)); | ||
| if (run.start < 0 || run.start + run.len > slots()) { | ||
| throw std::runtime_error("Pool::read: run out of bounds"); | ||
| } | ||
| return ::mlx::core::slice( | ||
| buf_, | ||
| ::mlx::core::Shape{0, 0, run.start, 0}, | ||
| ::mlx::core::Shape{1, H, run.start + run.len, D}, | ||
| ::mlx::core::Shape{1, 1, 1, 1}, | ||
| s); | ||
| } | ||
|
|
||
| int slots() const { | ||
| return static_cast<int>(buf_.shape(2)); | ||
| } | ||
|
|
||
| private: | ||
| ::mlx::core::Dtype dtype_; | ||
| Tensor buf_; | ||
| }; | ||
|
|
||
| // The MLX byte layer behind the neutral SequenceCache: one Pool per layer for K | ||
| // and one for V, sized from that layer's own policy. update_and_fetch plans the | ||
| // step (integer runs), writes the new K/V, reads the retained window, and | ||
| // declares the mask; the op handler owns q/scale and calls SDPA. | ||
| // | ||
| // Only flat layers are wired up so far. Ring layers are rejected at | ||
| // construction rather than silently mis-served: the plumbing below handles | ||
| // their runs, but the windowed mask and read_base_pos (RoPE alignment) are not | ||
| // implemented yet. | ||
| class MLXSequenceCache : public cache::SequenceCache, public MLXCache { | ||
| public: | ||
| explicit MLXSequenceCache(const cache::CacheConfig& cfg) | ||
| : cache::SequenceCache(checked(cfg)) { | ||
| const ::mlx::core::Dtype dt = | ||
| resolve_dtype(static_cast<int8_t>(cfg.kv_dtype)); | ||
| kpool_.reserve(static_cast<size_t>(cfg.n_layers)); | ||
| vpool_.reserve(static_cast<size_t>(cfg.n_layers)); | ||
| for (int l = 0; l < cfg.n_layers; ++l) { | ||
| // layers size 1 = one config broadcast to every layer, else per-layer. | ||
| const cache::LayerConfig& lc = | ||
| cfg.layers.size() == 1 ? cfg.layers.front() : cfg.layers[l]; | ||
| if (lc.policy.kind != cache::LayerPolicy::Kind::Flat) { | ||
| throw std::runtime_error( | ||
| "MLXSequenceCache: only Flat layers are supported so far"); | ||
| } | ||
| // Flat retains all history, so the layer's pool is the full cap. A ring | ||
| // layer will instead ask for window + max_write - 1 slots. | ||
| const int slots = cfg.capacity; | ||
| kpool_.emplace_back(slots, lc.n_kv_heads, lc.head_dim, dt); | ||
| vpool_.emplace_back(slots, lc.n_kv_heads, lc.head_dim, dt); | ||
| } | ||
| } | ||
|
|
||
| AttendSpec update_and_fetch( | ||
| int layer, | ||
| int position, | ||
| const Tensor& k, | ||
| const Tensor& v, | ||
| StreamOrDevice s) override { | ||
| if (layer < 0 || layer >= static_cast<int>(kpool_.size())) { | ||
| throw std::out_of_range("update_and_fetch: layer out of range"); | ||
| } | ||
| const int T = static_cast<int>(k.shape(2)); // BHSD: seq axis is 2 | ||
|
|
||
| std::optional<cache::SeqStepPlan> p = this->plan(layer, position, T); | ||
| if (!p) { | ||
| throw std::runtime_error( | ||
| "update_and_fetch: step exceeds capacity or invalid layer"); | ||
| } | ||
| // Flat layers never wrap, and ring layers are refused at construction, so | ||
| // every accepted step is a single run. Ring's split/rejoin lands with ring. | ||
| if (p->n_write != 1 || p->n_read != 1) { | ||
| throw std::runtime_error("update_and_fetch: expected a single-run plan"); | ||
| } | ||
| const size_t l = static_cast<size_t>(layer); | ||
| kpool_[l].write(p->write[0], k, s); | ||
| vpool_[l].write(p->write[0], v, s); | ||
| Tensor K = kpool_[l].read(p->read[0], s); | ||
| Tensor V = vpool_[l].read(p->read[0], s); | ||
| this->commit(*p); | ||
|
|
||
| // A multi-token chain is Causal (MLX "causal" is lower-right aligned, so | ||
| // fresh and chunked prefill are both correct with new tokens at the tail); | ||
| // a single decode token needs no mask. | ||
| const AttendSpec::Mask kind = | ||
| (T > 1) ? AttendSpec::Mask::Causal : AttendSpec::Mask::None; | ||
| return AttendSpec{K, V, kind, std::nullopt}; | ||
| } | ||
|
|
||
| private: | ||
| // Enforce the neutral contract as an exception, the failure mode this layer | ||
| // already uses. Runs as the base initializer's argument because | ||
| // SequenceCache's own ctor indexes `layers` before this class's body does. | ||
| static const cache::CacheConfig& checked(const cache::CacheConfig& cfg) { | ||
| if (!cache::valid(cfg)) { | ||
| throw std::runtime_error("MLXSequenceCache: invalid CacheConfig"); | ||
| } | ||
| return cfg; | ||
| } | ||
|
|
||
| std::vector<Pool> kpool_; | ||
| std::vector<Pool> vpool_; | ||
| }; | ||
|
|
||
| } // namespace mlx | ||
| } // namespace backends | ||
| } // namespace executorch |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Didn't the op have an output dtype?