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
34 changes: 34 additions & 0 deletions fork.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,40 @@ def:
- "tests/qmv_batch_invariant_tests.cpp"
- "tests/CMakeLists.txt"
- ".github/workflows/fork-tests.yml"
- title: "Prefill-row invariance scope (opt-in, per thread)"
description: |
A thread-local scope, `ThreadPrefillRows` in C++ and
`mlx_metal_set_thread_prefill_rows` in C, that names a number of reference rows.
`quantized_matmul` and `fast::scaled_dot_product_attention` read it when the op is
built and keep it in the primitive (`prefill_rows()`), so the route follows the
thread that built the graph, not the one that evaluates it; `is_equivalent` compares
it, autograd keeps it, and the compile cache keeps traces from inside and outside a
scope apart. In a scope a transposed, non-batched quantized product of two or more
rows takes `qmm_splitk` with the K split that the reference rows would get, and skips
the NAX split-K route, which chooses its split from the row count; head-dim 256 causal
or masked attention takes the fused NAX kernel from 16 queries instead of 1024. Each
row of a prompt chunk then has the same bits whatever the chunk's length, the
batch-invariant kernel idea of Thinking Machines (2025) applied to prompt chunks. Ops
built outside a scope, and with 0 rows, take the routes they took before; one-row
products keep `qmv`, and attention of 8 or fewer queries keeps the vector kernels.
`state()` is unchanged, so an exported graph imports with 0. `tests/prefill_rows_tests.cpp`
checks that ops built outside a scope keep their bits, that each short product in a
scope matches the same rows of a 4096-row product, that compiled functions trace again
in a scope, and the head-dim 256 attention route.
globs:
- "mlx/utils.h"
- "mlx/utils.cpp"
- "mlx/backend/common/command_buffer_limits.h"
- "mlx/primitives.h"
- "mlx/primitives.cpp"
- "mlx/ops.cpp"
- "mlx/fast_primitives.h"
- "mlx/fast.cpp"
- "mlx/compile.cpp"
- "mlx/backend/metal/quantized.cpp"
- "mlx/backend/metal/scaled_dot_product_attention.cpp"
- "tests/prefill_rows_tests.cpp"
- "tests/CMakeLists.txt"
- title: "GPT-OSS MXFP4 decode: masked-tail gathered qmv"
description: |
GPT-OSS 20B gathered MXFP4 decode has K=2880, which misses the fast vector kernel's
Expand Down
14 changes: 14 additions & 0 deletions mlx/backend/common/command_buffer_limits.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,20 @@ MLX_API void mlx_metal_set_thread_command_buffer_limits(
/// 32 x 32 whatever the tile.
MLX_API void mlx_metal_set_thread_qmm_steel_tile(int tile, int* previous_tile);

/// Reference row count for the quantized matmuls and attention ops that the
/// calling thread builds from now on; 0 ends the scope. Stores the thread's
/// previous value in `previous_rows` when it is not null. An op keeps the
/// value of the thread that builds it, whichever thread evaluates it. On the
/// GPU, a quantized `x @ w.T` of two or more rows built with `rows` > 0 splits
/// K as a product of `rows` rows would (and skips the NAX split-K kernel), so
/// a row's bits do not depend on how many rows share the call. Head-dim 256
/// causal or masked attention takes the fused NAX kernel from 16 queries
/// instead of 1024. Ops built with 0 are unchanged.
MLX_API void mlx_metal_set_thread_prefill_rows(int rows, int* previous_rows);

/// The calling thread's prefill reference rows (0 outside a scope).
MLX_API int mlx_metal_thread_prefill_rows(void);

#ifdef __cplusplus
}
#endif
Expand Down
37 changes: 32 additions & 5 deletions mlx/backend/metal/quantized.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1541,18 +1541,23 @@ void qmm_splitk(
int K,
metal::Device& d,
const Stream& s,
const std::string& mode) {
// The split-K NAX route.
if (use_qmm_nax_splitk(x, biases, mode, M, N, K, group_size)) {
const std::string& mode,
int ref_rows = 0) {
// The split-K NAX route. A product with reference rows (a prefill-row
// scope) skips it, because that route chooses its K split from M.
if (ref_rows == 0 &&
use_qmm_nax_splitk(x, biases, mode, M, N, K, group_size)) {
return qmm_splitk_nax(
x, w, scales, biases, out, group_size, bits, M, N, K, d, s, mode);
}

// Choose split_k to target ~512 threadgroups
// Choose split_k to target ~512 threadgroups, counted for `ref_rows` rows
// when they are given so that the split does not depend on M.
int bm = 32, bn = 32;
int n_tiles = (N + bn - 1) / bn;
int m_tiles = (M + bm - 1) / bm;
int current_tgs = n_tiles * m_tiles;
int split_m_tiles = ref_rows > 0 ? (ref_rows + bm - 1) / bm : m_tiles;
int current_tgs = n_tiles * split_m_tiles;
int split_k = std::max(1, 512 / current_tgs);

// Each K partition must be a whole number of BK-wide (32) K-tiles as well as
Expand Down Expand Up @@ -2510,6 +2515,28 @@ void QuantizedMatmul::eval_gpu(const std::vector<array>& inputs, array& out) {
// to the limit - 1.
bool vector_rows = env::qmv_batch_invariant() && M < vector_limit;

// A product built in a prefill-row scope (`thread_prefill_rows`) takes the
// split-K route with the K split of `prefill_rows_` rows from two rows on.
// Then each row has the same bits whatever the row count of the call.
if (prefill_rows_ > 0 && transpose_ && non_batched && M >= 2) {
qmm_splitk(
x,
w,
scales,
biases,
out,
group_size_,
bits_,
M,
N,
K,
d,
s,
mode,
prefill_rows_);
return;
}

// For few rows use qmv_mma when N/K is large enough.
if (!vector_rows && transpose_ && non_batched && (M >= 6) && (M <= 16) &&
use_qmv_mma(x, w, scales, mode_, M, N, K, d)) {
Expand Down
6 changes: 4 additions & 2 deletions mlx/backend/metal/scaled_dot_product_attention.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1446,10 +1446,12 @@ bool ScaledDotProductAttention::use_fallback(
}

// Use headdim-split kernel when NAX is enabled and there are enough query
// blocks to fill the machine.
// blocks to fill the machine. Inside a prefill-row scope it starts from 16
// queries, so a prompt chunk takes one kernel whatever its length.
const int d256_nax_min_queries = thread_prefill_rows() > 0 ? 16 : 1024;
if (metal::is_nax_available() &&
(env::enable_tf32() || q.dtype() != float32) &&
query_sequence_length >= 1024 && query_head_dim == 256 &&
query_sequence_length >= d256_nax_min_queries && query_head_dim == 256 &&
(do_causal || has_arr_mask)) {
return false;
}
Expand Down
13 changes: 10 additions & 3 deletions mlx/compile.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -323,10 +323,12 @@ std::uintptr_t get_function_address(const std::function<T(U...)>& fun) {
class CompileCache {
public:
struct CacheEntry {
CacheEntry(std::optional<Stream> stream, bool shapeless)
: stream(stream), shapeless(shapeless) {}
CacheEntry(std::optional<Stream> stream, bool shapeless, int prefill_rows)
: stream(stream), shapeless(shapeless), prefill_rows(prefill_rows) {}
std::optional<Stream> stream;
bool shapeless;
// The traced ops keep the prefill rows of the thread that traced them.
int prefill_rows;
std::vector<array> inputs;
std::vector<array> outputs;
std::vector<array> tape;
Expand Down Expand Up @@ -395,8 +397,10 @@ class CompileCache {
};
// Loop over entries and check:
// - Default stream and device match the entry's default stream
// - The thread's prefill rows match the entry's
// - Inputs match i.e. shapes and types must be equal.
auto stream = peek_default_stream(default_device());
int prefill_rows = thread_prefill_rows();
for (CacheEntry& entry : entries) {
// Check that the default stream and device match
if (entry.stream != stream) {
Expand All @@ -405,6 +409,9 @@ class CompileCache {
if (entry.shapeless != shapeless) {
continue;
}
if (entry.prefill_rows != prefill_rows) {
continue;
}

// Check the inputs match and return if so
if (has_same_shape_and_dtype(inputs, entry.inputs) &&
Expand All @@ -413,7 +420,7 @@ class CompileCache {
}
}
// Otherwise append a new cache entry
entries.push_back(CacheEntry{stream, shapeless});
entries.push_back(CacheEntry{stream, shapeless, prefill_rows});
return {entries.back(), std::move(entries_ptr)};
}

Expand Down
7 changes: 5 additions & 2 deletions mlx/fast.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include "mlx/ops.h"
#include "mlx/transforms.h"
#include "mlx/transforms_impl.h"
#include "mlx/utils.h"

namespace mlx::core::fast {

Expand Down Expand Up @@ -957,7 +958,8 @@ array scaled_dot_product_attention(
do_causal,
has_sinks,
output_logsumexp,
force_fused);
force_fused,
thread_prefill_rows());
if (output_logsumexp) {
return array::make_arrays(
{std::move(out_shape), Shape{q.shape(0), q.shape(1), q.shape(2), 1}},
Expand Down Expand Up @@ -1027,7 +1029,8 @@ bool ScaledDotProductAttention::is_equivalent(const Primitive& other) const {
return scale_ == a_other.scale_ && do_causal_ == a_other.do_causal_ &&
has_sinks_ == a_other.has_sinks_ &&
output_logsumexp_ == a_other.output_logsumexp_ &&
force_fused_ == a_other.force_fused_;
force_fused_ == a_other.force_fused_ &&
prefill_rows_ == a_other.prefill_rows_;
}

bool ScaledDotProductAttentionVJP::is_equivalent(const Primitive& other) const {
Expand Down
12 changes: 10 additions & 2 deletions mlx/fast_primitives.h
Original file line number Diff line number Diff line change
Expand Up @@ -276,13 +276,15 @@ class ScaledDotProductAttention : public Custom {
bool do_causal,
bool has_sinks,
bool output_logsumexp,
bool force_fused)
bool force_fused,
int prefill_rows = 0)
: Custom(stream, std::move(fallback)),
scale_(scale),
do_causal_(do_causal),
has_sinks_(has_sinks),
output_logsumexp_(output_logsumexp),
force_fused_(force_fused) {}
force_fused_(force_fused),
prefill_rows_(prefill_rows) {}

static bool use_fallback(
const array& q,
Expand Down Expand Up @@ -325,13 +327,19 @@ class ScaledDotProductAttention : public Custom {
output_logsumexp_,
force_fused_);
}
// The building thread's prefill reference rows (`thread_prefill_rows`).
// Not part of `state()`: an exported graph imports with 0.
int prefill_rows() const {
return prefill_rows_;
}

private:
float scale_;
bool do_causal_;
bool has_sinks_;
bool output_logsumexp_;
bool force_fused_;
int prefill_rows_;
};

class ScaledDotProductAttentionVJP : public Custom {
Expand Down
7 changes: 6 additions & 1 deletion mlx/ops.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4988,7 +4988,12 @@ array quantized_matmul(
std::move(out_shape),
dtype,
std::make_shared<QuantizedMatmul>(
to_stream(s), group_size, bits, qmode, transpose),
to_stream(s),
group_size,
bits,
qmode,
transpose,
thread_prefill_rows()),
std::move(inputs));
}

Expand Down
5 changes: 4 additions & 1 deletion mlx/primitives.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3622,6 +3622,7 @@ std::vector<array> QuantizedMatmul::vjp(
for (auto arg : argnums) {
// gradient wrt to x
if (arg == 0) {
ThreadPrefillRows scope(prefill_rows_);
vjps.push_back(quantized_matmul(
cotangents[0],
primals[1],
Expand Down Expand Up @@ -3686,6 +3687,7 @@ std::vector<array> QuantizedMatmul::jvp(
throw std::runtime_error(
"[QuantizedMatmul::jvp] No JVP wrt the quantized matrix yet.");
}
ThreadPrefillRows scope(prefill_rows_);
return {quantized_matmul(
tangents[0],
primals[1],
Expand All @@ -3702,7 +3704,8 @@ std::vector<array> QuantizedMatmul::jvp(
bool QuantizedMatmul::is_equivalent(const Primitive& other) const {
const QuantizedMatmul& qm_other = static_cast<const QuantizedMatmul&>(other);
return group_size_ == qm_other.group_size_ && bits_ == qm_other.bits_ &&
mode_ == qm_other.mode_ && transpose_ == qm_other.transpose_;
mode_ == qm_other.mode_ && transpose_ == qm_other.transpose_ &&
prefill_rows_ == qm_other.prefill_rows_;
}

std::vector<Shape> QuantizedMatmul::output_shapes(
Expand Down
12 changes: 10 additions & 2 deletions mlx/primitives.h
Original file line number Diff line number Diff line change
Expand Up @@ -1642,12 +1642,14 @@ class QuantizedMatmul : public UnaryPrimitive {
int group_size,
int bits,
QuantizationMode mode,
bool transpose)
bool transpose,
int prefill_rows = 0)
: UnaryPrimitive(stream),
group_size_(group_size),
bits_(bits),
mode_(mode),
transpose_(transpose) {}
transpose_(transpose),
prefill_rows_(prefill_rows) {}

void eval_cpu(const std::vector<array>& inputs, array& out) override;
void eval_gpu(const std::vector<array>& inputs, array& out) override;
Expand All @@ -1660,12 +1662,18 @@ class QuantizedMatmul : public UnaryPrimitive {
auto state() const {
return std::make_tuple(group_size_, bits_, mode_, transpose_);
}
// The building thread's prefill reference rows (`thread_prefill_rows`).
// Not part of `state()`: an exported graph imports with 0.
int prefill_rows() const {
return prefill_rows_;
}

private:
int group_size_;
int bits_;
QuantizationMode mode_;
bool transpose_;
int prefill_rows_;
};

class QQMatmul : public UnaryPrimitive {
Expand Down
31 changes: 31 additions & 0 deletions mlx/utils.cpp
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
// Copyright © 2023 Apple Inc.

#include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <thread>
#include <vector>

#include "mlx/backend/common/command_buffer_limits.h"
#include "mlx/dtype_utils.h"
#include "mlx/types/limits.h"
#include "mlx/utils.h"
Expand Down Expand Up @@ -289,6 +291,20 @@ std::ostream& operator<<(std::ostream& os, array a) {
return os;
}

namespace {
thread_local int thread_prefill_rows_ = 0;
} // namespace

int thread_prefill_rows() {
return thread_prefill_rows_;
}

int set_thread_prefill_rows(int rows) {
int previous = thread_prefill_rows_;
thread_prefill_rows_ = std::max(0, rows);
return previous;
}

namespace env {

int get_var(const char* name, int default_value) {
Expand Down Expand Up @@ -356,3 +372,18 @@ iinfo::iinfo(Dtype dtype) : dtype(dtype) {
}

} // namespace mlx::core

#if defined(__APPLE__)
extern "C" void mlx_metal_set_thread_prefill_rows(
int rows,
int* previous_rows) {
int previous = mlx::core::set_thread_prefill_rows(rows);
if (previous_rows != nullptr) {
*previous_rows = previous;
}
}

extern "C" int mlx_metal_thread_prefill_rows(void) {
return mlx::core::thread_prefill_rows();
}
#endif
Loading
Loading