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
9 changes: 5 additions & 4 deletions .github/workflows/fork-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -209,16 +209,17 @@ jobs:
ctest --test-dir build -R '^qmv_batch_invariant$' \
--output-on-failure --no-tests=error

- name: Run the quantized matmul rows with MLX_QMV_ROW_EXACT=16
- name: Run the quantized matmul rows with their switches
# MLX reads the row limit once in each process. The C++ test steps
# above run the case with the row-exact kernel off; these ctest entries
# run it with the kernel on, and the batch-invariant case with the two
# switches (tests/CMakeLists.txt).
# run it with the kernel on, the batch-invariant case with the two
# switches, and the broadcast case with MLX_QMV_ROWS_BROADCAST=0
# (tests/CMakeLists.txt).
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
env:
LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/qmv-rows-%p-%m.profraw
run: |
ctest --test-dir build -R '^qmv_row_exact' \
ctest --test-dir build -R '^qmv_row' \
--output-on-failure --no-tests=error

- name: Merge the coverage profiles
Expand Down
16 changes: 15 additions & 1 deletion docs/src/usage/environment_variables.rst
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,21 @@ Metal
``MLX_QMV_BATCH_INVARIANT=1`` also, the kernel serves each row count below
the vector limit, thus a row keeps its bits from 1 row to the limit minus
1. The default, ``0``, does not use the kernel. MLX reads this variable
once in each process.
once in each process. The kernel also serves 2 bits where ``qmv`` uses its
fast kernel (K a multiple of 512).

.. envvar:: MLX_QMV_ROWS_BROADCAST

A batch of one-row quantized products with one weight matrix (``x`` of
shape ``[..., 1, K]`` and the weights, scales and biases broadcast over the
batch) uses the row-exact kernel of ``MLX_QMV_ROW_EXACT``. The batched
``qmv`` gives each row the bits that the row gets alone, and so does the
row-exact kernel, which reads the weights once for each tile of rows
instead of once for each row. Thus the bits do not change. It serves the
affine mode with 4 or 8 bits, or 2 bits where ``qmv`` uses its fast
kernel, and a group size of 32, 64 or 128; other products keep the batched
``qmv``. The default, ``1``, uses the kernel; ``0`` keeps the batched
``qmv``. MLX reads this variable once in each process.

