Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions .github/workflows/mlx.yml
Original file line number Diff line number Diff line change
Expand Up @@ -383,9 +383,11 @@ jobs:
${CONDA_RUN} python -m examples.models.muse_glimmer.tests.export_mlx_dflash_fixture \
/tmp/muse-glimmer-mlx-fixtures
${CONDA_RUN} cmake --build "${BATCHING_BIN_DIR}" \
--target muse_glimmer_batching_test muse_glimmer_mlx_dflash_test sampling_test
--target muse_glimmer_batching_test muse_glimmer_mlx_dflash_test sampling_test \
muse_glimmer_dflash2_pairtree_test muse_glimmer_dflash_mode_test
${CONDA_RUN} ctest --test-dir "${BATCHING_BIN_DIR}" \
-R '^muse_glimmer_(batching|sampling)$' --output-on-failure --no-tests=error
-R '^muse_glimmer_(batching|sampling|dflash2_pairtree|dflash_mode)$' \
--output-on-failure --no-tests=error
${CONDA_RUN} ctest --test-dir "${BATCHING_BIN_DIR}" \
-R '^muse_glimmer_mlx_dflash$' --output-on-failure --no-tests=error
test -x "${BATCHING_BIN_DIR}/muse_glimmer_batching_runner"
Expand Down
205 changes: 204 additions & 1 deletion backends/mlx/runtime/MLXBatchedCache.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#include <limits>
#include <map>
#include <optional>
#include <set>
#include <stdexcept>
#include <utility>
#include <vector>
Expand Down Expand Up @@ -60,6 +61,7 @@ class MLXBatchedCache : public cache::Cache,
}

