Skip to content
Merged
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
43 changes: 41 additions & 2 deletions src/lib/mlxcel-core/cpp/mlx_cxx_bridge.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2965,7 +2965,41 @@ std::unique_ptr<MlxArray> dequantize(
int32_t bits,
rust::Str mode
) {
std::optional<array> biases_opt = biases ? std::optional(biases->inner) : std::nullopt;
// Force `biases` row-contiguous before handing it to MLX.
//
// `quantize_impl` in
// https://github.com/ml-explore/mlx/blob/main/mlx/backend/metal/quantized.cpp
// binds `w` (buffer 0) and `scales` (buffer 1) on the shared compute
// encoder and only afterwards calls `ensure_row_contiguous` on `biases`.
// When `biases` is strided, that call enqueues a copy kernel on the SAME
// encoder, and the copy rebinds buffers 0 and 1 to its own operands. The
// dequantize dispatch that follows therefore reads `w` and `scales` from
// the copy's operands instead of its own, and the affine kernel degenerates
// to `biases * (q + 1)` with `q` decoded from the raw bias bytes. The
// result is silently wrong, not an error.
//
// This is an upstream ordering defect, not a contract on the caller:
// `QuantizedMatmul::eval_gpu` in the same file hoists every
// `ensure_row_contiguous*` above its first binding, and so did
// `fast::Quantize::eval_gpu` until ml-explore/mlx#3757 folded it into the
// shared `quantize_impl`. That upstream change is in the MLX pin adopted by
// #1046 and is not in the pin before it.
//
// `biases` is the only input whose contiguity copy is enqueued after a
// binding, so it is the only one that needs the guard.
//
// The guard is unconditional on purpose. `array::flags()` is not meaningful
// until the array has been evaluated, and `biases` here is typically an
// unevaluated graph node, so a `flags().row_contiguous ? b : contiguous(b)`
// short-circuit would read a default-constructed flag and skip the copy
// exactly when it is needed. `Contiguous` costs an added graph node, and at
// eval it elides the data copy for a standalone row-contiguous input, so
// every in-tree caller (load time or absorb time, never per token) pays
// nothing measurable. Re-check this when the pinned MLX commit moves; the
// regression test is
// `mlxcel-core::ffi_tests::dequantize_commutes_with_output_axis_slice_on_strided_inputs`.
std::optional<array> biases_opt =
biases ? std::optional(mlx::core::contiguous(biases->inner)) : std::nullopt;
std::string mode_str(mode.data(), mode.size());

return std::make_unique<MlxArray>(mlx::core::dequantize(
Expand Down Expand Up @@ -3006,7 +3040,12 @@ std::unique_ptr<MlxArray> quantized_embedding(

std::string mode_str(mode.data(), mode.size());

// Dequantize with explicit optional wrapping
// Dequantize with explicit optional wrapping. This calls MLX directly
// rather than the `dequantize` shim above, so it does not inherit that
// shim's row-contiguity guard on `biases`. It is safe because `take`
// allocates a fresh row-contiguous output; keep it that way. Substituting a
// slice or any other view for the `take` reintroduces the silent miscompute
// documented on the shim.
auto result = mlx::core::dequantize(
w_indexed,
scales_indexed,
Expand Down
4 changes: 4 additions & 0 deletions src/lib/mlxcel-core/cpp/mlx_cxx_kernels.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1970,6 +1970,10 @@ std::unique_ptr<MlxArray> run_fused_moe_two_kernel(
// compute w*scale+bias inline in f32 registers, so a bf16-dequant
// truth would itself carry a per-weight rounding the production
// paths do not have.
// The `biases` argument must stay an `astype(take(...))` result
// (row-contiguous): this calls MLX directly, so it does not inherit the
// row-contiguity guard on `biases` carried by the `dequantize` shim in
// mlx_cxx_bridge.cpp, and a strided `biases` there miscomputes silently.
auto idx1 = astype(indices.inner, uint32);
auto dq_sel = [&](const array& w_q, const array& s_q, const array& b_q,
int bits_q) {
Expand Down
4 changes: 4 additions & 0 deletions src/lib/mlxcel-core/cpp/mlx_cxx_nemotron.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,10 @@ void nemotron_decode_step(
auto w_idx = take(m.embed_w->inner, flat_ids, 0);
auto s_idx = take(m.embed_s->inner, flat_ids, 0);
auto b_idx = take(m.embed_b->inner, flat_ids, 0);
// `b_idx` must stay a `take` result (row-contiguous) rather than a view:
// this calls MLX directly, so it does not inherit the row-contiguity guard
// on `biases` carried by the `dequantize` shim in mlx_cxx_bridge.cpp, and a
// strided `biases` there miscomputes silently.
auto h = dequantize(w_idx, s_idx, b_idx, m.gs, m.bits, "affine");
auto id_shape = input_ids.inner.shape();
h = reshape(h, {id_shape[0], id_shape[1], (int)h.shape().back()});
Expand Down
85 changes: 85 additions & 0 deletions src/lib/mlxcel-core/src/ffi_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3824,3 +3824,88 @@ fn qmv_multirow_matches_per_row_qmv_bitwise() {
}
}
}

/// `dequantize` must not depend on the memory layout of its inputs.
///
/// Slicing an affine-quantized triplet along a non-contiguous axis (splitting a
/// fused MoE `gate_up_proj` into its gate and up halves is the production case,
/// see `sanitize_gemma4_unified_weights`) leaves `weight`, `scales`, and
/// `biases` as strided views. MLX's Metal `quantize_impl`
/// (<https://github.com/ml-explore/mlx/blob/main/mlx/backend/metal/quantized.cpp>)
/// binds `w` and `scales` on the shared compute encoder before it materializes
/// a row-contiguous copy of `biases`, and that copy kernel rebinds buffers 0
/// and 1, so a strided `biases` silently turns the affine dequantization into
/// `biases * (q + 1)`. The `dequantize` shim in `mlx_cxx_bridge.cpp` guards
/// `biases` for exactly this reason; this test pins the guard so an MLX bump
/// that reintroduces the ordering (or a refactor that drops the guard) fails
/// here rather than in a model's output.
///
/// Dequantization is elementwise over the group axis, so slicing the output
/// axis must commute with it exactly: bit-identical, not merely close.
///
/// The test is differential, not tautological: the reference leg dequantizes
/// the whole tensor (contiguous inputs, guard inert) and the leg under test
/// dequantizes the slices (strided inputs, guard active). It was confirmed
/// non-vacuous by reverting the guard, which makes it fail with a 3.71 max
/// absolute difference. That failure is only reachable if `slice_axis` really
/// does hand back strided views here, so it doubles as a check that the
/// precondition still holds.
#[test]
fn dequantize_commutes_with_output_axis_slice_on_strided_inputs() {
const BITS: i32 = 4;
const GROUP_SIZE: i32 = 32;
let (experts, rows, in_features) = (2i32, 8i32, 64i32);
let packed_cols = in_features * BITS / 32;
let groups = in_features / GROUP_SIZE;

// Distinct values per (expert, row, column/group) so that a mis-bound
// buffer or a wrong-axis split cannot coincidentally agree.
let mut weight_data: Vec<u32> = Vec::new();
let mut scales_data: Vec<f32> = Vec::new();
let mut biases_data: Vec<f32> = Vec::new();
for e in 0..experts as u32 {
for r in 0..rows as u32 {
for c in 0..packed_cols as u32 {
weight_data.push(0x1234_5678u32.wrapping_add(e * 131 + r * 17 + c));
}
for g in 0..groups as u32 {
scales_data.push(0.05 + 0.01 * e as f32 + 0.001 * r as f32 + 0.0003 * g as f32);
biases_data.push(-0.2 + 0.02 * e as f32 - 0.003 * r as f32 + 0.0007 * g as f32);
}
}
}
let weight = from_slice_u32(&weight_data, &[experts, rows, packed_cols]);
let scales = from_slice_f32(&scales_data, &[experts, rows, groups]);
let biases = from_slice_f32(&biases_data, &[experts, rows, groups]);

let dq = |w: &MlxArray, s: &MlxArray, b: &MlxArray| unsafe {
dequantize(w, s, b as *const MlxArray, GROUP_SIZE, BITS, "affine")
};

// Reference: dequantize the whole tensor, then slice the output axis.
let full = dq(&weight, &scales, &biases);
let half = rows / 2;

for (name, start, stop) in [("first half", 0, half), ("second half", half, rows)] {
let expected = crate::utils::slice_axis(&full, 1, start, stop);
let w_slice = crate::utils::slice_axis(&weight, 1, start, stop);
let s_slice = crate::utils::slice_axis(&scales, 1, start, stop);
let b_slice = crate::utils::slice_axis(&biases, 1, start, stop);
let actual = dq(&w_slice, &s_slice, &b_slice);
assert_eq!(
array_shape(&actual),
vec![experts, half, in_features],
"{name}: shape"
);
eval(&expected);
eval(&actual);
// Compare bytes for the verdict but report the numeric gap: the byte
// vectors are 2 KiB each and a raw `assert_eq!` on them is unreadable.
let max_abs_diff = item_f32(&max_all(&abs(&subtract(&actual, &expected))));
assert!(
array_to_raw_bytes(&actual) == array_to_raw_bytes(&expected),
"{name}: dequantize(slice(x)) must equal slice(dequantize(x)) bit for bit \
(max abs diff {max_abs_diff})"
);
}
}
5 changes: 5 additions & 0 deletions src/lib/mlxcel-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1118,6 +1118,11 @@ mod ffi {

/// Dequantize quantized weights to full precision
/// biases: nullable for mxfp4/nvfp4/mxfp8 modes
///
/// `biases` is normalized to row-contiguous before the call. MLX's
/// Metal dequantize path miscomputes silently on a strided `biases`,
/// so callers may pass a sliced or otherwise strided view safely; see
/// the comment on the `dequantize` shim in `cpp/mlx_cxx_bridge.cpp`.
unsafe fn dequantize(
w: &MlxArray,
scales: &MlxArray,
Expand Down
8 changes: 8 additions & 0 deletions src/loading/vlm_gemma_unified.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,14 @@ fn emit_component_suffix(component: &str) -> &str {
/// no group straddling. This mirrors the `mistral4` / `qwen3_5_moe` fused
/// splits, which likewise slice the output axis of the already-`[E, out, in]`
/// tensor without transposing.
///
/// Both legs are strided views of the fused parent, not copies. That is
/// deliberate: `gather_qmm` / `quantized_matmul` receive the per-input batch
/// strides explicitly, so they consume the views zero-copy, and materializing
/// would allocate a second copy of every fused expert tensor at load time.
/// Consumers must therefore not assume row-contiguity here; `mlxcel_core::dequantize`
/// carries the one guard this requires (see the comment on the `dequantize`
/// shim in `src/lib/mlxcel-core/cpp/mlx_cxx_bridge.cpp`).
fn split_fused_gate_up_component(
value: &mlxcel_core::MlxArray,
component: &str,
Expand Down