Advanced tuning
---------------
Expand Down
27 changes: 27 additions & 0 deletions fork.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,33 @@ def:
- "tests/qmv_row_exact_tests.cpp"
- "tests/CMakeLists.txt"
- ".github/workflows/fork-tests.yml"
- title: "Row kernel for broadcast batches of one-row products, and 2 bits"
description: |
`affine_qmv_rows` also serves 2 bits where `qmv` uses its fast kernel (K a multiple
of 512): for each row the expressions of `load_vector` and `qdot` for 2 bits and one
pack per thread, as in `qmv_fast_impl`. A batch of one-row products with one weight
matrix (`x` of shape `[..., 1, K]` with contiguous rows, and the weights, scales and
biases broadcast over the batch) now runs `affine_qmv_rows` instead of the batched
`qmv` (`MLX_QMV_ROWS_BROADCAST`, read once in each process, default 1; 0 keeps the
batched `qmv`). Both give each row the bits that `qmv` gives the row alone, so no
output bit changes; the kernel reads the weights once for each tile of up to 8 rows
(2 or 4 bits) or 6 rows (8 bits) instead of once for each row. The signed-Hadamard
2-bit linear layers of mlx-swift (`HadamardQuantizedLinear`) send their multi-row
projections this way to keep each row's bits, so their prefill and batched decode
read the weights once per tile. K = 64 and K = 128 (`qmv_quad`), 2 bits outside the
fast kernel, other modes and bit widths keep the batched `qmv`.
`tests/qmv_row_exact_tests.cpp` compares the bytes of each row of broadcast batches of
2 to 19 rows, and of row-exact products with 2 bits, with the same row alone; the
`qmv_rows_broadcast_off` ctest entry runs the broadcast case with the batched `qmv`.
globs:
- "mlx/utils.h"
- "mlx/backend/metal/quantized.cpp"
- "mlx/backend/metal/kernels/quantized.h"
- "mlx/backend/metal/kernels/quantized.metal"
- "docs/src/usage/environment_variables.rst"
- "tests/qmv_row_exact_tests.cpp"
- "tests/CMakeLists.txt"
- ".github/workflows/fork-tests.yml"
- 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
31 changes: 26 additions & 5 deletions mlx/backend/metal/kernels/quantized.h
Original file line number Diff line number Diff line change
Expand Up @@ -1994,6 +1994,7 @@ template <
// The affine qmv for 2 to 8 rows of x in one launch. Each row gets the bits of
// the one-row kernel (qmv_fast_impl if fast, else qmv_impl): the same lanes,
// expressions and order of additions. The rows share only the weight read.
// 2 bits are served only where the one-row kernel is qmv_fast_impl.
template <typename T, int group_size, int bits, bool fast, int rows>
[[kernel]] void affine_qmv_rows(
const device uint32_t* w [[buffer(0)]],
Expand All @@ -2008,17 +2009,21 @@ template <typename T, int group_size, int bits, bool fast, int rows>
uint simd_gid [[simdgroup_index_in_threadgroup]],
uint simd_lid [[thread_index_in_simdgroup]]) {
static_assert(
bits == 4 || bits == 8, "Template undefined for bits not in {4, 8}");
bits == 2 || bits == 4 || bits == 8,
"Template undefined for bits not in {2, 4, 8}");
static_assert(bits != 2 || fast, "2 bits need the qmv_fast_impl layout");
constexpr int num_simdgroups = 4;
constexpr int results_per_simdgroup = 2;
constexpr int packs_per_thread = fast ? 2 : 1;
// As qmv_fast_impl: one pack per thread for 2 bits.
constexpr int packs_per_thread = fast && bits != 2 ? 2 : 1;
constexpr int pack_factor = get_affine_pack_factor<bits, 32>();
constexpr int bytes_per_pack = get_bytes_per_pack<bits, 32>();
constexpr int values_per_thread = pack_factor * packs_per_thread;
constexpr int block_size = values_per_thread * SIMD_SIZE;
constexpr int scale_step_per_thread = group_size / values_per_thread;
// A thread keeps the weights of a block as 16-bit words (4 bits) or bytes.
constexpr int words = bits == 4 ? values_per_thread / 4 : values_per_thread;
// A thread keeps the weights of a block as 16-bit words (4 bits) or bytes
// (4 values of 2 bits, or one value of 8 bits).
constexpr int words = bits == 8 ? values_per_thread : values_per_thread / 4;

typedef float U;

