mirror of
https://github.com/ollama/ollama.git
synced 2026-12-04 00:21:20 +00:00
mlx: speed up batched Inkling target verification on Metal (#20016)
* mlx: speed up batched Inkling target verification on Metal Reuse expert route metadata across output tiles in wide NVFP4 and MXFP8 gathers. Share the Inkling NVFP4 route plan across gate/up and down, and use matrix tiles when at least five routes share an expert. Run short target projections in a single tiled dispatch while preserving per-row FP32 reduction order and the vocabulary softcap. Keep the published weights, trained 4-over-6 activation quantizer, and cache dtypes. Matrix expert tiles accumulate in FP32 with a different summation order. * address comments
This commit is contained in:
1 parent
07798c63ed
commit
97e8bebfda
7 files changed
+945
-41
No files matched your search
@@ -0,0 +1,245 @@
|
||||
package mlx
|
||||
|
||||
import "math"
|
||||
|
||||
// InklingNVFP4ExpertPlan shares route runs between Inkling's quantized gate/up
|
||||
// and down projections. The matrix tile accepts only the reconstructed values
|
||||
// from QuantizeNVFP4Activation4Over6, which fit BF16 exactly. Its FP32 reduction
|
||||
// can differ from the vector gather and is intentionally scoped to Inkling.
|
||||
// Use the plan within the MLX scope that created it.
|
||||
type InklingNVFP4ExpertPlan struct {
|
||||
indices, table *Array
|
||||
}
|
||||
|
||||
// NewInklingNVFP4ExpertPlan prepares [rows, 8] route IDs for one forward.
|
||||
// It returns nil when the shape or Metal device is unsupported.
|
||||
func NewInklingNVFP4ExpertPlan(indices *Array) *InklingNVFP4ExpertPlan {
|
||||
if indices == nil || indices.NumDims() != 2 || indices.Dim(1) != 8 ||
|
||||
indices.Dim(0) < 16 || indices.Dim(0) > 128 ||
|
||||
(indices.DType() != DTypeUint32 && indices.DType() != DTypeInt32) ||
|
||||
!MetalIsAvailable() || !hasMetalTensorOps() {
|
||||
return nil
|
||||
}
|
||||
generation, _ := appleGPU(kernelArchitecture())
|
||||
if generation < 17 {
|
||||
return nil
|
||||
}
|
||||
// Bind the table and both projections to the same IDs even if the caller
|
||||
// later reassigns its array handle.
|
||||
indices = indices.Clone()
|
||||
table := shortGatherRouteTableFor(indices, 16)
|
||||
if table == nil {
|
||||
return nil
|
||||
}
|
||||
return &InklingNVFP4ExpertPlan{indices: indices, table: table}
|
||||
}
|
||||
|
||||
// GateUp applies the original per-route SwiGLU epilogue before the down
|
||||
// projection's activation quantization. It returns BF16 [rows*8, 1152],
|
||||
// or nil when the projection cannot run. Out-of-range IDs produce NaN.
|
||||
func (p *InklingNVFP4ExpertPlan) GateUp(x, weight, scales, xmax, maxima, denominator, scores *Array,
|
||||
gateCap, upCap float32, maxProduct int,
|
||||
) *Array {
|
||||
if p == nil || p.indices == nil {
|
||||
return nil
|
||||
}
|
||||
rows, topK := p.indices.Dim(0), p.indices.Dim(1)
|
||||
if xmax == nil || maxima == nil || denominator == nil || scores == nil ||
|
||||
xmax.DType() != DTypeFloat32 || xmax.Size() != rows ||
|
||||
maxima.DType() != DTypeFloat32 || maxima.Size() != 128 ||
|
||||
denominator.DType() != DTypeFloat32 || denominator.Size() != 1 ||
|
||||
scores.DType() != DTypeFloat32 || scores.Size() != rows*topK {
|
||||
return nil
|
||||
}
|
||||
return p.project(x, weight, scales, inklingNVFP4MatrixGateUp, 1, 2304, topK,
|
||||
[]*Array{xmax, maxima, denominator.Reshape(1), scores}, []gpuIntArg{
|
||||
{"XmaxStride", topK},
|
||||
{"MaxProduct", maxProduct},
|
||||
{"GateCapBits", int(math.Float32bits(gateCap))},
|
||||
{"UpCapBits", int(math.Float32bits(upCap))},
|
||||
}, gpuOutputSpec{"inkling_expert_gated", []int32{int32(rows * topK), 1152}, DTypeBFloat16})
|
||||
}
|
||||
|
||||
// Down returns FP32 [rows, 8, 1, 2304] dot products for Inkling's expert sum,
|
||||
// or nil when the projection cannot run. Out-of-range IDs produce NaN.
|
||||
func (p *InklingNVFP4ExpertPlan) Down(x, weight, scales *Array) *Array {
|
||||
if p == nil || p.indices == nil {
|
||||
return nil
|
||||
}
|
||||
rows, topK := p.indices.Dim(0), p.indices.Dim(1)
|
||||
return p.project(x, weight, scales, inklingNVFP4MatrixDown, topK, 1152, 1, nil, nil,
|
||||
gpuOutputSpec{"inkling_expert_down", []int32{int32(rows), int32(topK), 1, 2304}, DTypeFloat32})
|
||||
}
|
||||
|
||||
func (p *InklingNVFP4ExpertPlan) project(x, weight, scales *Array, kernel *gpuKernel,
|
||||
activationRows, width, rowStep int, epilogueInputs []*Array, epilogueArgs []gpuIntArg, output gpuOutputSpec,
|
||||
) *Array {
|
||||
const channels = 2304
|
||||
if x == nil || weight == nil || scales == nil ||
|
||||
x.NumDims() != 4 || x.DType() != DTypeFloat32 ||
|
||||
weight.NumDims() != 3 || weight.DType() != DTypeUint32 ||
|
||||
scales.NumDims() != 3 || scales.DType() != DTypeUint8 ||
|
||||
x.Dim(0) != p.indices.Dim(0) || x.Dim(1) != activationRows || x.Dim(2) != 1 || x.Dim(3) != width ||
|
||||
weight.Dim(0) != 128 || weight.Dim(1) != channels || weight.Dim(2) != width/8 ||
|
||||
scales.Dim(0) != 128 || scales.Dim(1) != channels || scales.Dim(2) != width/16 {
|
||||
return nil
|
||||
}
|
||||
out, ok := kernel.applyMetal(gpuLaunch{
|
||||
inputs: append([]*Array{x, weight, scales, p.indices, p.table}, epilogueInputs...),
|
||||
ints: append([]gpuIntArg{
|
||||
{"Width", width},
|
||||
{"Channels", channels},
|
||||
{"RowStep", rowStep},
|
||||
{"TileRows", 16},
|
||||
{"MatrixRows", 16},
|
||||
{"KTile", 64},
|
||||
{"VectorOutputs", 4},
|
||||
{"DispatchChannels", 32},
|
||||
}, epilogueArgs...),
|
||||
outputs: []gpuOutputSpec{output},
|
||||
grid: [3]int{channels / 32 * 128, p.indices.Size(), 1},
|
||||
threadGroup: [3]int{128, 1, 1},
|
||||
})
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return out[0]
|
||||
}
|
||||
|
||||
var inklingNVFP4MatrixDown = &gpuKernel{
|
||||
name: "inkling_nvfp4_matrix_down",
|
||||
inputs: []string{"x", "weight", "scales", "ids", "route_table"}, outputs: []string{"out"},
|
||||
metal: gpuSource{header: inklingNVFP4MatrixMetalHeader, source: inklingNVFP4MatrixMetalSource},
|
||||
}
|
||||
|
||||
var inklingNVFP4MatrixGateUp = &gpuKernel{
|
||||
name: "inkling_nvfp4_matrix_gate_up",
|
||||
inputs: []string{"x", "weight", "scales", "ids", "route_table", "xmax", "maxima", "denominator", "scores"}, outputs: []string{"out"},
|
||||
metal: gpuSource{header: inklingNVFP4MatrixMetalHeader + expertSwiGLUMetal + "#define FUSED_GATE 1\n", source: inklingNVFP4MatrixMetalSource},
|
||||
}
|
||||
|
||||
const inklingNVFP4MatrixMetalHeader = shortGatherHeader + shortGatherNVFP4Header + `
|
||||
#include <metal_tensor>
|
||||
#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h>
|
||||
`
|
||||
|
||||
const inklingNVFP4MatrixMetalSource = `
|
||||
using dims = dextents<int, 2>;
|
||||
using strides = array<int, 2>;
|
||||
using namespace mpp::tensor_ops;
|
||||
constexpr int channelsPerGroup = 64, channelsPerSimd = 16, kTile = KTile;
|
||||
const uint route = threadgroup_position_in_grid.y;
|
||||
const uint xtile = threadgroup_position_in_grid.x;
|
||||
const uint channel = xtile * DispatchChannels;
|
||||
const uint worker = thread_index_in_threadgroup, sg = simdgroup_index_in_threadgroup;
|
||||
const uint first = channel + sg * channelsPerSimd;
|
||||
const uint expert = uint(ids[route]);
|
||||
if (expert >= uint(weight_shape[0])) {
|
||||
#if FUSED_GATE
|
||||
if (worker < DispatchChannels / 2) out[route * (Channels / 2) + channel / 2 + worker] = bfloat(NAN);
|
||||
#else
|
||||
if (worker < DispatchChannels) out[route * Channels + channel + worker] = NAN;
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
const uint meta = route * (TileRows + 1);
|
||||
const uint count = route_table[meta];
|
||||
if (count == 0) return;
|
||||
constexpr uint sparseSlots = 4;
|
||||
if (count <= sparseSlots) {
|
||||
constexpr uint columnsPerSimd = DispatchChannels / 4;
|
||||
const uint vectorStart = channel + sg * columnsPerSimd;
|
||||
uint owners[sparseSlots];
|
||||
for (uint j = 0; j < sparseSlots; ++j) owners[j] = route_table[meta + 1 + j];
|
||||
const uint lane = thread_index_in_simdgroup;
|
||||
#if FUSED_GATE
|
||||
constexpr uint pairs = VectorOutputs / 2;
|
||||
const uint j = lane / pairs, pair = lane % pairs;
|
||||
const float denom = denominator[0] * float(MaxProduct);
|
||||
const float gateCap = as_type<float>(GateCapBits), upCap = as_type<float>(UpCapBits);
|
||||
#else
|
||||
const uint j = lane / VectorOutputs, component = lane % VectorOutputs;
|
||||
#endif
|
||||
for (uint col = vectorStart; col < vectorStart + columnsPerSimd; col += VectorOutputs) {
|
||||
float dots[VectorOutputs][sparseSlots] = {};
|
||||
gather_dots<sparseSlots, VectorOutputs, sparseSlots, Width, RowStep, 8>(
|
||||
count, x, weight, scales, ulong(expert) * Channels + col, owners, lane, dots);
|
||||
if (j < count) {
|
||||
const uint owner = pick_route(owners, j);
|
||||
#if FUSED_GATE
|
||||
const float scale = (xmax[owner / XmaxStride] * maxima[expert]) / denom;
|
||||
const float value = expert_swiglu(pick_dot(dots, 2 * pair, j), pick_dot(dots, 2 * pair + 1, j),
|
||||
scale, scores[owner], gateCap, upCap);
|
||||
out[owner * (Channels / 2) + col / 2 + pair] = bfloat(value);
|
||||
#else
|
||||
out[owner * Channels + col + component] = pick_dot(dots, component, j);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Native matrix work retains one workgroup per 64 output channels.
|
||||
if (xtile % (channelsPerGroup / DispatchChannels) != 0) return;
|
||||
threadgroup vec<bfloat, 8> leftStorage[MatrixRows * kTile / 8], rightStorage[channelsPerGroup * kTile / 8];
|
||||
threadgroup bfloat* left = reinterpret_cast<threadgroup bfloat*>(leftStorage);
|
||||
threadgroup bfloat* right = reinterpret_cast<threadgroup bfloat*>(rightStorage);
|
||||
threadgroup float tile[MatrixRows * channelsPerGroup];
|
||||
using matrixInput = tensor<threadgroup bfloat, dims, tensor_inline>;
|
||||
constexpr matmul2d_descriptor shape(MatrixRows, channelsPerSimd, kTile, false, true, true,
|
||||
matmul2d_descriptor::mode::multiply_accumulate);
|
||||
matmul2d<shape, execution_simdgroup> dot;
|
||||
auto accum = dot.template get_destination_cooperative_tensor<matrixInput, matrixInput, float>();
|
||||
for (uint i = 0; i < accum.get_capacity(); ++i) accum[i] = 0.0f;
|
||||
for (uint k = 0; k < Width; k += kTile) {
|
||||
// A word covers eight codes and two words share a scale. Decode each
|
||||
// 16-element block together and keep contiguous vector stores.
|
||||
for (uint i = worker; i < MatrixRows * kTile / 8; i += 128) {
|
||||
const uint localRow = i / (kTile / 8);
|
||||
const uint col = i % (kTile / 8) * 8;
|
||||
vec<bfloat, 8> value;
|
||||
for (uint j = 0; j < 8; ++j) value[j] = bfloat(0.0f);
|
||||
if (localRow < count) {
|
||||
const uint owner = route_table[meta + 1 + localRow];
|
||||
const device float *src = x + (owner / RowStep) * Width + k + col;
|
||||
for (uint j = 0; j < 8; ++j) value[j] = bfloat(src[j]);
|
||||
}
|
||||
leftStorage[i] = value;
|
||||
}
|
||||
for (uint i = worker; i < channelsPerGroup * kTile / 16; i += 128) {
|
||||
const uint col = k + i % (kTile / 16) * 16;
|
||||
const size_t offset = size_t(expert) * Channels + channel + i / (kTile / 16);
|
||||
const device uint* words = weight + offset * (Width / 8) + col / 8;
|
||||
const float scale = decode_e4m3(scales[offset * (Width / 16) + col / 16]);
|
||||
for (uint j = 0; j < 2; ++j) {
|
||||
const uint word = words[j];
|
||||
vec<bfloat, 8> values;
|
||||
for (uint n = 0; n < 8; ++n) values[n] = bfloat(decode_e2m1(word >> (4 * n)) * scale);
|
||||
rightStorage[2 * i + j] = values;
|
||||
}
|
||||
}
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
matrixInput a(left, dims(kTile, MatrixRows), strides{1, kTile});
|
||||
matrixInput w(right + (first - channel) * kTile, dims(kTile, channelsPerSimd), strides{1, kTile});
|
||||
dot.run(a, w, accum);
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
}
|
||||
tensor<threadgroup float, dims, tensor_inline> result(tile + (first - channel), dims(channelsPerSimd, MatrixRows), strides{1, channelsPerGroup});
|
||||
accum.store(result);
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
#if FUSED_GATE
|
||||
constexpr uint activationsPerGroup = channelsPerGroup / 2;
|
||||
const float denom = denominator[0] * float(MaxProduct);
|
||||
const float gateCap = as_type<float>(GateCapBits), upCap = as_type<float>(UpCapBits);
|
||||
for (uint i = worker; i < count * activationsPerGroup; i += 128) {
|
||||
const uint owner = route_table[meta + 1 + i / activationsPerGroup];
|
||||
const float scale = (xmax[owner / XmaxStride] * maxima[expert]) / denom;
|
||||
const float value = expert_swiglu(tile[2 * i], tile[2 * i + 1], scale, scores[owner], gateCap, upCap);
|
||||
out[owner * (Channels / 2) + channel / 2 + i % activationsPerGroup] = bfloat(value);
|
||||
}
|
||||
#else
|
||||
for (uint i = worker; i < count * channelsPerGroup; i += 128) {
|
||||
uint owner = route_table[meta + 1 + i / channelsPerGroup];
|
||||
out[owner * Channels + channel + i % channelsPerGroup] = tile[i];
|
||||
}
|
||||
#endif
|
||||
`
|
||||
@@ -0,0 +1,315 @@
|
||||
package mlx
|
||||
|
||||
import (
|
||||
"math"
|
||||
"math/rand/v2"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/ollama/ollama/mlx/mlxthread/mlxthreadtest"
|
||||
)
|
||||
|
||||
// These tests need the actual bank geometry: smaller banks return nil before
|
||||
// either the vector or matrix branch runs. Reuse one bank per projection.
|
||||
func TestInklingNVFP4HybridProjections(t *testing.T) {
|
||||
withMLXThread(t, func(t *mlxthreadtest.T) {
|
||||
requireMetal(t)
|
||||
generation, _ := appleGPU(kernelArchitecture())
|
||||
if generation < 17 || !hasMetalTensorOps() {
|
||||
t.Skip("requires M5 and Metal tensor ops")
|
||||
}
|
||||
random := rand.New(rand.NewPCG(61, 23))
|
||||
for _, width := range []int{2304, 1152} {
|
||||
Scoped(func() {
|
||||
weight, scales := shortGatherBank(random, "nvfp4", 128, 2304, width)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
rows int
|
||||
dtype DType
|
||||
strided bool
|
||||
offset bool
|
||||
}{
|
||||
{"spread", 16, DTypeInt32, false, false},
|
||||
{"mixed", 17, DTypeUint32, false, false},
|
||||
{"hot", 64, DTypeInt32, false, false},
|
||||
{"mixed", 17, DTypeInt32, true, false},
|
||||
{"mixed", 17, DTypeUint32, true, false},
|
||||
{"mixed", 17, DTypeUint32, false, true},
|
||||
} {
|
||||
Scoped(func() {
|
||||
rows, topK := tc.rows, 8
|
||||
var ids []int32
|
||||
if tc.name == "mixed" {
|
||||
// Exact 4/5 and 16/17 run boundaries, shuffled across rows.
|
||||
var ordered []int32
|
||||
for expert, count := range []int{4, 5, 16, 17, 6} {
|
||||
ordered = append(ordered, slices.Repeat([]int32{int32(expert)}, count)...)
|
||||
}
|
||||
for len(ordered) < rows*topK {
|
||||
ordered = append(ordered, int32(8+(len(ordered)-48)%120))
|
||||
}
|
||||
ids = make([]int32, len(ordered))
|
||||
for i, expert := range ordered {
|
||||
ids[i*73%len(ids)] = expert
|
||||
}
|
||||
} else {
|
||||
ids = shortGatherRoutes(random, tc.name, rows, topK, 128).Ints()
|
||||
}
|
||||
if tc.strided {
|
||||
ids[32], ids[len(ids)-1] = -1, 128
|
||||
}
|
||||
indices := FromValues(ids, rows, topK).AsType(tc.dtype)
|
||||
if tc.strided {
|
||||
padded := make([]int32, len(ids)*2)
|
||||
for i, id := range ids {
|
||||
padded[2*i], padded[2*i+1] = id, -1
|
||||
}
|
||||
indices = FromValues(padded, rows, 2*topK).AsType(tc.dtype).Slice(Slice(), Slice(0, 2*topK, 2))
|
||||
}
|
||||
plan := NewInklingNVFP4ExpertPlan(indices)
|
||||
if plan == nil {
|
||||
t.Fatalf("width %d %+v: plan did not run", width, tc)
|
||||
}
|
||||
if tc.offset {
|
||||
// A later Set must not change the plan's captured routes.
|
||||
indices.Set(Zeros(tc.dtype, rows, topK))
|
||||
}
|
||||
// Independent grouping oracle checks leaders, zero-filled tails,
|
||||
// and every member, including chunks after the first 16 routes.
|
||||
groups := make(map[int32][]int32)
|
||||
for route, id := range ids {
|
||||
groups[id] = append(groups[id], int32(route))
|
||||
}
|
||||
wantTable := make([]int32, len(ids)*17)
|
||||
for _, owners := range groups {
|
||||
for start := 0; start < len(owners); start += 16 {
|
||||
run := owners[start:min(start+16, len(owners))]
|
||||
offset := int(run[0]) * 17
|
||||
wantTable[offset] = int32(len(run))
|
||||
copy(wantTable[offset+1:offset+17], run)
|
||||
}
|
||||
}
|
||||
if got := plan.table.AsType(DTypeInt32).Ints(); !slices.Equal(got, wantTable) {
|
||||
t.Fatalf("width %d %+v: route table differs from grouping oracle", width, tc)
|
||||
}
|
||||
activationRows := topK
|
||||
if width == 2304 {
|
||||
activationRows = 1
|
||||
}
|
||||
x, xmax := QuantizeNVFP4Activation4Over6(patternArray(DTypeBFloat16,
|
||||
[]int{rows, activationRows, 1, width}, 0, 0.03, 7919, 2003), 1536)
|
||||
w, s := weight, scales
|
||||
if tc.strided {
|
||||
x = Contiguous(x.Transpose(3, 1, 2, 0), false).Transpose(3, 1, 2, 0)
|
||||
w = Contiguous(w.Transpose(0, 2, 1), false).Transpose(0, 2, 1)
|
||||
s = Contiguous(s.Transpose(0, 2, 1), false).Transpose(0, 2, 1)
|
||||
}
|
||||
if tc.offset {
|
||||
// Keep the bank contiguous but move its base by one packed word.
|
||||
shifted := Concatenate([]*Array{Zeros(DTypeUint32, 1), weight.Reshape(-1)}, 0)
|
||||
w = shifted.Slice(Slice(1, shifted.Size())).Reshape(weight.Dims()...)
|
||||
}
|
||||
// The reference never reads an invalid expert. Invalid output
|
||||
// rows are checked separately for NaN, not compared to expert 0.
|
||||
valid := slices.Clone(ids)
|
||||
for i, id := range valid {
|
||||
if id < 0 || id >= 128 {
|
||||
valid[i] = 0
|
||||
}
|
||||
}
|
||||
referenceIDs := FromValues(valid, rows, topK)
|
||||
var got, want *Array
|
||||
channels := 2304
|
||||
if width == 2304 {
|
||||
channels = 1152
|
||||
maxima := patternArray(DTypeFloat32, []int{128}, 0.05, 0.005, 7, 17)
|
||||
denominator := FromValue(float32(2688))
|
||||
scores := patternArray(DTypeFloat32, []int{rows, topK}, 0.2, 0.01, 5, 11)
|
||||
got = plan.GateUp(x, w, s, xmax, maxima, denominator, scores, 4, 25, 1536)
|
||||
want = ShortGatherNVFP4SwiGLU(x, weight, s, referenceIDs, xmax, maxima, denominator, scores, topK, 4, 25, 1536)
|
||||
} else {
|
||||
got = plan.Down(x, w, s)
|
||||
want = ShortGatherQMM(x, weight, s, referenceIDs, "nvfp4")
|
||||
}
|
||||
if got == nil || want == nil {
|
||||
t.Fatalf("width %d %+v: candidate/reference projection did not run", width, tc)
|
||||
}
|
||||
a, b := got.AsType(DTypeFloat32).Floats(), want.AsType(DTypeFloat32).Floats()
|
||||
if len(a) != len(ids)*channels || len(b) != len(a) {
|
||||
t.Fatalf("width %d %+v: output lengths %d and %d", width, tc, len(a), len(b))
|
||||
}
|
||||
for route, id := range ids {
|
||||
for c := range channels {
|
||||
i := route*channels + c
|
||||
if id < 0 || id >= 128 {
|
||||
if !math.IsNaN(float64(a[i])) {
|
||||
t.Fatalf("invalid route %d channel %d = %g", route, c, a[i])
|
||||
}
|
||||
continue
|
||||
}
|
||||
if math.IsNaN(float64(a[i])) || math.IsInf(float64(a[i]), 0) ||
|
||||
math.IsNaN(float64(b[i])) || math.IsInf(float64(b[i]), 0) {
|
||||
t.Fatalf("valid route %d channel %d is nonfinite", route, c)
|
||||
}
|
||||
if math.Float32bits(a[i]) != math.Float32bits(b[i]) {
|
||||
t.Fatalf("width %d %+v route %d channel %d: got %g (%08x), want %g (%08x)",
|
||||
width, tc, route, c, a[i], math.Float32bits(a[i]), b[i], math.Float32bits(b[i]))
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestInklingNVFP4HybridFallback(t *testing.T) {
|
||||
withMLXThread(t, func(t *mlxthreadtest.T) {
|
||||
for _, ids := range []*Array{nil, Zeros(DTypeInt32, 128), Zeros(DTypeInt32, 15, 8), Zeros(DTypeInt32, 129, 8), Zeros(DTypeInt32, 16, 7), Zeros(DTypeFloat32, 16, 8)} {
|
||||
if NewInklingNVFP4ExpertPlan(ids) != nil {
|
||||
t.Fatal("unsupported route shape/type accepted")
|
||||
}
|
||||
}
|
||||
ids := Zeros(DTypeInt32, 16, 8)
|
||||
generation, _ := appleGPU(kernelArchitecture())
|
||||
if !MetalIsAvailable() || !hasMetalTensorOps() || generation < 17 {
|
||||
if NewInklingNVFP4ExpertPlan(ids) != nil {
|
||||
t.Fatal("unsupported device accepted")
|
||||
}
|
||||
return
|
||||
}
|
||||
if NewInklingNVFP4ExpertPlan(Zeros(DTypeInt32, 128, 8)) == nil {
|
||||
t.Fatal("wide expert plan did not run")
|
||||
}
|
||||
plan := NewInklingNVFP4ExpertPlan(ids)
|
||||
if plan == nil {
|
||||
t.Fatal("supported plan did not run")
|
||||
}
|
||||
x, w, s := Zeros(DTypeFloat32, 16, 8, 1, 1152), Zeros(DTypeUint32, 128, 2304, 144), Zeros(DTypeUint8, 128, 2304, 72)
|
||||
for _, bad := range []struct{ x, w, s *Array }{
|
||||
{nil, w, s},
|
||||
{x.AsType(DTypeBFloat16), w, s},
|
||||
{x.Reshape(128, 1152), w, s},
|
||||
{Zeros(DTypeFloat32, 16, 1, 1, 1152), w, s},
|
||||
{x, w.Slice(Slice(0, 127), Slice(), Slice()), s},
|
||||
{x, w, s.AsType(DTypeFloat32)},
|
||||
{x, w, s.Slice(Slice(), Slice(), Slice(0, 71))},
|
||||
{x, Zeros(DTypeUint32, 128, 2304, 288), Zeros(DTypeUint8, 128, 2304, 36)}, // MXFP8 geometry
|
||||
} {
|
||||
if plan.Down(bad.x, bad.w, bad.s) != nil {
|
||||
t.Fatal("unsupported projection accepted")
|
||||
}
|
||||
}
|
||||
gx, gw, gs := Zeros(DTypeFloat32, 16, 1, 1, 2304), Zeros(DTypeUint32, 128, 2304, 288), Zeros(DTypeUint8, 128, 2304, 144)
|
||||
maxima, denominator, scores := Zeros(DTypeFloat32, 128), FromValue(float32(2688)), Zeros(DTypeFloat32, 16, 8)
|
||||
for _, xmax := range []*Array{nil, Zeros(DTypeFloat32, 15), Zeros(DTypeBFloat16, 16)} {
|
||||
if plan.GateUp(gx, gw, gs, xmax, maxima, denominator, scores, 4, 25, 1536) != nil {
|
||||
t.Fatal("unsupported maxima accepted")
|
||||
}
|
||||
}
|
||||
// Same serialized-backend pattern as TestShortGatherRouteTableUnavailable;
|
||||
// this does not add a test hook or replace a native handle.
|
||||
for _, kernel := range []*gpuKernel{shortGatherRouteTable, inklingNVFP4MatrixGateUp, inklingNVFP4MatrixDown} {
|
||||
func() {
|
||||
disabled := kernel.metalDisabled
|
||||
kernel.metalDisabled = true
|
||||
defer func() { kernel.metalDisabled = disabled }()
|
||||
switch kernel {
|
||||
case shortGatherRouteTable:
|
||||
if NewInklingNVFP4ExpertPlan(ids) != nil {
|
||||
t.Fatal("plan ran without route table")
|
||||
}
|
||||
case inklingNVFP4MatrixGateUp:
|
||||
if plan.GateUp(gx, gw, gs, Zeros(DTypeFloat32, 16), maxima, denominator, scores, 4, 25, 1536) != nil {
|
||||
t.Fatal("disabled gate/up did not fall back")
|
||||
}
|
||||
down := plan.Down(x, w, s)
|
||||
if down == nil {
|
||||
t.Fatal("down declined with only gate/up disabled")
|
||||
}
|
||||
Eval(down)
|
||||
case inklingNVFP4MatrixDown:
|
||||
if plan.Down(x, w, s) != nil {
|
||||
t.Fatal("disabled down did not fall back")
|
||||
}
|
||||
gate := plan.GateUp(gx, gw, gs, Zeros(DTypeFloat32, 16), maxima, denominator, scores, 4, 25, 1536)
|
||||
if gate == nil {
|
||||
t.Fatal("gate/up declined with only down disabled")
|
||||
}
|
||||
Eval(gate)
|
||||
}
|
||||
}()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func BenchmarkInklingNVFP4DownEager(b *testing.B) {
|
||||
benchmarkInklingNVFP4Down(b, false)
|
||||
}
|
||||
|
||||
func BenchmarkInklingNVFP4DownKernel(b *testing.B) {
|
||||
benchmarkInklingNVFP4Down(b, true)
|
||||
}
|
||||
|
||||
func benchmarkInklingNVFP4Down(b *testing.B, hybrid bool) {
|
||||
for _, pattern := range []string{"random", "hot"} {
|
||||
b.Run(pattern, func(b *testing.B) {
|
||||
benchmarkInklingMetalKernel(b, true, func() func() *Array {
|
||||
// 80 flattened rows exercise the wide expert branch. Its eager
|
||||
// baseline calls the normal per-route quantized gather.
|
||||
const rows, topK, width = 80, 8, 1152
|
||||
random := rand.New(rand.NewPCG(61, 23))
|
||||
weight, scales := shortGatherBank(random, "nvfp4", 128, 2304, width)
|
||||
ids := shortGatherRoutes(random, pattern, rows, topK, 128)
|
||||
values, _ := QuantizeNVFP4Activation4Over6(patternArray(DTypeBFloat16,
|
||||
[]int{rows, topK, 1, width}, 0, 0.03, 7919, 2003), 1536)
|
||||
Eval(weight, scales, ids, values)
|
||||
return func() *Array {
|
||||
if hybrid {
|
||||
return NewInklingNVFP4ExpertPlan(ids).Down(values, weight, scales)
|
||||
}
|
||||
return GatherQMM(values, weight, scales, nil, nil, ids, true, 16, 4, "nvfp4", nil, false)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// benchmarkInklingMetalKernel measures one completed, fresh graph per loop.
|
||||
// Inputs and the first compilation belong outside the timed loop.
|
||||
func benchmarkInklingMetalKernel(b *testing.B, m5 bool, prepare func() func() *Array) {
|
||||
b.Helper()
|
||||
worker := mlxTestThread(b)
|
||||
var supported, launched bool
|
||||
if err := worker.Do(b.Context(), func() error {
|
||||
generation, _ := appleGPU(kernelArchitecture())
|
||||
supported = MetalIsAvailable() && (!m5 || (generation >= 17 && hasMetalTensorOps()))
|
||||
if !supported {
|
||||
return nil
|
||||
}
|
||||
Scoped(func() {
|
||||
run := prepare()
|
||||
Scoped(func() {
|
||||
if out := run(); out != nil {
|
||||
Eval(out)
|
||||
launched = true
|
||||
}
|
||||
})
|
||||
if launched {
|
||||
for b.Loop() {
|
||||
Scoped(func() { Eval(run()) })
|
||||
}
|
||||
}
|
||||
})
|
||||
return nil
|
||||
}); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
if !supported {
|
||||
b.Skip("requires the corresponding Metal path")
|
||||
}
|
||||
if !launched {
|
||||
b.Fatal("benchmark projection declined its fixture")
|
||||
}
|
||||
}
|
||||
+116
-16
@@ -1,13 +1,16 @@
|
||||
package mlx
|
||||
|
||||
import "math"
|
||||
import (
|
||||
"math"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// ShortGatherQMM returns GatherQMM(x, weight, scales, nil, nil, indices, true,
|
||||
// group, bits, mode, nil, false) for NVFP4 (16, 4) or MXFP8 (32, 8) expert
|
||||
// banks, reading each selected expert's weights once for all the routes that
|
||||
// select it instead of once per route. indices [rows, topK] hold at most 128
|
||||
// routes. x is FP32 [rows, 1, 1, K], one vector per row, or
|
||||
// [rows, topK, 1, K], one per route. The FP32 result is [rows, topK, 1, N].
|
||||
// routes, or 512 on M5 and later. x is FP32 [rows, 1, 1, K],
|
||||
// one vector per row, or [rows, topK, 1, K], one per route. The FP32 result is [rows, topK, 1, N].
|
||||
// Each route keeps the lane order of GatherQMM's vector kernels, so its
|
||||
// result does not depend on the routes that share its expert. With
|
||||
// quantized activations, as Inkling's are, at its expert widths on M5 it
|
||||
@@ -18,7 +21,15 @@ func ShortGatherQMM(x, weight, scales, indices *Array, mode string) *Array {
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
out, ok := plan.kernel.applyMetal(plan.launch([]*Array{x, weight, scales, indices}, nil,
|
||||
inputs := []*Array{x, weight, scales, indices}
|
||||
if plan.routes > 128 {
|
||||
table := shortGatherRouteTableFor(indices, plan.chunk)
|
||||
if table == nil {
|
||||
return nil
|
||||
}
|
||||
inputs = append(inputs, table)
|
||||
}
|
||||
out, ok := plan.kernel.applyMetal(plan.launch(inputs, nil,
|
||||
gpuOutputSpec{"short_gather_qmm", []int32{int32(plan.rows), int32(plan.topK), 1, int32(plan.channels)}, DTypeFloat32}))
|
||||
if !ok {
|
||||
return nil
|
||||
@@ -46,7 +57,17 @@ func ShortGatherNVFP4SwiGLU(x, weight, scales, indices, xmax, maxima, denominato
|
||||
}
|
||||
// Kernels index every input; a 0-d array would arrive as a scalar.
|
||||
denominator = denominator.Reshape(1)
|
||||
out, ok := shortGatherNVFP4SwiGLU.applyMetal(plan.launch([]*Array{x, weight, scales, indices, xmax, maxima, denominator, scores},
|
||||
kernel := shortGatherNVFP4SwiGLU
|
||||
inputs := []*Array{x, weight, scales, indices, xmax, maxima, denominator, scores}
|
||||
if plan.routes > 128 {
|
||||
table := shortGatherRouteTableFor(indices, plan.chunk)
|
||||
if table == nil {
|
||||
return nil
|
||||
}
|
||||
kernel = shortGatherNVFP4SwiGLUTable
|
||||
inputs = append(inputs, table)
|
||||
}
|
||||
out, ok := kernel.applyMetal(plan.launch(inputs,
|
||||
[]gpuIntArg{
|
||||
{"XmaxStride", xmaxStride},
|
||||
{"MaxProduct", maxProduct},
|
||||
@@ -121,7 +142,16 @@ func planShortGather(x, weight, scales, indices *Array, mode string) (shortGathe
|
||||
p := shortGatherPlan{rows: indices.Dim(0), topK: indices.Dim(1), width: x.Dim(3), channels: weight.Dim(1), lanes: 8}
|
||||
experts := weight.Dim(0)
|
||||
p.routes = p.rows * p.topK
|
||||
if x.Dim(0) != p.rows || (x.Dim(1) != 1 && x.Dim(1) != p.topK) || p.routes < 1 || p.routes > 128 ||
|
||||
arch := kernelArchitecture()
|
||||
generation, _ := appleGPU(arch)
|
||||
maxRoutes := 128
|
||||
if generation >= 17 {
|
||||
// Reuse the route scan across channel tiles for wider verification
|
||||
// batches. Bound the temporary table and leave larger forwards
|
||||
// on the stock gather.
|
||||
maxRoutes = 512
|
||||
}
|
||||
if x.Dim(0) != p.rows || (x.Dim(1) != 1 && x.Dim(1) != p.topK) || p.routes < 1 || p.routes > maxRoutes ||
|
||||
experts < 1 || scales.Dim(0) != experts || scales.Dim(1) != p.channels {
|
||||
return shortGatherPlan{}, false
|
||||
}
|
||||
@@ -131,18 +161,23 @@ func planShortGather(x, weight, scales, indices *Array, mode string) (shortGathe
|
||||
return shortGatherPlan{}, false
|
||||
}
|
||||
p.kernel = shortGatherNVFP4
|
||||
if p.routes > 128 {
|
||||
p.kernel = shortGatherNVFP4Table
|
||||
}
|
||||
case "mxfp8":
|
||||
if p.width%32 != 0 || weight.Dim(2) != p.width/4 || scales.Dim(2) != p.width/32 {
|
||||
return shortGatherPlan{}, false
|
||||
}
|
||||
p.kernel = shortGatherMXFP8
|
||||
if p.routes > 128 {
|
||||
p.kernel = shortGatherMXFP8Table
|
||||
}
|
||||
if p.width%256 != 0 {
|
||||
p.lanes = 4
|
||||
}
|
||||
default:
|
||||
return shortGatherPlan{}, false
|
||||
}
|
||||
arch := kernelArchitecture()
|
||||
tuning, ok := tuneShortGather(mode, p.rows, x.Dim(1) != 1, arch)
|
||||
if !ok || p.channels%(tuning.outputs*tuning.simdgroups) != 0 {
|
||||
return shortGatherPlan{}, false
|
||||
@@ -172,6 +207,58 @@ func (p shortGatherPlan) launch(inputs []*Array, ints []gpuIntArg, output gpuOut
|
||||
}
|
||||
}
|
||||
|
||||
// shortGatherRouteTableFor computes each expert run once per launch. Each
|
||||
// row holds a count and up to chunk routes. Callers validate the indices.
|
||||
func shortGatherRouteTableFor(indices *Array, chunk int) *Array {
|
||||
routes := indices.Size()
|
||||
out, ok := shortGatherRouteTable.applyMetal(gpuLaunch{
|
||||
inputs: []*Array{indices},
|
||||
ints: []gpuIntArg{{"Chunk", chunk}},
|
||||
outputs: []gpuOutputSpec{{"table", []int32{int32(routes), int32(chunk + 1)}, DTypeUint32}},
|
||||
grid: [3]int{32, routes, 1},
|
||||
threadGroup: [3]int{32, 1, 1},
|
||||
})
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return out[0]
|
||||
}
|
||||
|
||||
var shortGatherRouteTable = &gpuKernel{
|
||||
name: "short_gather_route_table",
|
||||
inputs: []string{"indices"},
|
||||
outputs: []string{"table"},
|
||||
metal: gpuSource{header: shortGatherHeader, source: `
|
||||
const uint lane = thread_index_in_simdgroup, route = threadgroup_position_in_grid.y;
|
||||
uint routes[Chunk] = {};
|
||||
const uint count = expert_run<Chunk>(indices, indices_shape[0] * indices_shape[1],
|
||||
route, uint(indices[route]), lane, routes);
|
||||
const uint offset = route * (Chunk + 1);
|
||||
if (lane < Chunk) table[offset + lane + 1] = routes[lane];
|
||||
if (lane == 0) table[offset] = count;
|
||||
`},
|
||||
}
|
||||
|
||||
// The narrow variants retain their original bindings and shader. Only wider
|
||||
// launches bind a route table, so small batches do not pay for its preparation.
|
||||
var (
|
||||
shortGatherNVFP4Table = newShortGatherTableKernel(shortGatherNVFP4,
|
||||
shortGatherPrefix+shortGatherTableRun+shortGatherSuffix)
|
||||
shortGatherMXFP8Table = newShortGatherTableKernel(shortGatherMXFP8,
|
||||
shortGatherPrefix+shortGatherTableRun+shortGatherSuffix)
|
||||
shortGatherNVFP4SwiGLUTable = newShortGatherTableKernel(shortGatherNVFP4SwiGLU,
|
||||
shortGatherSwiGLUPrefix+shortGatherTableRun+shortGatherSwiGLUSuffix)
|
||||
)
|
||||
|
||||
func newShortGatherTableKernel(base *gpuKernel, source string) *gpuKernel {
|
||||
return &gpuKernel{
|
||||
name: base.name + "_table",
|
||||
inputs: append(slices.Clone(base.inputs), "route_table"),
|
||||
outputs: base.outputs,
|
||||
metal: gpuSource{source: source, header: base.metal.header},
|
||||
}
|
||||
}
|
||||
|
||||
// shortGatherHeader collects the routes that select one expert. Every
|
||||
// threadgroup ballots all routes; the routes of an expert form runs of Chunk
|
||||
// in route order, and only the first route of a run computes it.
|
||||
@@ -236,7 +323,9 @@ inline float decode_e4m3(uchar bits) {
|
||||
// shortGatherSource is the kernel body shared by both formats. Each format's
|
||||
// gather_dots fills dots[out][j] in every lane for channel first + out of
|
||||
// route routes[j], j < count; lanes then store one value each.
|
||||
const shortGatherSource = `
|
||||
const shortGatherSource = shortGatherPrefix + shortGatherRun + shortGatherSuffix
|
||||
|
||||
const shortGatherPrefix = `
|
||||
const uint channels = weight_shape[1];
|
||||
const uint route = threadgroup_position_in_grid.y, lane = thread_index_in_simdgroup;
|
||||
const uint first = (threadgroup_position_in_grid.x * Simdgroups + simdgroup_index_in_threadgroup) * Outputs;
|
||||
@@ -246,18 +335,29 @@ if (expert >= uint(weight_shape[0])) {
|
||||
return;
|
||||
}
|
||||
uint routes[Chunk];
|
||||
const uint count = expert_run<Chunk>(indices, indices_shape[0] * indices_shape[1], route, expert, lane, routes);
|
||||
`
|
||||
|
||||
const shortGatherRun = `const uint count = expert_run<Chunk>(indices, indices_shape[0] * indices_shape[1], route, expert, lane, routes);
|
||||
if (count == 0) return;
|
||||
float dots[Outputs][Chunk] = {};
|
||||
`
|
||||
|
||||
const shortGatherTableRun = `const uint at = route * (Chunk + 1);
|
||||
const uint count = route_table[at];
|
||||
if (count == 0) return;
|
||||
for (uint i = 0; i < count; ++i) routes[i] = route_table[at + 1 + i];
|
||||
`
|
||||
|
||||
const shortGatherSuffix = `float dots[Outputs][Chunk] = {};
|
||||
gather_dots<Chunk, Outputs, Chunk, Width, RowStep, Lanes>(count, x, weight, scales, ulong(expert) * channels + first,
|
||||
routes, lane, dots);
|
||||
const uint j = lane / Outputs, out = lane % Outputs;
|
||||
if (j < count) y[ulong(pick_route(routes, j)) * channels + first + out] = pick_dot(dots, out, j);
|
||||
`
|
||||
|
||||
// shortGatherSwiGLUSource is shortGatherSource for NVFP4 gate/up pairs
|
||||
// (Outputs is even): lane pair * count + j finishes route j's SwiGLU of a pair.
|
||||
const shortGatherSwiGLUSource = `
|
||||
// shortGatherSwiGLUSource finishes NVFP4 gate/up pairs with the same lane order.
|
||||
const shortGatherSwiGLUSource = shortGatherSwiGLUPrefix + shortGatherRun + shortGatherSwiGLUSuffix
|
||||
|
||||
const shortGatherSwiGLUPrefix = `
|
||||
const uint channels = weight_shape[1];
|
||||
const uint route = threadgroup_position_in_grid.y, lane = thread_index_in_simdgroup;
|
||||
const uint first = (threadgroup_position_in_grid.x * Simdgroups + simdgroup_index_in_threadgroup) * Outputs;
|
||||
@@ -267,9 +367,9 @@ if (expert >= uint(weight_shape[0])) {
|
||||
return;
|
||||
}
|
||||
uint routes[Chunk];
|
||||
const uint count = expert_run<Chunk>(indices, indices_shape[0] * indices_shape[1], route, expert, lane, routes);
|
||||
if (count == 0) return;
|
||||
float dots[Outputs][Chunk] = {};
|
||||
`
|
||||
|
||||
const shortGatherSwiGLUSuffix = `float dots[Outputs][Chunk] = {};
|
||||
gather_dots<Chunk, Outputs, Chunk, Width, RowStep, Lanes>(count, x, weight, scales, ulong(expert) * channels + first,
|
||||
routes, lane, dots);
|
||||
if (lane < count * (Outputs / 2)) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"math"
|
||||
"math/rand/v2"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/ollama/ollama/mlx/mlxthread/mlxthreadtest"
|
||||
@@ -82,9 +83,14 @@ func TestShortGatherQMM(t *testing.T) {
|
||||
const experts, topK, channels = 128, 8, 256
|
||||
// Inkling's gate/up product reads one vector per row, its down
|
||||
// product one per route.
|
||||
generation, _ := appleGPU(kernelArchitecture())
|
||||
rowsToTest := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
|
||||
if generation >= 17 {
|
||||
rowsToTest = append(rowsToTest, 17, 24, 64)
|
||||
}
|
||||
for _, shape := range []struct{ width, vectors int }{{2304, 1}, {1152, topK}} {
|
||||
weight, scales := shortGatherBank(random, mode, experts, channels, shape.width)
|
||||
for rows := 1; rows <= 16; rows++ {
|
||||
for _, rows := range rowsToTest {
|
||||
// The documented single-row fallback before M3 keeps the stock gather.
|
||||
if arch := kernelArchitecture(); !shortGatherRuns(mode, rows, shape.vectors != 1, arch) {
|
||||
continue
|
||||
@@ -100,7 +106,6 @@ func TestShortGatherQMM(t *testing.T) {
|
||||
// within a lane's 8 values are exact in FP32, so on M5
|
||||
// each route matches GatherQMM bit for bit. Other
|
||||
// activations may round differently in a few places.
|
||||
generation, _ := appleGPU(kernelArchitecture())
|
||||
for _, x := range []*Array{quantize(raw.AsType(DTypeBFloat16)), raw} {
|
||||
got := ShortGatherQMM(x, weight, scales, ids, mode)
|
||||
if got == nil {
|
||||
@@ -149,16 +154,140 @@ func TestShortGatherQMMEdges(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
many := FromValues(make([]float32, 17*width), 17, 1, 1, width)
|
||||
if ShortGatherQMM(many, weight, scales, Zeros(DTypeInt32, 17, 8), "nvfp4") != nil {
|
||||
t.Error("accepted 136 routes")
|
||||
}
|
||||
if ShortGatherQMM(x.AsType(DTypeBFloat16), weight, scales, ids, "nvfp4") != nil {
|
||||
t.Error("accepted BF16 activations")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestShortGatherQMMDispatch(t *testing.T) {
|
||||
withMLXThread(t, func(t *mlxthreadtest.T) {
|
||||
requireMetal(t)
|
||||
generation, _ := appleGPU(kernelArchitecture())
|
||||
random := rand.New(rand.NewPCG(7, 11))
|
||||
for _, mode := range []string{"nvfp4", "mxfp8"} {
|
||||
weight, scales := shortGatherBank(random, mode, 16, 64, 512)
|
||||
for _, shape := range [][2]int{{16, 8}, {43, 3}, {64, 8}, {171, 3}} {
|
||||
rows, topK := shape[0], shape[1]
|
||||
x := BroadcastTo(FromValue(float32(0)), int32(rows), 1, 1, 512)
|
||||
ids := BroadcastTo(FromValues([]int32{0}, 1), int32(rows), int32(topK))
|
||||
plan, ok := planShortGather(x, weight, scales, ids, mode)
|
||||
routes := rows * topK
|
||||
want := routes <= 128 || generation >= 17 && routes <= 512
|
||||
if ok != want {
|
||||
t.Fatalf("%s routes=%d: supported=%t, want %t", mode, routes, ok, want)
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
kernel := shortGatherNVFP4
|
||||
inputs := []string{"x", "weight", "scales", "indices"}
|
||||
if mode == "mxfp8" {
|
||||
kernel = shortGatherMXFP8
|
||||
if routes > 128 {
|
||||
kernel = shortGatherMXFP8Table
|
||||
}
|
||||
} else if routes > 128 {
|
||||
kernel = shortGatherNVFP4Table
|
||||
}
|
||||
if routes > 128 {
|
||||
inputs = append(inputs, "route_table")
|
||||
}
|
||||
if plan.kernel != kernel || !slices.Equal(plan.kernel.inputs, inputs) {
|
||||
t.Fatalf("%s routes=%d: selected kernel %s with inputs %v", mode, routes, plan.kernel.name, plan.kernel.inputs)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !slices.Equal(shortGatherNVFP4SwiGLU.inputs, []string{"x", "weight", "scales", "indices", "xmax", "maxima", "denominator", "scores"}) {
|
||||
t.Fatal("narrow SwiGLU added a route-table binding")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestShortGatherQMMWideStrides(t *testing.T) {
|
||||
withMLXThread(t, func(t *mlxthreadtest.T) {
|
||||
requireMetal(t)
|
||||
if generation, _ := appleGPU(kernelArchitecture()); generation < 17 {
|
||||
t.Skip("wide gather requires M5 or later")
|
||||
}
|
||||
const rows, topK, experts, channels, width = 43, 3, 16, 64, 512
|
||||
random := rand.New(rand.NewPCG(17, 19))
|
||||
for _, mode := range []string{"nvfp4", "mxfp8"} {
|
||||
weight, scales := shortGatherBank(random, mode, experts, 2*channels, width)
|
||||
weight = weight.Slice(Slice(), Slice(0, 2*channels, 2), Slice())
|
||||
scales = scales.Slice(Slice(), Slice(0, 2*channels, 2), Slice())
|
||||
raw := patternArray(DTypeBFloat16, []int{2 * rows, 1, 1, width}, 0.1, 0.03, 7, 31)
|
||||
var x *Array
|
||||
group, bits := 16, 4
|
||||
if mode == "mxfp8" {
|
||||
x = MXFP8Quantize(raw, DTypeFloat32)
|
||||
group, bits = 32, 8
|
||||
} else {
|
||||
x, _ = QuantizeNVFP4Activation4Over6(raw, 1536)
|
||||
}
|
||||
x = x.Slice(Slice(0, 2*rows, 2), Slice(), Slice(), Slice())
|
||||
ids := make([]int32, rows*topK*2)
|
||||
valid := make([]int32, rows*topK)
|
||||
for route := range valid {
|
||||
valid[route] = int32(route % experts)
|
||||
ids[2*route] = valid[route]
|
||||
}
|
||||
ids[2*32], ids[2*128] = -1, experts
|
||||
want := GatherQMM(x, weight, scales, nil, nil, FromValues(valid, rows, topK), true, group, bits, mode, nil, false).Floats()
|
||||
for _, dtype := range []DType{DTypeInt32, DTypeUint32} {
|
||||
indices := FromValues(ids, rows, 2*topK).AsType(dtype).Slice(Slice(), Slice(0, 2*topK, 2))
|
||||
result := ShortGatherQMM(x, weight, scales, indices, mode)
|
||||
if result == nil {
|
||||
t.Fatalf("%s %v strided route table did not run", mode, dtype)
|
||||
}
|
||||
for i, value := range result.Floats() {
|
||||
route := i / channels
|
||||
if route == 32 || route == 128 {
|
||||
if !math.IsNaN(float64(value)) {
|
||||
t.Fatalf("%s %v invalid route %d channel %d = %g", mode, dtype, route, i%channels, value)
|
||||
}
|
||||
} else if math.Float32bits(value) != math.Float32bits(want[i]) {
|
||||
t.Fatalf("%s %v route %d channel %d = %g, want %g", mode, dtype, route, i%channels, value, want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestShortGatherRouteTableUnavailable(t *testing.T) {
|
||||
withMLXThread(t, func(t *mlxthreadtest.T) {
|
||||
requireMetal(t)
|
||||
if generation, _ := appleGPU(kernelArchitecture()); generation < 17 {
|
||||
t.Skip("wide gather requires M5 or later")
|
||||
}
|
||||
random := rand.New(rand.NewPCG(23, 29))
|
||||
x := Zeros(DTypeFloat32, 17, 1, 1, 512)
|
||||
ids := Zeros(DTypeInt32, 17, 8)
|
||||
// Simulate an unavailable backend using its existing state, on the
|
||||
// serialized MLX thread, without replacing the kernel or native handle.
|
||||
disabled := shortGatherRouteTable.metalDisabled
|
||||
shortGatherRouteTable.metalDisabled = true
|
||||
defer func() { shortGatherRouteTable.metalDisabled = disabled }()
|
||||
for _, mode := range []string{"nvfp4", "mxfp8"} {
|
||||
weight, scales := shortGatherBank(random, mode, 16, 64, 512)
|
||||
if ShortGatherQMM(x, weight, scales, ids, mode) != nil {
|
||||
t.Fatalf("%s wide gather ran without its route table", mode)
|
||||
}
|
||||
if mode == "nvfp4" && ShortGatherNVFP4SwiGLU(x, weight, scales, ids, Zeros(DTypeFloat32, 17), Zeros(DTypeFloat32, 16),
|
||||
FromValue(float32(2688)), Zeros(DTypeFloat32, 17, 8), 8, 4, 25, 1536) != nil {
|
||||
t.Fatal("wide SwiGLU ran without its route table")
|
||||
}
|
||||
narrow := ShortGatherQMM(x.Slice(Slice(0, 2), Slice(), Slice(), Slice()), weight, scales,
|
||||
ids.Slice(Slice(0, 2), Slice()), mode)
|
||||
if narrow == nil {
|
||||
t.Fatalf("unavailable route table disabled the %s narrow gather", mode)
|
||||
}
|
||||
Eval(narrow)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestShortGatherNVFP4SwiGLU checks the epilogue gather against the gather
|
||||
// followed by NVFP4SwiGLUQuantize; both quantize the same BF16 values.
|
||||
func TestShortGatherNVFP4SwiGLU(t *testing.T) {
|
||||
@@ -172,7 +301,7 @@ func TestShortGatherNVFP4SwiGLU(t *testing.T) {
|
||||
weight, scales := shortGatherBank(random, "nvfp4", experts, channels, width)
|
||||
maxima := patternArray(DTypeFloat32, []int{experts}, 3, 0.25, 7, 17)
|
||||
denominator := FromValue(float32(2688))
|
||||
for _, rows := range []int{1, 2, 3, 4, 8, 16} {
|
||||
for _, rows := range []int{1, 2, 3, 4, 8, 16, 24, 64} {
|
||||
// The documented single-row fallback before M3 keeps the stock gather.
|
||||
if !shortGatherRuns("nvfp4", rows, false, arch) {
|
||||
continue
|
||||
@@ -203,3 +332,40 @@ func TestShortGatherNVFP4SwiGLU(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func BenchmarkWideShortGatherEager(b *testing.B) {
|
||||
benchmarkWideShortGather(b, false)
|
||||
}
|
||||
|
||||
func BenchmarkWideShortGatherKernel(b *testing.B) {
|
||||
benchmarkWideShortGather(b, true)
|
||||
}
|
||||
|
||||
func benchmarkWideShortGather(b *testing.B, table bool) {
|
||||
for _, mode := range []string{"nvfp4", "mxfp8"} {
|
||||
b.Run(mode, func(b *testing.B) {
|
||||
benchmarkInklingMetalKernel(b, true, func() func() *Array {
|
||||
const rows, topK, width = 32, 8, 2304
|
||||
random := rand.New(rand.NewPCG(5, 9))
|
||||
weight, scales := shortGatherBank(random, mode, 128, 2304, width)
|
||||
ids := shortGatherRoutes(random, "random", rows, topK, 128)
|
||||
x := patternArray(DTypeBFloat16, []int{rows, 1, 1, width}, 0, 0.03, 7919, 2003)
|
||||
var values *Array
|
||||
group, bits := 16, 4
|
||||
if mode == "nvfp4" {
|
||||
values, _ = QuantizeNVFP4Activation4Over6(x, 1536)
|
||||
} else {
|
||||
group, bits = 32, 8
|
||||
values = MXFP8Quantize(x, DTypeFloat32)
|
||||
}
|
||||
Eval(weight, scales, ids, values)
|
||||
return func() *Array {
|
||||
if table {
|
||||
return ShortGatherQMM(values, weight, scales, ids, mode)
|
||||
}
|
||||
return GatherQMM(values, weight, scales, nil, nil, ids, true, group, bits, mode, nil, false)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -100,11 +100,11 @@ func (e routedExperts) forward(x *mlx.Array) *mlx.Array {
|
||||
flat := x.Reshape(batch*tokens, width)
|
||||
indices, weights := routeExperts(e.routerLogits(x), e.Bias, e.topK, e.routeScale)
|
||||
// The Metal grouped gather reuses each expert when there are at least
|
||||
// four routes per expert on average. Keep short target verification rows
|
||||
// on the width-stable path even if multiple requests share a batch.
|
||||
// four routes per expert on average. Short verification batches keep
|
||||
// their original route order and may share a vector or matrix tile.
|
||||
grouped := e.GateUp.BlockScales != nil && e.Down.BlockScales != nil &&
|
||||
tokens >= 64 && batch*tokens*e.topK/e.Router.Dim(0) >= 4 && mlx.MetalIsAvailable()
|
||||
return e.combine(flat, indices, weights, grouped).Reshape(batch, tokens, width)
|
||||
return e.combine(flat, indices, weights, batch, grouped).Reshape(batch, tokens, width)
|
||||
}
|
||||
|
||||
// routerLogits returns FP32 router scores, [batch*tokens, experts]. Short
|
||||
@@ -125,8 +125,8 @@ func (e routedExperts) routerLogits(x *mlx.Array) *mlx.Array {
|
||||
|
||||
// combine evaluates the selected experts and sums them for each token.
|
||||
// Grouped routes are sorted by expert for the Metal path.
|
||||
func (e routedExperts) combine(flat, indices, weights *mlx.Array, grouped bool) *mlx.Array {
|
||||
if out := e.combineQuantized(flat, indices, weights, grouped); out != nil {
|
||||
func (e routedExperts) combine(flat, indices, weights *mlx.Array, batch int, grouped bool) *mlx.Array {
|
||||
if out := e.combineQuantized(flat, indices, weights, batch, grouped); out != nil {
|
||||
return out
|
||||
}
|
||||
weighted := e.gateUpInput(flat, indices, weights)
|
||||
@@ -137,7 +137,7 @@ func (e routedExperts) combine(flat, indices, weights *mlx.Array, grouped bool)
|
||||
// combineQuantized runs NVFP4 or MXFP8 experts with fused Metal epilogues:
|
||||
// the gate/up scaling, SwiGLU and down quantization, then the down scaling
|
||||
// and the sum over routes. It returns nil where those kernels cannot run.
|
||||
func (e routedExperts) combineQuantized(flat, indices, weights *mlx.Array, grouped bool) *mlx.Array {
|
||||
func (e routedExperts) combineQuantized(flat, indices, weights *mlx.Array, batch int, grouped bool) *mlx.Array {
|
||||
if !mlx.MetalIsAvailable() || e.GateUp.BlockScales == nil || e.Down.BlockScales == nil ||
|
||||
(e.GateUp.Maxima == nil) != (e.Down.Maxima == nil) || flat.DType() != mlx.DTypeBFloat16 {
|
||||
return nil
|
||||
@@ -173,13 +173,22 @@ func (e routedExperts) combineQuantized(flat, indices, weights *mlx.Array, group
|
||||
}
|
||||
xmaxStride = 1
|
||||
}
|
||||
var plan *mlx.InklingNVFP4ExpertPlan
|
||||
var down, downMax *mlx.Array
|
||||
if nvfp4 && !grouped {
|
||||
if batch >= 4 && rows <= batch*shortTargetRows {
|
||||
plan = mlx.NewInklingNVFP4ExpertPlan(indices)
|
||||
}
|
||||
// The short gate/up gather finishes the SwiGLU in its epilogue, so
|
||||
// only the down quantizer remains.
|
||||
if activated := mlx.ShortGatherNVFP4SwiGLU(values, e.GateUp.Weight, e.GateUp.BlockScales, indices, xmax,
|
||||
e.GateUp.Maxima, e.GateUp.Denominator, weights, xmaxStride, e.gateCap, e.upCap,
|
||||
nvfp4ActivationDenominator); activated != nil {
|
||||
activated := plan.GateUp(values, e.GateUp.Weight, e.GateUp.BlockScales, xmax, e.GateUp.Maxima,
|
||||
e.GateUp.Denominator, weights, e.gateCap, e.upCap, nvfp4ActivationDenominator)
|
||||
if activated == nil {
|
||||
activated = mlx.ShortGatherNVFP4SwiGLU(values, e.GateUp.Weight, e.GateUp.BlockScales, indices, xmax,
|
||||
e.GateUp.Maxima, e.GateUp.Denominator, weights, xmaxStride, e.gateCap, e.upCap,
|
||||
nvfp4ActivationDenominator)
|
||||
}
|
||||
if activated != nil {
|
||||
down, downMax = mlx.QuantizeNVFP4Activation4Over6(activated, nvfp4ActivationDenominator)
|
||||
}
|
||||
}
|
||||
@@ -200,8 +209,12 @@ func (e routedExperts) combineQuantized(flat, indices, weights *mlx.Array, group
|
||||
} else {
|
||||
down = down.Reshape(rows, e.topK, 1, -1)
|
||||
}
|
||||
inner := e.Down.gather(down, indices, grouped).Reshape(routes, width)
|
||||
return mlx.ExpertSum(inner, downMax, e.Down.Maxima, e.Down.Denominator, indices, inverse, e.topK, nvfp4ActivationDenominator)
|
||||
dots := plan.Down(down, e.Down.Weight, e.Down.BlockScales)
|
||||
if dots == nil {
|
||||
dots = e.Down.gather(down, indices, grouped)
|
||||
}
|
||||
return mlx.ExpertSum(dots.Reshape(routes, width), downMax, e.Down.Maxima, e.Down.Denominator,
|
||||
indices, inverse, e.topK, nvfp4ActivationDenominator)
|
||||
}
|
||||
|
||||
func (e routedExperts) gateUpInput(flat, indices, scores *mlx.Array) *mlx.Array {
|
||||
|
||||
@@ -96,8 +96,14 @@ func TestShortExpertsMatchStockGather(t *testing.T) {
|
||||
topK: topK, gateCap: 4, upCap: 25,
|
||||
}
|
||||
mode := name
|
||||
maxRows := 16
|
||||
// Cross the route-table boundary on devices that support it.
|
||||
if mlx.ShortGatherQMM(mlx.Zeros(mlx.DTypeFloat32, 17, 1, 1, hidden), e.GateUp.Weight, e.GateUp.BlockScales,
|
||||
mlx.Zeros(mlx.DTypeInt32, 17, topK), mode) != nil {
|
||||
maxRows = 17
|
||||
}
|
||||
epilogue := 0
|
||||
for rows := 1; rows <= 16; rows++ {
|
||||
for rows := 1; rows <= maxRows; rows++ {
|
||||
input := make([]float32, rows*hidden)
|
||||
for i := range input {
|
||||
input[i] = float32(random.NormFloat64())
|
||||
@@ -133,7 +139,7 @@ func TestShortExpertsMatchStockGather(t *testing.T) {
|
||||
epilogue++
|
||||
}
|
||||
}
|
||||
got := e.combine(flat, indices, weights, false).AsType(mlx.DTypeFloat32).Floats()
|
||||
got := e.combine(flat, indices, weights, 1, false).AsType(mlx.DTypeFloat32).Floats()
|
||||
want := stockShortExperts(e, flat, indices, weights).AsType(mlx.DTypeFloat32).Floats()
|
||||
var diff, scale float64
|
||||
same := 0
|
||||
@@ -154,9 +160,9 @@ func TestShortExpertsMatchStockGather(t *testing.T) {
|
||||
if nvfp4 {
|
||||
// The epilogue's device gate does not depend on the row count
|
||||
// past one row, so it runs for every multi-row forward or none.
|
||||
t.Logf("the SwiGLU epilogue ran for %d of 15 multi-row forwards", epilogue)
|
||||
if epilogue != 0 && epilogue != 15 {
|
||||
t.Fatalf("the SwiGLU epilogue ran for only %d of 15 multi-row forwards", epilogue)
|
||||
t.Logf("the SwiGLU epilogue ran for %d of %d multi-row forwards", epilogue, maxRows-1)
|
||||
if epilogue != 0 && epilogue != maxRows-1 {
|
||||
t.Fatalf("the SwiGLU epilogue ran for only %d of %d multi-row forwards", epilogue, maxRows-1)
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -164,3 +170,62 @@ func TestShortExpertsMatchStockGather(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHybridNVFP4ExpertsMatchStockGather(t *testing.T) {
|
||||
mlxtest.Run(t, func(t *mlxtest.T) {
|
||||
mlx.Scoped(func() {
|
||||
// The primitive tests exercise the hybrid projections directly.
|
||||
// This test checks their composition through the model forward.
|
||||
if mlx.NewInklingNVFP4ExpertPlan(mlx.Zeros(mlx.DTypeInt32, 16, 8)) == nil {
|
||||
t.Skip("hybrid plan unavailable; require the primitive fallback test on this device")
|
||||
}
|
||||
const topK, width = 8, 2304
|
||||
random := rand.New(rand.NewPCG(53, 59))
|
||||
e := routedExperts{
|
||||
Router: mlx.Zeros(mlx.DTypeFloat32, 128, width),
|
||||
GateUp: shortExpertBank(random, true, 128, 2304, width),
|
||||
Down: shortExpertBank(random, true, 128, width, 1152),
|
||||
topK: topK, routeScale: 1, gateCap: 4, upCap: 25,
|
||||
}
|
||||
for _, shape := range []struct {
|
||||
batch, tokens int
|
||||
fallback string
|
||||
}{{4, 4, ""}, {16, 5, ""}, {16, 8, ""}, {4, 4, "gate/up"}, {4, 4, "down"}} {
|
||||
mlx.Scoped(func() {
|
||||
experts := e
|
||||
if shape.fallback != "" {
|
||||
// An extra unused expert makes just this bank ineligible
|
||||
// for the fixed 128-expert plan. Routing still uses 128 IDs.
|
||||
bank := &experts.GateUp
|
||||
if shape.fallback == "down" {
|
||||
bank = &experts.Down
|
||||
}
|
||||
first := mlx.FromValues([]int32{0}, 1)
|
||||
for _, array := range []**mlx.Array{&bank.Weight, &bank.BlockScales, &bank.Maxima} {
|
||||
*array = mlx.Concatenate([]*mlx.Array{*array, mlx.Take(*array, first, 0)}, 0)
|
||||
}
|
||||
}
|
||||
rows := shape.batch * shape.tokens
|
||||
input := make([]float32, rows*width)
|
||||
for i := range input {
|
||||
input[i] = float32(random.NormFloat64())
|
||||
}
|
||||
x := mlx.FromValues(input, shape.batch, shape.tokens, width).AsType(mlx.DTypeBFloat16)
|
||||
indices, weights := routeExperts(e.routerLogits(x), nil, topK, e.routeScale)
|
||||
flat := x.Reshape(rows, width)
|
||||
got := experts.forward(x).AsType(mlx.DTypeFloat32).Floats()
|
||||
want := stockShortExperts(experts, flat, indices, weights).AsType(mlx.DTypeFloat32).Floats()
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("B%d×%d fallback %q: output lengths %d and %d", shape.batch, shape.tokens, shape.fallback, len(got), len(want))
|
||||
}
|
||||
for i, value := range got {
|
||||
if math.IsNaN(float64(value)) || math.IsInf(float64(value), 0) || math.Float32bits(value) != math.Float32bits(want[i]) {
|
||||
t.Fatalf("B%d×%d fallback %q output %d: got %g (%08x), want %g (%08x)",
|
||||
shape.batch, shape.tokens, shape.fallback, i, value, math.Float32bits(value), want[i], math.Float32bits(want[i]))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -143,8 +143,8 @@ func TestGroupedNVFP4ExpertsPreserveRouting(t *testing.T) {
|
||||
x := mlx.FromValues(input, rows, width).AsType(mlx.DTypeBFloat16)
|
||||
ids := mlx.FromValues(indices, rows, topK)
|
||||
gains := mlx.FromValues(weights, rows, topK)
|
||||
want := e.combine(x, ids, gains, false).AsType(mlx.DTypeFloat32).Floats()
|
||||
got := e.combine(x, ids, gains, true).AsType(mlx.DTypeFloat32).Floats()
|
||||
want := e.combine(x, ids, gains, 1, false).AsType(mlx.DTypeFloat32).Floats()
|
||||
got := e.combine(x, ids, gains, 1, true).AsType(mlx.DTypeFloat32).Floats()
|
||||
// The sorted products round to BF16 before the outer scale, which can
|
||||
// move a value across an NVFP4 boundary. Misrouted rows differ wholesale.
|
||||
var diff, scale float64
|
||||
|
||||
Reference in new issue
Block a user