bool declare_step(const std::vector<int32_t>& seq_ids) override {
resolve_tree();
if (seq_ids.empty() ||
seq_ids.size() > static_cast<size_t>(std::numeric_limits<int>::max())) {
return false;
Expand Down Expand Up @@ -111,6 +113,80 @@ class MLXBatchedCache : public cache::Cache,
return true;
}

bool supports_tree_steps() const override {
return !geometry_.dflash_block_size.has_value();
}

// Each sequence's tokens are contiguous and form one tree rooted at the
// first of them.
bool declare_tree_step(
const std::vector<int32_t>& seq_ids,
const std::vector<int32_t>& parents) override {
if (!supports_tree_steps() || parents.size() != seq_ids.size()) {
return false;
}
// A malformed step leaves a pending tree pending.
std::set<int32_t> seen;
for (size_t i = 0; i < parents.size(); ++i) {
const bool first = i == 0 || seq_ids[i] != seq_ids[i - 1];
if (parents[i] < -1 || parents[i] >= static_cast<int32_t>(i) ||
(parents[i] >= 0 && seq_ids[parents[i]] != seq_ids[i]) ||
(parents[i] < 0) != first ||
(first && !seen.insert(seq_ids[i]).second)) {
return false;
}
}
if (!declare_step(seq_ids)) {
return false;
}
step_parents_ = parents;
return true;
}

bool retain_tree(const std::vector<int32_t>& keep) override {
if (!tree_) {
return false;
}
const Tree& tree = *tree_;
const int length = static_cast<int>(tree.parents.size());
std::vector<uint8_t> kept(length, 0);
for (int32_t index : keep) {
if (index < 0 || index >= length || kept[index]) {
return false;
}
kept[index] = 1;
}
// Kept tokens form root-to-node paths: a kept token's parent is kept and
// keeps no other child.
std::vector<uint8_t> children(length, 0);
for (int i = 0; i < length; ++i) {
const int32_t parent = tree.parents[i];
if (kept[i] && parent >= 0 && (!kept[parent] || children[parent]++)) {
return false;
}
}
std::vector<std::vector<int>> local(tree.spans.size());
for (size_t i = 0; i < tree.spans.size(); ++i) {
const Span& span = tree.spans[i];
for (int j = 0; j < span.q_len; ++j) {
if (kept[span.at + j]) {
local[i].push_back(j);
}
}
const auto& row = rows_.at(span.seq_id);
// The step's forward must be complete before any row changes.
if (row.length() != tree.bases[i] + span.q_len ||
!row.can_retain_tree(tree.bases[i], local[i])) {
return false;
}
}
for (size_t i = 0; i < tree.spans.size(); ++i) {
rows_.at(tree.spans[i].seq_id).retain_tree(tree.bases[i], local[i]);
}
invalidate_step();
return true;
}

std::optional<int> max_seqs() const override {
return std::nullopt;
}
Expand All @@ -125,6 +201,7 @@ class MLXBatchedCache : public cache::Cache,

std::optional<int32_t> seq_clone(int32_t src, std::optional<int> upto)
override {
resolve_tree();
auto it = rows_.find(src);
if (it == rows_.end() || it->second.length() == 0) {
return std::nullopt;
Expand All @@ -148,6 +225,7 @@ class MLXBatchedCache : public cache::Cache,
}

bool seq_rm(int32_t seq_id) override {
resolve_tree();
if (rows_.erase(seq_id) == 0) {
return false;
}
Expand All @@ -162,6 +240,7 @@ class MLXBatchedCache : public cache::Cache,
}

bool rewind(int32_t seq_id, int position) override {
resolve_tree();
if (!can_rewind(seq_id, position) || !rows_.at(seq_id).rewind(position)) {
return false;
}
Expand All @@ -171,7 +250,27 @@ class MLXBatchedCache : public cache::Cache,

int pos(int32_t seq_id) const override {
auto it = rows_.find(seq_id);
return it == rows_.end() ? 0 : it->second.length();
if (it == rows_.end()) {
return 0;
}
if (tree_) {
// As the next verb will leave it. A tree is pending once its forward
// has run on every layer (CellCache: once its first layer placed it);
// then that is its root and unbranched chain, before that nothing of
// it, since resolution drops an unfinished step.
for (size_t i = 0; i < tree_->spans.size(); ++i) {
const Span& span = tree_->spans[i];
if (span.seq_id == seq_id &&
it->second.length() == tree_->bases[i] + span.q_len) {
int kept = 0;
for (const int32_t node : unbranched_paths(tree_->parents)) {
kept += node >= span.at && node < span.at + span.q_len;
}
return tree_->bases[i] + kept;
}
}
}
return it->second.length();
}

Tensor attend(
Expand All @@ -183,6 +282,9 @@ class MLXBatchedCache : public cache::Cache,
float scale,
StreamOrDevice s) override {
validate_step(positions, q, k, v);
if (!step_parents_.empty()) {
return attend_tree(layer, positions, q, k, v, scale, s);
}
const auto query_spans = make_query_spans(layer, q.shape(2));
const auto& queries = query_spans.empty() ? spans_ : query_spans;

Expand Down Expand Up @@ -245,6 +347,91 @@ class MLXBatchedCache : public cache::Cache,
int group_at;
};

// A placed tree step, until retain_tree resolves it.
struct Tree {
std::vector<Span> spans;
std::vector<int> bases;
std::vector<int32_t> parents;
};

// Each tree's root and the chain below it, up to the first node with
// several children: the longest part that is one path.
static std::vector<int32_t> unbranched_paths(
const std::vector<int32_t>& parents) {
const int length = static_cast<int>(parents.size());
std::vector<int> children(length, 0), child(length, -1);
for (int i = 0; i < length; ++i) {
if (parents[i] >= 0) {
++children[parents[i]];
child[parents[i]] = i;
}
}
std::vector<int32_t> keep;
for (int i = 0; i < length; ++i) {
for (int node = parents[i] < 0 ? i : -1; node >= 0;
node = children[node] == 1 ? child[node] : -1) {
keep.push_back(node);
}
}
return keep;
}

// Settles an unretained tree before another verb: each tree keeps its root
// and the single path below it, up to the first branch. A step whose
// forward did not complete is dropped like an unfinished ordinary step.
void resolve_tree() {
if (!tree_) {
return;
}
if (!retain_tree(unbranched_paths(tree_->parents))) {
invalidate_step();
}
}

Tensor attend_tree(
int layer,
const std::vector<int32_t>& positions,
const Tensor& q,
const Tensor& k,
const Tensor& v,
float scale,
StreamOrDevice s) {
if (q.shape(2) != step_length()) {
throw std::invalid_argument("attend: a tree step queries every token");
}
if (!placed_) {
Tree tree{spans_, {}, step_parents_};
for (const Span& span : spans_) {
tree.bases.push_back(rows_.at(span.seq_id).length());
}
tree_ = std::move(tree);
step_pos_ = positions;
declared_ = false;
placed_ = true;
}
std::vector<Tensor> outs;
outs.reserve(spans_.size());
for (const Span& span : spans_) {
std::vector<int32_t> parents(
step_parents_.begin() + span.at,
step_parents_.begin() + span.at + span.q_len);
for (int32_t& parent : parents) {
parent = parent < 0 ? -1 : parent - span.at;
}
outs.push_back(rows_.at(span.seq_id)
.attend_tree(
layer,
parents,
tokens(q, span.at, span.q_len, s),
tokens(k, span.at, span.q_len, s),
tokens(v, span.at, span.q_len, s),
scale,
s));
}
return outs.size() == 1 ? std::move(outs.front())
: ::mlx::core::concatenate(outs, 2, s);
}

static Tensor tokens(const Tensor& t, int off, int len, StreamOrDevice s) {
if (off == 0 && len == t.shape(2)) {
return t;
Expand Down Expand Up @@ -351,6 +538,18 @@ class MLXBatchedCache : public cache::Cache,
}

bool check_positions(const std::vector<int32_t>& positions) const {
if (!step_parents_.empty()) {
for (const Span& span : spans_) {
const int base = rows_.at(span.seq_id).length();
for (int i = span.at; i < span.at + span.q_len; ++i) {
const int32_t parent = step_parents_[i];
if (positions[i] != (parent < 0 ? base : positions[parent] + 1)) {
return false;
}
}
}
return true;
}
std::map<int32_t, int64_t> ends;
size_t at = 0;
for (const Span& span : spans_) {
Expand Down Expand Up @@ -398,6 +597,8 @@ class MLXBatchedCache : public cache::Cache,
spans_.clear();
groups_.clear();
step_pos_.clear();
step_parents_.clear();
tree_.reset();
declared_ = false;
placed_ = false;
}
Expand All @@ -408,6 +609,8 @@ class MLXBatchedCache : public cache::Cache,
std::vector<Span> spans_;
std::vector<std::vector<size_t>> groups_;
std::vector<int32_t> step_pos_;
std::vector<int32_t> step_parents_;
std::optional<Tree> tree_;
bool declared_ = false;
bool placed_ = false;
};
Expand Down
Loading
Loading