Expand Down Expand Up @@ -2074,7 +2079,23 @@ template <typename T, int group_size, int bits, bool fast, int rows>
for (int row = 0; row < results_per_simdgroup; row++) {
accum[row] = 0;
}
if (bits == 4) {
if (bits == 2) {
// load_vector and qdot for 2 bits.
for (int i = 0; i < words; i++) {
sum += U(xl[4 * i]) + U(xl[4 * i + 1]) + U(xl[4 * i + 2]) +
U(xl[4 * i + 3]);
U x0 = xl[4 * i];
U x1 = xl[4 * i + 1] / 4.0f;
U x2 = xl[4 * i + 2] / 16.0f;
U x3 = xl[4 * i + 3] / 64.0f;
for (int row = 0; row < results_per_simdgroup; row++) {
uint8_t wi = uint8_t(wv[row * words + i]);
accum[row] +=
(x0 * (wi & 0x03) + x1 * (wi & 0x0c) + x2 * (wi & 0x30) +
x3 * (wi & 0xc0));
}
}
} else if (bits == 4) {
for (int i = 0; i < words; i++) {
sum += U(xl[4 * i]) + U(xl[4 * i + 1]) + U(xl[4 * i + 2]) +
U(xl[4 * i + 3]);
Expand Down
1 change: 1 addition & 0 deletions mlx/backend/metal/kernels/quantized.metal
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@ instantiate_quantized_all()
instantiate_quantized_rows(type, group_size, bits, fast, 8)

#define instantiate_quantized_rows_bits(type, group_size) \
instantiate_quantized_rows_counts(type, group_size, 2, 1) \
instantiate_quantized_rows_counts(type, group_size, 4, 0) \
instantiate_quantized_rows_counts(type, group_size, 4, 1) \
instantiate_quantized_rows_counts(type, group_size, 8, 0) \
Expand Down
79 changes: 74 additions & 5 deletions mlx/backend/metal/quantized.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -638,8 +638,9 @@ void qmv_wide(
compute_encoder.dispatch_threadgroups(grid_dims, group_dims);
}

// The row-exact kernel (qmv_rows) serves the affine x @ w.T with 4 or 8 bits
// for 2 rows up to row_limit, which comes from MLX_QMV_ROW_EXACT.
// The row-exact kernel (qmv_rows) serves the affine x @ w.T with 4 or 8 bits,
// or with 2 bits where qmv uses its fast kernel, for 2 rows up to row_limit,
// which comes from MLX_QMV_ROW_EXACT.
inline bool use_qmv_rows(
const std::optional<array>& biases,
QuantizationMode mode,
Expand All @@ -652,15 +653,53 @@ inline bool use_qmv_rows(
int row_limit) {
return M >= 2 && M <= row_limit && transpose && non_batched &&
mode == QuantizationMode::Affine && biases.has_value() &&
(bits == 4 || bits == 8) &&
(bits == 4 || bits == 8 ||
(bits == 2 && K % qmv_fast_k_alignment(bits) == 0)) &&
(group_size == 32 || group_size == 64 || group_size == 128) &&
K % group_size == 0;
}

// True if the batch dimensions of a (all but the last two) are broadcast: every
// matrix of the batch is the first one.
inline bool is_broadcast_batch(const array& a) {
for (int i = 0; i + 2 < a.ndim(); ++i) {
if (a.shape(i) > 1 && a.strides()[i] != 0) {
return false;
}
}
return true;
}

// A batch of one-row products with one weight matrix: x is [..., 1, K] with
// contiguous rows, and the weights, scales and biases are broadcast over the
// batch. The batched qmv gives each row the bits that qmv gives the row alone,
// and so does affine_qmv_rows, which reads the weights once for a tile of rows
// (MLX_QMV_ROWS_BROADCAST, on by default).
inline bool use_qmv_rows_broadcast(
const array& x,
const array& w,
const array& scales,
const std::optional<array>& biases,
QuantizationMode mode,
bool transpose,
bool non_batched,
int group_size,
int bits,
int M,
int K) {
int rows = x.size() / K;
return env::qmv_rows_broadcast() && M == 1 && !non_batched && rows >= 2 &&
K != 64 && K != 128 && x.flags().row_contiguous &&
is_broadcast_batch(w) && is_broadcast_batch(scales) &&
biases.has_value() && is_broadcast_batch(*biases) &&
use_qmv_rows(
biases, mode, transpose, true, group_size, bits, rows, K, rows);
}

// Dispatches affine_qmv_rows: each row of x gets the bits that qmv gives it
// alone, and one launch reads each weight once for a tile of rows. A tile has
// up to 8 rows (4 bits) or 6 rows (8 bits, where 7 or 8 rows are slower than
// two tiles).
// up to 8 rows (2 or 4 bits) or 6 rows (8 bits, where 7 or 8 rows are slower
// than two tiles). w, scales and biases are read as one matrix each.
void qmv_rows(
const array& x,
const array& w,
Expand Down Expand Up @@ -2593,6 +2632,36 @@ 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 batch of one-row products with one weight matrix keeps the bits of the
// batched qmv and reads the weights once for each tile of rows.
if (use_qmv_rows_broadcast(
x,
w,
scales,
biases,
mode_,
transpose_,
non_batched,
group_size_,
bits_,
M,
K)) {
qmv_rows(
x,
w,
scales,
*biases,
out,
group_size_,
bits_,
x.size() / K,
N,
K,
d,
s);
return;
}

// With MLX_QMV_ROW_EXACT, each row of a few rows has the bits of the row
// alone. One row of K = 64 or 128 is qmv_quad, which makes each row alone.
// With MLX_QMV_BATCH_INVARIANT also, the kernel serves each row count below
Expand Down
9 changes: 9 additions & 0 deletions mlx/utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,15 @@ inline int qmv_row_exact() {
return rows_;
}

// A batch of one-row quantized products with one weight matrix uses the
// row-exact kernel, which gives each row the bits of the batched qmv and reads
// the weights once per tile of rows (see `use_qmv_rows_broadcast` in
// backend/metal/quantized.cpp). On by default; 0 is off.
inline bool qmv_rows_broadcast() {
static bool on_ = get_var("MLX_QMV_ROWS_BROADCAST", 1);
return on_;
}

inline bool metal_fast_synch() {
static bool metal_fast_synch = get_var("MLX_METAL_FAST_SYNCH", 0);
return metal_fast_synch;
Expand Down
12 changes: 12 additions & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,18 @@ if(MLX_BUILD_METAL)
qmv_row_exact
PROPERTIES ENVIRONMENT "MLX_QMV_ROW_EXACT=16" PASS_REGULAR_EXPRESSION
"test cases: +1 \\| +1 passed \\| +0 failed")
# MLX reads MLX_QMV_ROWS_BROADCAST once in each process, so this entry runs
# the broadcast case with the batched qmv. The tests entries run it with the
# row-exact kernel (the default).
add_test(
NAME qmv_rows_broadcast_off
COMMAND
tests
"--test-case=quantized matmul broadcast batches keep the bits of one row")
set_tests_properties(
qmv_rows_broadcast_off
PROPERTIES ENVIRONMENT "MLX_QMV_ROWS_BROADCAST=0" PASS_REGULAR_EXPRESSION
"test cases: +1 \\| +1 passed \\| +0 failed")
# With the two switches, the row-exact kernel serves each row count below the
# vector limit, and the batch-invariant case must stay correct.
add_test(
Expand Down
74 changes: 72 additions & 2 deletions tests/qmv_row_exact_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,10 @@ TEST_CASE("quantized matmul rows keep the bits of one row") {
{9, 128},
{64, 64}};
for (auto [N, K] : shapes) {
for (int bits : {4, 8}) {
for (int bits : {2, 4, 8}) {
for (int group_size : {32, 64, 128}) {
if (K % group_size != 0) {
// 2 bits are served where the one-row kernel is the fast one.
if (K % group_size != 0 || (bits == 2 && K % 512 != 0)) {
continue;
}
for (auto dtype : {float32, float16, bfloat16}) {
Expand Down Expand Up @@ -136,3 +137,72 @@ TEST_CASE("quantized matmul rows keep the bits of one row") {
}
}
}

TEST_CASE("quantized matmul broadcast batches keep the bits of one row") {
// A batch of one-row products with one weight matrix (x [..., 1, K], the
// weights broadcast over the batch). With MLX_QMV_ROWS_BROADCAST on (the
// default) the row-exact kernel serves it; the qmv_rows_broadcast_off ctest
// entry runs this case with the batched qmv (tests/CMakeLists.txt). Each row
// must have the bytes of the row alone either way.
const char* value = std::getenv("MLX_QMV_ROWS_BROADCAST");
bool on = value == nullptr || std::atoi(value) != 0;
REQUIRE(env::qmv_rows_broadcast() == on);

// K selects the one-row kernel: fast (K a multiple of 512 for 2 and 4 bits,
// of 256 for 8 bits), general (with a short last block), or qmv_quad
// (K = 64 or 128). 2 bits outside the fast kernel keep the batched qmv.
std::vector<std::pair<int, int>> shapes = {
{2048, 1024}, {61, 5120}, {1, 2048}, {1000, 768}, {5, 320}, {9, 128}};
for (auto [N, K] : shapes) {
for (int bits : {2, 4, 8}) {
for (int group_size : {32, 64, 128}) {
if (K % group_size != 0) {
continue;
}
for (auto dtype : {float32, float16, bfloat16}) {
CAPTURE(N);
CAPTURE(K);
CAPTURE(bits);
CAPTURE(group_size);
CAPTURE(dtype);
auto q = weights(N, K, group_size, bits, dtype, N + K + bits + 7);
Weights b{
group_size,
bits,
expand_dims(q.w, 0, Device::gpu),
expand_dims(q.scales, 0, Device::gpu),
expand_dims(q.biases, 0, Device::gpu)};
constexpr int count = 19;
auto x = astype(
random::normal(
{count, K},
float32,
0.0f,
1.0f,
random::key(K + 1),
Device::gpu),
dtype,
Device::gpu);
std::vector<array> alone;
for (int i = 0; i < count; ++i) {
alone.push_back(product(q, rows(x, i, i + 1)));
}
auto singles = concatenate(alone, 0, Device::gpu);
eval(singles);
// 2 to 19 rows: one tile, two tiles and a partial last tile.
for (int m : {2, 3, 7, 8, 9, 16, 19}) {
CAPTURE(m);
auto y = product(b, reshape(rows(x, 0, m), {m, 1, K}, Device::gpu));
CHECK(same_bytes(
reshape(y, {m, N}, Device::gpu), rows(singles, 0, m)));
}
// Two batch dimensions are more rows of one batch.
auto y =
product(b, reshape(rows(x, 0, 6), {2, 3, 1, K}, Device::gpu));
CHECK(
same_bytes(reshape(y, {6, N}, Device::gpu), rows(singles, 0, 6)));
}
}
}
}
}
Loading