Skip to content

Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

MLX: version bump (#18235)

Daniel Hiltgenf093c6e0089c
diff --git a/MLX_VERSION b/MLX_VERSION
index 58b7f7c00..5e7f9cbe4 100644
--- a/MLX_VERSION
+++ b/MLX_VERSION
@@ -1 +1 @@
-37c26e5755da637255d57ea34b4879196a485301
\ No newline at end of file
+cbb4059d8c6652d1c2cce98c348a8a689eb275b8
\ No newline at end of file
diff --git a/cmake/local.cmake b/cmake/local.cmake
index 7e9f685c5..3535a5556 100644
--- a/cmake/local.cmake
+++ b/cmake/local.cmake
@@ -169,14 +169,28 @@ if(OLLAMA_MLX_BACKENDS)
list(APPEND _mlx_source_targets ollama-mlx-source)
endif()
+ # Temporary MLX-C carry patch for gather_qmm global-scale support, carried
+ # until it merges upstream into ml-explore/mlx-c. Then bump MLX_C_VERSION
+ # and delete mlx/compat/.
+ find_package(Git REQUIRED)
+ set(OLLAMA_MLX_C_COMPAT_PATCH_COMMAND
+ ${CMAKE_COMMAND}
+ -DPATCH_DIR=${CMAKE_SOURCE_DIR}/mlx/compat
+ -DPATCH_LABEL=mlx/compat
+ -P ${CMAKE_SOURCE_DIR}/cmake/apply-git-patches.cmake
+ CACHE INTERNAL "MLX-C carry patch")
+
+ set(_mlx_c_source_override FALSE)
if(DEFINED "FETCHCONTENT_SOURCE_DIR_MLX-C" AND NOT "${FETCHCONTENT_SOURCE_DIR_MLX-C}" STREQUAL "")
get_filename_component(OLLAMA_MLX_C_SOURCE_DIR
"${FETCHCONTENT_SOURCE_DIR_MLX-C}" ABSOLUTE BASE_DIR "${CMAKE_SOURCE_DIR}")
message(STATUS "Using MLX-C source override: ${OLLAMA_MLX_C_SOURCE_DIR}")
+ set(_mlx_c_source_override TRUE)
elseif(DEFINED ENV{OLLAMA_MLX_C_SOURCE})
get_filename_component(OLLAMA_MLX_C_SOURCE_DIR
"$ENV{OLLAMA_MLX_C_SOURCE}" ABSOLUTE BASE_DIR "${CMAKE_SOURCE_DIR}")
message(STATUS "Using local MLX-C source: ${OLLAMA_MLX_C_SOURCE_DIR}")
+ set(_mlx_c_source_override TRUE)
else()
set(OLLAMA_MLX_C_SOURCE_DIR "${CMAKE_BINARY_DIR}/_deps/mlx-c-src")
ExternalProject_Add(ollama-mlx-c-source
@@ -188,9 +202,22 @@ if(OLLAMA_MLX_BACKENDS)
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
- USES_TERMINAL_DOWNLOAD TRUE)
+ PATCH_COMMAND ${OLLAMA_MLX_C_COMPAT_PATCH_COMMAND}
+ USES_TERMINAL_DOWNLOAD TRUE
+ USES_TERMINAL_PATCH TRUE)
list(APPEND _mlx_source_targets ollama-mlx-c-source)
endif()
+ if(_mlx_c_source_override)
+ # Source overrides bypass the ExternalProject patch step, so the carry
+ # patch has to be applied to the override checkout as well. The
+ # applier is idempotent, which keeps repeated builds safe.
+ add_custom_target(ollama-mlx-c-override-patch
+ COMMAND ${OLLAMA_MLX_C_COMPAT_PATCH_COMMAND}
+ WORKING_DIRECTORY ${OLLAMA_MLX_C_SOURCE_DIR}
+ COMMENT "Applying MLX-C compat patches to ${OLLAMA_MLX_C_SOURCE_DIR}"
+ VERBATIM)
+ list(APPEND _mlx_source_targets ollama-mlx-c-override-patch)
+ endif()
# XGrammar has no pre-fetch: without an override each variant's build
# clones it via FetchContent.
if(DEFINED FETCHCONTENT_SOURCE_DIR_XGRAMMAR AND NOT "${FETCHCONTENT_SOURCE_DIR_XGRAMMAR}" STREQUAL "")
diff --git a/mlx/compat/0001-mlx-c-qmm-global-scale.patch b/mlx/compat/0001-mlx-c-qmm-global-scale.patch
new file mode 100644
index 000000000..a5bc7d6f2
--- /dev/null
+++ b/mlx/compat/0001-mlx-c-qmm-global-scale.patch
@@ -0,0 +1,33 @@
+diff --git a/mlx/c/ops.cpp b/mlx/c/ops.cpp
+index bf565d1..435706a 100644
+--- a/mlx/c/ops.cpp
++++ b/mlx/c/ops.cpp
+@@ -1687,6 +1687,7 @@ extern "C" int mlx_gather_qmm(
+ mlx_optional_int group_size,
+ mlx_optional_int bits,
+ const char* mode,
++ const mlx_array global_scale /* may be null */,
+ bool sorted_indices,
+ const mlx_stream s) {
+ try {
+@@ -1708,6 +1709,8 @@ extern "C" int mlx_gather_qmm(
+ (bits.has_value ? std::make_optional<int>(bits.value)
+ : std::nullopt),
+ std::string(mode),
++ (global_scale.ctx ? std::make_optional(mlx_array_get_(global_scale))
++ : std::nullopt),
+ sorted_indices,
+ mlx_stream_get_(s)));
+ } catch (std::exception& e) {
+diff --git a/mlx/c/ops.h b/mlx/c/ops.h
+index 7417785..6dfbf9e 100644
+--- a/mlx/c/ops.h
++++ b/mlx/c/ops.h
+@@ -548,6 +548,7 @@ int mlx_gather_qmm(
+ mlx_optional_int group_size,
+ mlx_optional_int bits,
+ const char* mode,
++ const mlx_array global_scale /* may be null */,
+ bool sorted_indices,
+ const mlx_stream s);
+ int mlx_gather_qqmm(
diff --git a/x/mlxrunner/mlx/depthwise_conv.go b/x/mlxrunner/mlx/depthwise_conv.go
index 12df18c9f..738e57ce6 100644
--- a/x/mlxrunner/mlx/depthwise_conv.go
+++ b/x/mlxrunner/mlx/depthwise_conv.go
@@ -35,7 +35,7 @@ out[elem] = static_cast<InT>(conv_out * sigmoid);
const depthwiseConvSiLUMetalHeader = `
template <typename T>
T stable_sigmoid(T x) {
- auto y = 1 / (1 + metal::exp(metal::abs(x)));
+ auto y = 1 / (1 + metal::precise::exp(metal::abs(x)));
return (x < 0) ? y : 1 - y;
}
`
diff --git a/x/mlxrunner/mlx/generated.c b/x/mlxrunner/mlx/generated.c
index 500875a94..9c671eb31 100644
--- a/x/mlxrunner/mlx/generated.c
+++ b/x/mlxrunner/mlx/generated.c
@@ -1404,6 +1404,7 @@ int (*mlx_gather_qmm_)(
mlx_optional_int group_size,
mlx_optional_int bits,
const char* mode,
+ const mlx_array global_scale /* may be null */,
bool sorted_indices,
const mlx_stream s) = NULL;
int (*mlx_gather_qqmm_)(
diff --git a/x/mlxrunner/mlx/generated.h b/x/mlxrunner/mlx/generated.h
index c60ab7c71..102500be9 100644
--- a/x/mlxrunner/mlx/generated.h
+++ b/x/mlxrunner/mlx/generated.h
@@ -2717,6 +2717,7 @@ extern int (*mlx_gather_qmm_)(
mlx_optional_int group_size,
mlx_optional_int bits,
const char* mode,
+ const mlx_array global_scale /* may be null */,
bool sorted_indices,
const mlx_stream s);
extern int (*mlx_gather_qqmm_)(
@@ -6045,9 +6046,10 @@ static inline int mlx_gather_qmm(
mlx_optional_int group_size,
mlx_optional_int bits,
const char* mode,
+ const mlx_array global_scale /* may be null */,
bool sorted_indices,
const mlx_stream s) {
- return mlx_gather_qmm_(res, x, w, scales, biases, lhs_indices, rhs_indices, transpose, group_size, bits, mode, sorted_indices, s);
+ return mlx_gather_qmm_(res, x, w, scales, biases, lhs_indices, rhs_indices, transpose, group_size, bits, mode, global_scale, sorted_indices, s);
}
static inline int mlx_gather_qqmm(
mlx_array* res,
diff --git a/x/mlxrunner/mlx/include/mlx/c/ops.h b/x/mlxrunner/mlx/include/mlx/c/ops.h
index 741778570..6dfbf9e1d 100644
--- a/x/mlxrunner/mlx/include/mlx/c/ops.h
+++ b/x/mlxrunner/mlx/include/mlx/c/ops.h
@@ -548,6 +548,7 @@ int mlx_gather_qmm(
mlx_optional_int group_size,
mlx_optional_int bits,
const char* mode,
+ const mlx_array global_scale /* may be null */,
bool sorted_indices,
const mlx_stream s);
int mlx_gather_qqmm(
diff --git a/x/mlxrunner/mlx/ops_extra.go b/x/mlxrunner/mlx/ops_extra.go
index 125dbb528..63b039e40 100644
--- a/x/mlxrunner/mlx/ops_extra.go
+++ b/x/mlxrunner/mlx/ops_extra.go
@@ -8,6 +8,25 @@ import (
"unsafe"
)
+// Nvfp4MaxProduct is the product of the maximum E4M3 and E2M1 values. Every
+// globalScale below is in MLX's representation: a checkpoint's multiplier m
+// (ModelOpt's weight_scale_2) is held as m*Nvfp4MaxProduct, so Nvfp4MaxProduct
+// itself is the identity. Wrappers that hand the scale to MLX pass it through;
+// wrappers that apply it themselves divide it back out.
+const Nvfp4MaxProduct = 448 * 6
+
+// scaleAndCast applies a global scale to an output and casts back, fusing the
+// divide, multiply and cast into one kernel. Eagerly this is several: MLX
+// promotes binary operands with an astype, so a bf16 input times a float32
+// scale round-trips through a full-size float32 intermediate.
+var scaleAndCast = Compile2(
+ "GlobalScaleOutput",
+ func(out, scale *Array) *Array {
+ return Mul(out, DivScalar(scale, Nvfp4MaxProduct)).AsType(out.DType())
+ },
+ Shapeless(),
+)
+
// Quantization operations
func Quantize(w *Array, groupSize, bits int, mode string) (weights, scales, biases *Array) {
@@ -45,6 +64,8 @@ func ToFP8(x *Array) *Array {
return out
}
+// Dequantize applies globalScale itself rather than forwarding it: MLX's own
+// argument accepts only a scalar, and callers pass per-expert banks.
func Dequantize(w, scales, biases *Array, groupSize, bits int, mode string, globalScale *Array) *Array {
cMode := C.CString(mode)
defer C.free(unsafe.Pointer(cMode))
@@ -61,19 +82,18 @@ func Dequantize(w, scales, biases *Array, groupSize, bits int, mode string, glob
var noGlobalScale C.mlx_array
mlxCheck(C.mlx_dequantize(&out.ctx, w.ctx, scales.ctx, b, optGroupSize, optBits, cMode, noGlobalScale, optDtype, DefaultStream().ctx))
if globalScale != nil {
- // The C-level global_scale argument is rejected on Metal; apply it on top.
gs := globalScale
- if gs.Size() > 1 {
- // A vector scale is per-row; bind it to the weight's leading axis.
- gs = Reshape(gs, int32(gs.Size()), 1)
+ for gs.NumDims() < out.NumDims() {
+ gs = ExpandDims(gs, -1)
}
- outType := out.DType()
- out = Mul(out, gs).AsType(outType)
+ out = scaleAndCast(out, gs)
}
return out
}
-func QuantizedMatmul(x, w, scales, biases *Array, transpose bool, groupSize, bits int, mode string) *Array {
+// QuantizedMatmul applies globalScale to the output; MLX's quantized_matmul
+// has none of its own.
+func QuantizedMatmul(x, w, scales, biases *Array, transpose bool, groupSize, bits int, mode string, globalScale *Array) *Array {
cMode := C.CString(mode)
defer C.free(unsafe.Pointer(cMode))
optGroupSize := C.mlx_optional_int{value: C.int(groupSize), has_value: true}
@@ -86,16 +106,23 @@ func QuantizedMatmul(x, w, scales, biases *Array, transpose bool, groupSize, bit
out := New("QUANTIZED_MATMUL")
mlxCheck(C.mlx_quantized_matmul(&out.ctx, x.ctx, w.ctx, scales.ctx, b, C.bool(transpose), optGroupSize, optBits, cMode, DefaultStream().ctx))
+ if globalScale != nil {
+ out = scaleAndCast(out, globalScale)
+ }
return out
}
-func GatherQMM(x, w, scales *Array, biases, lhsIndices, rhsIndices *Array, transpose bool, groupSize, bits int, mode string, sortedIndices bool) *Array {
+// GatherQMM multiplies x against the quantized weight banks selected by
+// lhsIndices and rhsIndices, with one globalScale entry per expert. Metal
+// applies it inside the gather kernel, other backends scale the gathered
+// output rows in the wrapper.
+func GatherQMM(x, w, scales *Array, biases, lhsIndices, rhsIndices *Array, transpose bool, groupSize, bits int, mode string, globalScale *Array, sortedIndices bool) *Array {
cMode := C.CString(mode)
defer C.free(unsafe.Pointer(cMode))
optGroupSize := C.mlx_optional_int{value: C.int(groupSize), has_value: true}
optBits := C.mlx_optional_int{value: C.int(bits), has_value: true}
- var b, lhs, rhs C.mlx_array
+ var b, lhs, rhs, gs C.mlx_array
if biases != nil {
b = biases.ctx
}
@@ -105,12 +132,37 @@ func GatherQMM(x, w, scales *Array, biases, lhsIndices, rhsIndices *Array, trans
if rhsIndices != nil {
rhs = rhsIndices.ctx
}
+ // The wrapper fallback needs rhs indices to map output rows to experts;
+ // without them the native path reports the unsupported combination.
+ applyWrapperScale := globalScale != nil && !MetalIsAvailable() && rhsIndices != nil
+ if globalScale != nil && !applyWrapperScale {
+ gs = globalScale.ctx
+ }
out := New("GATHER_QMM")
- mlxCheck(C.mlx_gather_qmm(&out.ctx, x.ctx, w.ctx, scales.ctx, b, lhs, rhs, C.bool(transpose), optGroupSize, optBits, cMode, C.bool(sortedIndices), DefaultStream().ctx))
+ mlxCheck(C.mlx_gather_qmm(&out.ctx, x.ctx, w.ctx, scales.ctx, b, lhs, rhs, C.bool(transpose), optGroupSize, optBits, cMode, gs, C.bool(sortedIndices), DefaultStream().ctx))
+ if applyWrapperScale {
+ out = mulGatherQMMGlobalScale(out, globalScale, rhsIndices)
+ }
return out
}
+// mulGatherQMMGlobalScale scales gathered output rows by the per-expert
+// global scale.
+func mulGatherQMMGlobalScale(out, globalScale, rhsIndices *Array) *Array {
+ // The indices address the weight's flattened batch dimensions, so the bank
+ // has to be flat too before taking from it.
+ perExpert := Reshape(globalScale, int32(globalScale.Size()))
+ scaleRows := Take(perExpert, rhsIndices, 0)
+ // out is the broadcast index shape plus the two matmul axes, and rhsIndices
+ // may be shorter, so pad left before appending those axes.
+ for scaleRows.NumDims() < out.NumDims()-2 {
+ scaleRows = ExpandDims(scaleRows, 0)
+ }
+ scaleRows = ExpandDims(ExpandDims(scaleRows, -1), -1)
+ return scaleAndCast(out, scaleRows)
+}
+
// Missing tensor ops
func Arange(start, stop, step float64, dtype DType) *Array {
@@ -129,6 +181,17 @@ func Tile(a *Array, reps []int32) *Array {
return out
}
+// BroadcastTo broadcasts an array to the given shape.
+func BroadcastTo(a *Array, shape ...int32) *Array {
+ cShape := make([]C.int, len(shape))
+ for i, s := range shape {
+ cShape[i] = C.int(s)
+ }
+ out := New("BROADCAST_TO")
+ mlxCheck(C.mlx_broadcast_to(&out.ctx, a.ctx, unsafe.SliceData(cShape), C.size_t(len(shape)), DefaultStream().ctx))
+ return out
+}
+
func Tri(n, m int32, k int) *Array {
out := New("TRI")
mlxCheck(C.mlx_tri(&out.ctx, C.int(n), C.int(m), C.int(k), C.mlx_dtype(DTypeFloat32), DefaultStream().ctx))
diff --git a/x/mlxrunner/mlx/ops_extra_test.go b/x/mlxrunner/mlx/ops_extra_test.go
index 648354085..fe06562ac 100644
--- a/x/mlxrunner/mlx/ops_extra_test.go
+++ b/x/mlxrunner/mlx/ops_extra_test.go
@@ -7,6 +7,16 @@ import (
"github.com/ollama/ollama/x/internal/mlxthreadtest"
)
+// mlxForm converts checkpoint multipliers to MLX's global-scale
+// representation, which is what the wrappers take.
+func mlxForm(checkpoint []float32) []float32 {
+ out := make([]float32, len(checkpoint))
+ for i, v := range checkpoint {
+ out[i] = v * Nvfp4MaxProduct
+ }
+ return out
+}
+
// fp4Values decodes an fp4 (E2M1) code to its value.
var fp4Values = [16]float32{0, 0.5, 1, 1.5, 2, 3, 4, 6, 0, -0.5, -1, -1.5, -2, -3, -4, -6}
@@ -16,6 +26,69 @@ func TestDequantizeGlobalScale(t *testing.T) {
})
}
+// TestMulGatherQMMGlobalScale checks the wrapper-side scaling that
+// non-Metal backends use in place of the gather kernel's global scale: the
+// gathered output rows are multiplied by the per-expert scale, converted from
+// amax units, and cast back. The reference gathers the dequantized weights.
+func TestMulGatherQMMGlobalScale(t *testing.T) {
+ withMLXThread(t, func(t *mlxthreadtest.T) {
+ if !MetalIsAvailable() {
+ t.Skip("building the unscaled gather requires a GPU backend")
+ }
+
+ const experts, rows, cols, group = 2, 4, 64, 16
+ packed := make([]uint32, experts*rows*cols/8)
+ for i := range packed {
+ for j := range 8 {
+ packed[i] |= uint32((i*8+j)%16) << (4 * j)
+ }
+ }
+ scaleBits := make([]uint8, experts*rows*(cols/group))
+ for i := range scaleBits {
+ exp := (i/(cols/group)+i%(cols/group))%4 - 1
+ scaleBits[i] = uint8((exp + 7) << 3)
+ }
+ weights := FromValues(packed, experts, rows, cols/8)
+ blockScales := FromValues(scaleBits, experts, rows, cols/group)
+ checkpointScales := []float32{0.5, 2}
+
+ xValues := make([]float32, cols)
+ for i := range xValues {
+ xValues[i] = float32(i%7-3) / 8
+ }
+ x := FromValues(xValues, 1, cols).AsType(DTypeBFloat16)
+ indices := FromValues([]int32{0, 1}, 1, experts)
+
+ kernelScales := make([]float32, experts)
+ for e := range kernelScales {
+ kernelScales[e] = checkpointScales[e] * Nvfp4MaxProduct
+ }
+ base := GatherQMM(x, weights, blockScales, nil, nil, indices,
+ true, group, 4, "nvfp4", nil, false)
+ got := mulGatherQMMGlobalScale(base, FromValues(kernelScales, experts), indices).AsType(DTypeFloat32)
+
+ dense := Dequantize(weights, blockScales, nil, group, 4, "nvfp4",
+ FromValues(kernelScales, experts)).AsType(DTypeFloat32)
+ want := GatherMM(x.AsType(DTypeFloat32), Transpose(dense, 0, 2, 1), nil, indices, false)
+ Eval(got, want)
+
+ gotValues, wantValues := got.Floats(), want.Floats()
+ if len(gotValues) != len(wantValues) {
+ t.Fatalf("result length = %d, want %d", len(gotValues), len(wantValues))
+ }
+ for i := range gotValues {
+ if math.IsNaN(float64(gotValues[i])) || math.IsInf(float64(gotValues[i]), 0) {
+ t.Fatalf("result[%d] = %v, want finite", i, gotValues[i])
+ }
+ delta := math.Abs(float64(gotValues[i] - wantValues[i]))
+ tolerance := 0.02 * math.Max(math.Abs(float64(wantValues[i])), 1)
+ if delta > tolerance {
+ t.Fatalf("result[%d] = %v, want %v (delta %v > %v)", i, gotValues[i], wantValues[i], delta, tolerance)
+ }
+ }
+ })
+}
+
// The quantized payload is built directly, the way an nvfp4 checkpoint ships
// it: packed fp4 codes, e4m3 group-scale bytes, and a separate global scale.
// Only the dequantize consumer path runs, so expectations are exact.
@@ -68,8 +141,8 @@ func testDequantizeGlobalScale(t *mlxthreadtest.T) {
scale *Array
gs func(r int) float32
}{
- {"scalar", FromValues([]float32{2}, 1), func(int) float32 { return 2 }},
- {"perRow", FromValues(perRow, rows), func(r int) float32 { return perRow[r] }},
+ {"scalar", FromValues([]float32{2 * Nvfp4MaxProduct}, 1), func(int) float32 { return 2 }},
+ {"perRow", FromValues(mlxForm(perRow), rows), func(r int) float32 { return perRow[r] }},
}
for _, tc := range cases {
got := Dequantize(wq, scales, nil, group, 4, "nvfp4", tc.scale)
@@ -78,4 +151,34 @@ func testDequantizeGlobalScale(t *mlxthreadtest.T) {
}
check(tc.name, got, tc.gs)
}
+
+ const experts = 2
+ expertPacked := make([]uint32, experts*len(packed))
+ expertScales := make([]uint8, experts*len(scaleBits))
+ for e := range experts {
+ copy(expertPacked[e*len(packed):], packed)
+ copy(expertScales[e*len(scaleBits):], scaleBits)
+ }
+ expertWeights := FromValues(expertPacked, experts, rows, cols/8)
+ expertBlockScales := FromValues(expertScales, experts, rows, cols/group)
+ expertGlobalScales := []float32{0.5, 2}
+ expertOut := Dequantize(
+ expertWeights,
+ expertBlockScales,
+ nil,
+ group,
+ 4,
+ "nvfp4",
+ FromValues(mlxForm(expertGlobalScales), experts),
+ ).AsType(DTypeFloat32)
+ Eval(expertOut)
+ for i, got := range expertOut.Floats() {
+ e := i / (rows * cols)
+ r := (i / cols) % rows
+ c := i % cols
+ want := fp4Values[c%16] * scaleOf(r, c/group) * expertGlobalScales[e]
+ if got != want {
+ t.Fatalf("expert bank[%d] = %v, want %v", i, got, want)
+ }
+ }
}
diff --git a/x/mlxrunner/model/embedding.go b/x/mlxrunner/model/embedding.go
index 1b3c14ef9..021ef3044 100644
--- a/x/mlxrunner/model/embedding.go
+++ b/x/mlxrunner/model/embedding.go
@@ -35,13 +35,7 @@ func MakeEmbeddingLayer(
scales,
)
- // Check for per-tensor global scale (NVIDIA double-scale nvfp4).
- // NVIDIA ModelOpt stores this as "weight_scale_2"; our import
- // pipeline maps it to "weight.global_scale".
- globalScale := tensors[path+".weight.global_scale"]
- if globalScale == nil {
- globalScale = tensors[path+".weight_scale_2"]
- }
+ globalScale, _ := ReadGlobalScale(tensors, path+".weight")
return &nn.QuantizedEmbedding{
Weight: w,
diff --git a/x/mlxrunner/model/embedding_test.go b/x/mlxrunner/model/embedding_test.go
index 7f57a10c4..8ef08652f 100644
--- a/x/mlxrunner/model/embedding_test.go
+++ b/x/mlxrunner/model/embedding_test.go
@@ -71,50 +71,55 @@ func TestMakeEmbeddingLayerQuantized(t *testing.T) {
})
}
+// A checkpoint scale is converted to MLX's representation at load, and the
+// same converted scale reaches the linear view.
func TestMakeEmbeddingLayerQuantizedGlobalScale(t *testing.T) {
- weight := &mlx.Array{}
- scales := &mlx.Array{}
- globalScale := &mlx.Array{}
-
- emb := MakeEmbeddingLayer(map[string]*mlx.Array{
- "model.embed_tokens.weight": weight,
- "model.embed_tokens.weight_scale": scales,
- "model.embed_tokens.weight.global_scale": globalScale,
- }, "model.embed_tokens", 16, 4, "nvfp4", nil)
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ const checkpoint = 0.375
+ emb := MakeEmbeddingLayer(map[string]*mlx.Array{
+ "model.embed_tokens.weight": {},
+ "model.embed_tokens.weight_scale": {},
+ "model.embed_tokens.weight.global_scale": mlx.FromValues([]float32{checkpoint}, 1),
+ }, "model.embed_tokens", 16, 4, "nvfp4", nil)
- qemb, ok := emb.(*nn.QuantizedEmbedding)
- if !ok {
- t.Fatalf("embedding type = %T, want *nn.QuantizedEmbedding", emb)
- }
- if qemb.GlobalScale != globalScale {
- t.Fatalf("GlobalScale = %p, want %p", qemb.GlobalScale, globalScale)
- }
+ qemb, ok := emb.(*nn.QuantizedEmbedding)
+ if !ok {
+ t.Fatalf("embedding type = %T, want *nn.QuantizedEmbedding", emb)
+ }
+ mlx.Eval(qemb.GlobalScale)
+ want := float32(checkpoint * mlx.Nvfp4MaxProduct)
+ if got := qemb.GlobalScale.Floats(); len(got) != 1 || got[0] != want {
+ t.Fatalf("GlobalScale = %v, want [%v]", got, want)
+ }
- linear, ok := qemb.AsLinear().(*nn.QuantizedLinear)
- if !ok {
- t.Fatalf("AsLinear type = %T, want *nn.QuantizedLinear", qemb.AsLinear())
- }
- if linear.GlobalScale != globalScale {
- t.Fatalf("AsLinear GlobalScale = %p, want %p", linear.GlobalScale, globalScale)
- }
+ linear, ok := qemb.AsLinear().(*nn.QuantizedLinear)
+ if !ok {
+ t.Fatalf("AsLinear type = %T, want *nn.QuantizedLinear", qemb.AsLinear())
+ }
+ if linear.GlobalScale != qemb.GlobalScale {
+ t.Fatalf("AsLinear GlobalScale = %p, want %p", linear.GlobalScale, qemb.GlobalScale)
+ }
+ })
}
+// ModelOpt's own "weight_scale_2" name is honoured, and converted the same way.
func TestMakeEmbeddingLayerQuantizedGlobalScaleFallback(t *testing.T) {
- weight := &mlx.Array{}
- scales := &mlx.Array{}
- globalScale := &mlx.Array{}
-
- emb := MakeEmbeddingLayer(map[string]*mlx.Array{
- "model.embed_tokens.weight": weight,
- "model.embed_tokens.weight_scale": scales,
- "model.embed_tokens.weight_scale_2": globalScale,
- }, "model.embed_tokens", 16, 4, "nvfp4", nil)
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ const checkpoint = 0.375
+ emb := MakeEmbeddingLayer(map[string]*mlx.Array{
+ "model.embed_tokens.weight": {},
+ "model.embed_tokens.weight_scale": {},
+ "model.embed_tokens.weight_scale_2": mlx.FromValues([]float32{checkpoint}, 1),
+ }, "model.embed_tokens", 16, 4, "nvfp4", nil)
- qemb, ok := emb.(*nn.QuantizedEmbedding)
- if !ok {
- t.Fatalf("embedding type = %T, want *nn.QuantizedEmbedding", emb)
- }
- if qemb.GlobalScale != globalScale {
- t.Fatalf("GlobalScale = %p, want %p", qemb.GlobalScale, globalScale)
- }
+ qemb, ok := emb.(*nn.QuantizedEmbedding)
+ if !ok {
+ t.Fatalf("embedding type = %T, want *nn.QuantizedEmbedding", emb)
+ }
+ mlx.Eval(qemb.GlobalScale)
+ want := float32(checkpoint * mlx.Nvfp4MaxProduct)
+ if got := qemb.GlobalScale.Floats(); len(got) != 1 || got[0] != want {
+ t.Fatalf("GlobalScale = %v, want [%v]", got, want)
+ }
+ })
}
diff --git a/x/mlxrunner/model/linear.go b/x/mlxrunner/model/linear.go
index cfbcfd3a7..34dbfe8b4 100644
--- a/x/mlxrunner/model/linear.go
+++ b/x/mlxrunner/model/linear.go
@@ -74,13 +74,7 @@ func MakeLinearLayer(
scales,
)
- // Check for per-tensor global scale (NVIDIA double-scale nvfp4).
- // NVIDIA ModelOpt stores this as "weight_scale_2"; our import
- // pipeline maps it to "weight.global_scale".
- globalScale := tensors[path+".weight.global_scale"]
- if globalScale == nil {
- globalScale = tensors[path+".weight_scale_2"]
- }
+ globalScale, _ := ReadGlobalScale(tensors, path+".weight")
return &nn.QuantizedLinear{
Weight: w,
diff --git a/x/mlxrunner/model/quant.go b/x/mlxrunner/model/quant.go
index c027424a4..611b9e6b9 100644
--- a/x/mlxrunner/model/quant.go
+++ b/x/mlxrunner/model/quant.go
@@ -5,6 +5,92 @@ import (
"github.com/ollama/ollama/x/quant"
)
+// Import rewrites every vendor spelling to ".global_scale"; "_scale_2" is
+// ModelOpt's own name, reached when a checkpoint skips import.
+var globalScaleSuffixes = []string{".global_scale", "_scale_2"}
+
+// These scale the activations, never the weight, but are freed alongside it.
+var activationScaleSuffixes = []string{".input_global_scale", ".input_scale"}
+
+// ReadGlobalScale returns a weight's NVFP4 global scale in MLX's
+// representation, and the companion keys the caller should release. Candidate
+// keys are tried in order, so pass the resolved tensor key before any base.
+func ReadGlobalScale(tensors map[string]*mlx.Array, weightKeys ...string) (*mlx.Array, []string) {
+ var found *mlx.Array
+ var consumed []string
+ for _, key := range weightKeys {
+ if key == "" {
+ continue
+ }
+ for _, suffix := range globalScaleSuffixes {
+ scale, ok := tensors[key+suffix]
+ if !ok || scale == nil {
+ continue
+ }
+ if found == nil {
+ found = scale
+ }
+ consumed = append(consumed, key+suffix)
+ }
+ for _, suffix := range activationScaleSuffixes {
+ if _, ok := tensors[key+suffix]; ok {
+ consumed = append(consumed, key+suffix)
+ }
+ }
+ }
+ return ToMLXGlobalScale(found), consumed
+}
+
+// ToMLXGlobalScale converts a checkpoint multiplier into the representation
+// every global scale is held in once loaded. Shape is flattened too: a scalar
+// ships as either [] or [1], and stacking a mix of the two fails.
+func ToMLXGlobalScale(globalScale *mlx.Array) *mlx.Array {
+ if globalScale == nil {
+ return nil
+ }
+ flat := mlx.Reshape(globalScale.AsType(mlx.DTypeFloat32), int32(globalScale.Size()))
+ return mlx.MulScalar(flat, mlx.Nvfp4MaxProduct)
+}
+
+// PrepareGatherQMMGlobalScale broadcasts an already-converted global scale
+// into the one-entry-per-expert bank gather_qmm wants. Materialized dense: the
+// kernel indexes it by raw offset, and a broadcast view is one element of
+// storage.
+func PrepareGatherQMMGlobalScale(globalScale *mlx.Array, numExperts int) *mlx.Array {
+ if globalScale == nil {
+ return nil
+ }
+ return mlx.Contiguous(mlx.BroadcastTo(globalScale, int32(numExperts)), false)
+}
+
+// GatherQMMIdentityScale is the scale that leaves an expert bank unscaled,
+// for rows folded into a scaled bank without a scale of their own.
+func GatherQMMIdentityScale() *mlx.Array {
+ return mlx.FromValues([]float32{mlx.Nvfp4MaxProduct}, 1)
+}
+
+// SameGlobalScales reports whether two prepared banks hold the same scale for
+// every expert, which is what lets two projections share one fused bank.
+func SameGlobalScales(a, b *mlx.Array) bool {
+ if a == nil || b == nil {
+ return a == nil && b == nil
+ }
+ if a == b {
+ return true
+ }
+ if a.Size() != b.Size() {
+ return false
+ }
+ mlx.Eval(a, b)
+ aValues, bValues := a.Floats(), b.Floats()
+ for i := range aValues {
+ if aValues[i] != bValues[i] {
+ return false
+ }
+ }
+ return true
+}
+
// QuantizationParams returns default groupSize, bits, and mode for a
// quantization type. The values live in the shared x/quant package so the
// importer, the runtime loader, and `ollama show` agree on them.
diff --git a/x/mlxrunner/model/quant_global_scale_test.go b/x/mlxrunner/model/quant_global_scale_test.go
new file mode 100644
index 000000000..c19af46e9
--- /dev/null
+++ b/x/mlxrunner/model/quant_global_scale_test.go
@@ -0,0 +1,250 @@
+package model
+
+import (
+ "math"
+ "slices"
+ "testing"
+
+ "github.com/ollama/ollama/x/internal/mlxtest"
+ "github.com/ollama/ollama/x/mlxrunner/mlx"
+)
+
+// ToMLXGlobalScale converts and flattens; PrepareGatherQMMGlobalScale only
+// broadcasts what it is given. Keeping the conversion in one place is what
+// lets a scale be read once and used by every consumer.
+func TestGlobalScaleConversion(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ if got := ToMLXGlobalScale(nil); got != nil {
+ t.Fatal("nil scale did not convert to nil")
+ }
+ if got := PrepareGatherQMMGlobalScale(nil, 4); got != nil {
+ t.Fatal("nil scale did not broadcast to nil")
+ }
+
+ // Checkpoints ship a scalar as either [] or [1]; both normalize to [1]
+ // so a mix of the two can still be stacked.
+ for _, scalar := range []*mlx.Array{
+ mlx.NewScalarArray(2),
+ mlx.FromValues([]float32{2}, 1),
+ } {
+ got := ToMLXGlobalScale(scalar)
+ mlx.Eval(got)
+ if dims := got.Dims(); len(dims) != 1 || dims[0] != 1 {
+ t.Fatalf("converted scalar dims = %v, want [1]", dims)
+ }
+ if want := float32(2 * mlx.Nvfp4MaxProduct); got.Floats()[0] != want {
+ t.Fatalf("converted scalar = %v, want %v", got.Floats()[0], want)
+ }
+ }
+
+ checkpointScales := []float32{0.5, 1, 2, 4}
+ perExpert := ToMLXGlobalScale(mlx.FromValues(checkpointScales, 4))
+ mlx.Eval(perExpert)
+ for i, got := range perExpert.Floats() {
+ if want := checkpointScales[i] * float32(mlx.Nvfp4MaxProduct); got != want {
+ t.Fatalf("converted scale[%d] = %v, want %v", i, got, want)
+ }
+ }
+
+ // Broadcasting is value-preserving, and does not convert a second time.
+ bank := PrepareGatherQMMGlobalScale(ToMLXGlobalScale(mlx.FromValues([]float32{2}, 1)), 4)
+ mlx.Eval(bank)
+ if dims := bank.Dims(); len(dims) != 1 || dims[0] != 4 {
+ t.Fatalf("bank dims = %v, want [4]", dims)
+ }
+ for i, got := range bank.Floats() {
+ if want := float32(2 * mlx.Nvfp4MaxProduct); got != want {
+ t.Fatalf("bank[%d] = %v, want %v", i, got, want)
+ }
+ }
+
+ // A scale count that is neither a checkpoint-wide scalar nor one per
+ // expert is malformed and fails the load instead of being ignored.
+ func() {
+ defer func() {
+ if recover() == nil {
+ t.Fatal("mismatched scale count did not fail")
+ }
+ }()
+ PrepareGatherQMMGlobalScale(ToMLXGlobalScale(mlx.FromValues([]float32{1, 2}, 2)), 4)
+ }()
+ })
+}
+
+func TestSameGlobalScales(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ perExpert := PrepareGatherQMMGlobalScale(mlx.FromValues([]float32{0.5, 1, 2, 4}, 4), 4)
+ same := PrepareGatherQMMGlobalScale(mlx.FromValues([]float32{0.5, 1, 2, 4}, 4), 4)
+ reordered := PrepareGatherQMMGlobalScale(mlx.FromValues([]float32{4, 2, 1, 0.5}, 4), 4)
+ broadcast := PrepareGatherQMMGlobalScale(mlx.FromValues([]float32{2}, 1), 4)
+ shorter := PrepareGatherQMMGlobalScale(mlx.FromValues([]float32{2}, 1), 2)
+
+ for _, tt := range []struct {
+ name string
+ a, b *mlx.Array
+ want bool
+ }{
+ {"both nil", nil, nil, true},
+ {"only one nil", perExpert, nil, false},
+ {"identical array", perExpert, perExpert, true},
+ {"equal values", perExpert, same, true},
+ {"same values reordered", perExpert, reordered, false},
+ {"broadcast scalar matches itself", broadcast, broadcast, true},
+ {"different expert counts", broadcast, shorter, false},
+ } {
+ if got := SameGlobalScales(tt.a, tt.b); got != tt.want {
+ t.Fatalf("%s: SameGlobalScales() = %v, want %v", tt.name, got, tt.want)
+ }
+ }
+ })
+}
+
+// TestGatherQMMGlobalScaleMatchesDequantized checks the whole scale chain —
+// Prepare's conversion to amax units plus the GatherQMM wrapper — against the
+// dequantized weights gathered densely. Metal runs the native kernel path;
+// CUDA runs the wrapper's output scaling. ModelOpt exports a checkpoint-wide
+// scalar, so both it and the per-expert form are covered.
+func TestGatherQMMGlobalScaleMatchesDequantized(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ if !mlx.MetalIsAvailable() && !mlx.CUDAIsAvailable() {
+ t.Skip("gather_qmm requires a GPU backend")
+ }
+
+ const experts, rows, cols, groupSize = 4, 32, 64, 16
+ packed := make([]uint32, experts*rows*cols/8)
+ for i := range packed {
+ for j := range 8 {
+ packed[i] |= uint32((i*8+j)%16) << (4 * j)
+ }
+ }
+ scales := make([]uint8, experts*rows*cols/groupSize)
+ for i := range scales {
+ scales[i] = uint8(((i % 4) + 6) << 3)
+ }
+ weights := mlx.FromValues(packed, experts, rows, cols/8)
+ blockScales := mlx.FromValues(scales, experts, rows, cols/groupSize)
+
+ xValues := make([]float32, cols)
+ for i := range xValues {
+ xValues[i] = float32(i%7-3) / 8
+ }
+ x := mlx.FromValues(xValues, 1, cols).AsType(mlx.DTypeBFloat16)
+ indices := mlx.FromValues([]int32{0, 1, 2, 3}, 1, experts)
+
+ for _, checkpointScale := range [][]float32{
+ {0.5, 1, 2, 4}, // one scale per expert
+ {2}, // checkpoint-wide scalar
+ } {
+ checkpoint := mlx.FromValues(checkpointScale, len(checkpointScale))
+ kernelScale := PrepareGatherQMMGlobalScale(checkpoint, experts)
+
+ got := mlx.GatherQMM(
+ x, weights, blockScales, nil, nil, indices,
+ true, groupSize, 4, "nvfp4", kernelScale, false,
+ ).AsType(mlx.DTypeFloat32)
+ dense := mlx.Dequantize(
+ weights, blockScales, nil, groupSize, 4, "nvfp4", checkpoint,
+ ).AsType(mlx.DTypeFloat32)
+ want := mlx.GatherMM(
+ x.AsType(mlx.DTypeFloat32), mlx.Transpose(dense, 0, 2, 1), nil, indices, false,
+ )
+ mlx.Eval(got, want)
+
+ gotValues, wantValues := got.Floats(), want.Floats()
+ if len(gotValues) != len(wantValues) {
+ t.Fatalf("result length = %d, want %d", len(gotValues), len(wantValues))
+ }
+ for i := range gotValues {
+ if math.IsNaN(float64(gotValues[i])) || math.IsInf(float64(gotValues[i]), 0) {
+ t.Fatalf("result[%d] = %v, want finite", i, gotValues[i])
+ }
+ delta := math.Abs(float64(gotValues[i] - wantValues[i]))
+ tolerance := 0.01 * math.Max(math.Abs(float64(wantValues[i])), 1)
+ if delta > tolerance {
+ t.Fatalf("result[%d] = %v, want %v (delta %v > %v)", i, gotValues[i], wantValues[i], delta, tolerance)
+ }
+ }
+ }
+ })
+}
+
+// One key policy for every model. The canonical name import writes wins;
+// ModelOpt's own name is the fallback for un-imported checkpoints; and an
+// activation scale is consumed but never mistaken for a weight scale.
+func TestReadGlobalScale(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ scale := func(v float32) *mlx.Array { return mlx.FromValues([]float32{v}, 1) }
+ mlxForm := func(v float32) float32 { return v * mlx.Nvfp4MaxProduct }
+
+ for _, tt := range []struct {
+ name string
+ tensors map[string]*mlx.Array
+ want float32 // 0 means "expect nil"
+ consumed []string
+ }{
+ {
+ name: "canonical name",
+ tensors: map[string]*mlx.Array{"w.weight.global_scale": scale(0.5)},
+ want: mlxForm(0.5),
+ consumed: []string{"w.weight.global_scale"},
+ },
+ {
+ name: "modelopt fallback",
+ tensors: map[string]*mlx.Array{"w.weight_scale_2": scale(0.25)},
+ want: mlxForm(0.25),
+ consumed: []string{"w.weight_scale_2"},
+ },
+ {
+ name: "canonical wins over fallback",
+ tensors: map[string]*mlx.Array{
+ "w.weight.global_scale": scale(0.5),
+ "w.weight_scale_2": scale(0.25),
+ },
+ want: mlxForm(0.5),
+ consumed: []string{"w.weight.global_scale", "w.weight_scale_2"},
+ },
+ {
+ // An activation scale is not a weight scale. Picking it up
+ // would silently rescale every output.
+ name: "activation scale is never the weight scale",
+ tensors: map[string]*mlx.Array{"w.weight.input_global_scale": scale(8)},
+ want: 0,
+ consumed: []string{"w.weight.input_global_scale"},
+ },
+ {
+ name: "activation scale alongside a weight scale",
+ tensors: map[string]*mlx.Array{
+ "w.weight.global_scale": scale(0.5),
+ "w.weight.input_global_scale": scale(8),
+ },
+ want: mlxForm(0.5),
+ consumed: []string{"w.weight.global_scale", "w.weight.input_global_scale"},
+ },
+ {name: "absent", tensors: map[string]*mlx.Array{}, want: 0},
+ } {
+ got, consumed := ReadGlobalScale(tt.tensors, "w.weight")
+ if tt.want == 0 {
+ if got != nil {
+ mlx.Eval(got)
+ t.Fatalf("%s: got %v, want nil", tt.name, got.Floats())
+ }
+ } else {
+ if got == nil {
+ t.Fatalf("%s: got nil, want [%v]", tt.name, tt.want)
+ }
+ mlx.Eval(got)
+ if values := got.Floats(); len(values) != 1 || values[0] != tt.want {
+ t.Fatalf("%s: got %v, want [%v]", tt.name, values, tt.want)
+ }
+ }
+ if len(consumed) != len(tt.consumed) {
+ t.Fatalf("%s: consumed %v, want %v", tt.name, consumed, tt.consumed)
+ }
+ for _, key := range tt.consumed {
+ if !slices.Contains(consumed, key) {
+ t.Fatalf("%s: consumed %v, missing %q", tt.name, consumed, key)
+ }
+ }
+ }
+ })
+}
diff --git a/x/models/cohere2_moe/cohere2_moe.go b/x/models/cohere2_moe/cohere2_moe.go
index d29a20099..884afb173 100644
--- a/x/models/cohere2_moe/cohere2_moe.go
+++ b/x/models/cohere2_moe/cohere2_moe.go
@@ -150,9 +150,10 @@ type SwitchMLP struct {
UpWeight *mlx.Array
DownWeight *mlx.Array
- GateWeightQ, GateScales, GateBiases *mlx.Array
- UpWeightQ, UpScales, UpBiases *mlx.Array
- DownWeightQ, DownScales, DownBiases *mlx.Array
+ GateWeightQ, GateScales, GateBiases *mlx.Array
+ UpWeightQ, UpScales, UpBiases *mlx.Array
+ DownWeightQ, DownScales, DownBiases *mlx.Array
+ GateGlobalScales, UpGlobalScales, DownGlobalScales *mlx.Array
GateBits, UpBits, DownBits int
GateGroupSize, UpGroupSize, DownGroupSize int
@@ -162,12 +163,14 @@ type SwitchMLP struct {
}
type stackedExpertWeights struct {
- Weight *mlx.Array
- Scales *mlx.Array
- Biases *mlx.Array
- Bits int
- GroupSize int
- Mode string
+ Weight *mlx.Array
+ Scales *mlx.Array
+ Biases *mlx.Array
+ GlobalScales *mlx.Array
+ Bits int
+ GroupSize int
+ Mode string
+ SourceQuantized bool
}
func parseConfig(configData []byte) (Config, error) {
@@ -420,37 +423,151 @@ func loadStackedProjection(tensors map[string]*mlx.Array, cfg *Config, useQuanti
}
qbiases := tensors[key+"_qbias"]
+ globalScale, _ := model.ReadGlobalScale(tensors, key, key+".weight")
groupSize, bits, mode := model.ResolveLinearQuantParams(
cfg.QuantGroupSize, cfg.QuantBits, cfg.QuantMode, cfg.TensorQuant,
key, w, scales,
)
+ globalScale = model.PrepareGatherQMMGlobalScale(globalScale, w.Dim(0))
if useQuantized && supportsGatherQMM(mode, bits) {
return &stackedExpertWeights{
- Weight: w,
- Scales: scales,
- Biases: qbiases,
- Bits: bits,
- GroupSize: groupSize,
- Mode: mode,
+ Weight: w,
+ Scales: scales,
+ Biases: qbiases,
+ GlobalScales: globalScale,
+ Bits: bits,
+ GroupSize: groupSize,
+ Mode: mode,
+ SourceQuantized: true,
}
}
return &stackedExpertWeights{
- Weight: mlx.Dequantize(w, scales, qbiases, groupSize, bits, mode, nil),
+ Weight: mlx.Dequantize(w, scales, qbiases, groupSize, bits, mode, globalScale),
+ Biases: qbiases,
+ Bits: bits,
+ GroupSize: groupSize,
+ Mode: mode,
+ SourceQuantized: true,
+ }
+}
+
+func denseExpertWeight(w *stackedExpertWeights) *mlx.Array {
+ if w.Scales == nil {
+ return w.Weight
+ }
+ return mlx.Dequantize(
+ w.Weight, w.Scales, w.Biases, w.GroupSize, w.Bits, w.Mode, w.GlobalScales,
+ )
+}
+
+func loadExpertProjection(tensors map[string]*mlx.Array, cfg *Config, useQuantized bool, base string) *stackedExpertWeights {
+ key := base + ".weight"
+ w := tensors[key]
+ if w == nil {
+ return nil
+ }
+
+ scales := tensors[key+"_scale"]
+ if scales == nil {
+ return &stackedExpertWeights{Weight: w}
+ }
+
+ qbiases := tensors[key+"_qbias"]
+ globalScale, _ := model.ReadGlobalScale(tensors, key, key+".weight")
+ groupSize, bits, mode := model.ResolveLinearQuantParams(
+ cfg.QuantGroupSize, cfg.QuantBits, cfg.QuantMode, cfg.TensorQuant,
+ key, w, scales,
+ )
+ if useQuantized && supportsGatherQMM(mode, bits) {
+ return &stackedExpertWeights{
+ Weight: w,
+ Scales: scales,
+ Biases: qbiases,
+ GlobalScales: globalScale,
+ Bits: bits,
+ GroupSize: groupSize,
+ Mode: mode,
+ SourceQuantized: true,
+ }
+ }
+
+ return &stackedExpertWeights{
+ Weight: mlx.Dequantize(w, scales, qbiases, groupSize, bits, mode, globalScale),
+ Biases: qbiases,
+ Bits: bits,
+ GroupSize: groupSize,
+ Mode: mode,
+ SourceQuantized: true,
+ }
+}
+
+func collectExpertProjection(tensors map[string]*mlx.Array, cfg *Config, useQuantized bool, layerPrefix, proj string) *stackedExpertWeights {
+ var weights, scales, biases, globalScales []*mlx.Array
+ var bits, groupSize int
+ var mode string
+ var quantized bool
+ var sourceQuantized bool
+
+ for e := range cfg.NumExperts {
+ base := fmt.Sprintf("%s.mlp.experts.%d.%s", layerPrefix, e, proj)
+ part := loadExpertProjection(tensors, cfg, useQuantized, base)
+ if part == nil {
+ return nil
+ }
+ if e == 0 {
+ bits, groupSize, mode = part.Bits, part.GroupSize, part.Mode
+ quantized = part.Scales != nil
+ sourceQuantized = part.SourceQuantized
+ } else if quantized != (part.Scales != nil) ||
+ sourceQuantized != part.SourceQuantized ||
+ (sourceQuantized && (part.Bits != bits || part.GroupSize != groupSize || part.Mode != mode)) {
+ return nil
+ }
+
+ weights = append(weights, part.Weight)
+ if part.Scales != nil {
+ scales = append(scales, part.Scales)
+ }
+ if part.Biases != nil {
+ biases = append(biases, part.Biases)
+ }
+ if part.GlobalScales != nil {
+ globalScales = append(globalScales, part.GlobalScales)
+ }
+ }
+
+ result := &stackedExpertWeights{
+ Weight: mlx.Stack(weights, 0),
Bits: bits,
GroupSize: groupSize,
Mode: mode,
}
+ if (len(biases) != 0 && len(biases) != len(weights)) ||
+ (len(globalScales) != 0 && len(globalScales) != len(weights)) {
+ return nil
+ }
+ if quantized {
+ result.Scales = mlx.Stack(scales, 0)
+ if len(biases) == len(weights) {
+ result.Biases = mlx.Stack(biases, 0)
+ }
+ if len(globalScales) == len(weights) {
+ result.GlobalScales = mlx.Reshape(mlx.Stack(globalScales, 0), cfg.NumExperts)
+ }
+ }
+ return result
}
-// loadStackedExperts resolves a stacked expert projection by its close-to-source
-// name (layers.N.mlp.experts.<proj>, which `ollama create` now writes) and falls
-// back to the legacy switch_mlp name that older imports produced.
+// loadStackedExperts resolves both packed and per-expert checkpoint layouts.
func loadStackedExperts(tensors map[string]*mlx.Array, cfg *Config, useQuantized bool, layerPrefix, proj string) *stackedExpertWeights {
if w := loadStackedProjection(tensors, cfg, useQuantized, layerPrefix+".mlp.experts."+proj); w != nil {
return w
}
- return loadStackedProjection(tensors, cfg, useQuantized, layerPrefix+".mlp.switch_mlp."+proj)
+ if w := loadStackedProjection(tensors, cfg, useQuantized, layerPrefix+".mlp.switch_mlp."+proj); w != nil {
+ return w
+ }
+ return collectExpertProjection(tensors, cfg, useQuantized, layerPrefix, proj)
}
// LoadWeights assigns tensors to model fields.
@@ -538,7 +655,7 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
upW := loadStackedExperts(tensors, cfg, useQuantizedExperts, layerPrefix, "up_proj")
downW := loadStackedExperts(tensors, cfg, useQuantizedExperts, layerPrefix, "down_proj")
if gateW == nil || upW == nil || downW == nil {
- return fmt.Errorf("layer %d: missing stacked expert weights (import the model with `ollama create`)", i)
+ return fmt.Errorf("layer %d: missing expert weights", i)
}
switchMLP := &SwitchMLP{}
@@ -547,25 +664,28 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
switchMLP.GateWeightQ = gateW.Weight
switchMLP.GateScales = gateW.Scales
switchMLP.GateBiases = gateW.Biases
+ switchMLP.GateGlobalScales = gateW.GlobalScales
switchMLP.GateBits = gateW.Bits
switchMLP.GateGroupSize = gateW.GroupSize
switchMLP.GateMode = gateW.Mode
switchMLP.UpWeightQ = upW.Weight
switchMLP.UpScales = upW.Scales
switchMLP.UpBiases = upW.Biases
+ switchMLP.UpGlobalScales = upW.GlobalScales
switchMLP.UpBits = upW.Bits
switchMLP.UpGroupSize = upW.GroupSize
switchMLP.UpMode = upW.Mode
switchMLP.DownWeightQ = downW.Weight
switchMLP.DownScales = downW.Scales
switchMLP.DownBiases = downW.Biases
+ switchMLP.DownGlobalScales = downW.GlobalScales
switchMLP.DownBits = downW.Bits
switchMLP.DownGroupSize = downW.GroupSize
switchMLP.DownMode = downW.Mode
} else {
- switchMLP.GateWeight = transposeExpertWeightForGatherMM(gateW.Weight)
- switchMLP.UpWeight = transposeExpertWeightForGatherMM(upW.Weight)
- switchMLP.DownWeight = transposeExpertWeightForGatherMM(downW.Weight)
+ switchMLP.GateWeight = transposeExpertWeightForGatherMM(denseExpertWeight(gateW))
+ switchMLP.UpWeight = transposeExpertWeightForGatherMM(denseExpertWeight(upW))
+ switchMLP.DownWeight = transposeExpertWeightForGatherMM(denseExpertWeight(downW))
}
moe.SwitchMLP = switchMLP
@@ -694,12 +814,15 @@ func (s *SwitchMLP) Forward(x *mlx.Array, indices *mlx.Array, cfg *Config) *mlx.
var gate, up, hidden, down *mlx.Array
if s.UseQuantized {
gate = mlx.GatherQMM(xFlat, s.GateWeightQ, s.GateScales, s.GateBiases,
- nil, idxFlat, true, s.GateGroupSize, s.GateBits, s.GateMode, doSort)
+ nil, idxFlat, true, s.GateGroupSize, s.GateBits, s.GateMode,
+ s.GateGlobalScales, doSort)
up = mlx.GatherQMM(xFlat, s.UpWeightQ, s.UpScales, s.UpBiases,
- nil, idxFlat, true, s.UpGroupSize, s.UpBits, s.UpMode, doSort)
+ nil, idxFlat, true, s.UpGroupSize, s.UpBits, s.UpMode,
+ s.UpGlobalScales, doSort)
hidden = mlx.SwiGLU(gate, up)
down = mlx.GatherQMM(hidden, s.DownWeightQ, s.DownScales, s.DownBiases,
- nil, idxFlat, true, s.DownGroupSize, s.DownBits, s.DownMode, doSort)
+ nil, idxFlat, true, s.DownGroupSize, s.DownBits, s.DownMode,
+ s.DownGlobalScales, doSort)
} else {
gate = mlx.GatherMM(xFlat, s.GateWeight, nil, idxFlat, doSort)
up = mlx.GatherMM(xFlat, s.UpWeight, nil, idxFlat, doSort)
diff --git a/x/models/cohere2_moe/cohere2_moe_test.go b/x/models/cohere2_moe/cohere2_moe_test.go
new file mode 100644
index 000000000..099d38c8d
--- /dev/null
+++ b/x/models/cohere2_moe/cohere2_moe_test.go
@@ -0,0 +1,46 @@
+package cohere2_moe
+
+import (
+ "fmt"
+ "testing"
+
+ "github.com/ollama/ollama/x/internal/mlxtest"
+ "github.com/ollama/ollama/x/mlxrunner/mlx"
+)
+
+func TestLoadPerExpertGlobalScale(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ const experts, rows, cols, groupSize = 4, 32, 64, 16
+ cfg := &Config{
+ NumExperts: experts,
+ QuantGroupSize: groupSize,
+ QuantBits: 4,
+ QuantMode: "nvfp4",
+ }
+ tensors := make(map[string]*mlx.Array)
+ for e := range experts {
+ base := fmt.Sprintf("model.layers.1.mlp.experts.%d.gate_proj.weight", e)
+ tensors[base] = mlx.Zeros(mlx.DTypeUint32, rows, cols/8)
+ tensors[base+"_scale"] = mlx.Zeros(mlx.DTypeUint8, rows, cols/groupSize)
+ tensors[base+".global_scale"] = mlx.FromValues([]float32{float32(e + 1)}, 1)
+ }
+
+ got := loadStackedExperts(tensors, cfg, true, "model.layers.1", "gate_proj")
+ if got == nil {
+ t.Fatal("loadStackedExperts returned nil")
+ }
+ if got.Scales == nil || got.GlobalScales == nil {
+ t.Fatal("per-expert weights did not use the quantized global-scale path")
+ } else if dims := got.GlobalScales.Dims(); len(dims) != 1 || dims[0] != experts {
+ t.Fatalf("global scale dims = %v, want [%d]", dims, experts)
+ }
+ if dims := got.Weight.Dims(); len(dims) != 3 || dims[0] != experts {
+ t.Fatalf("weight dims = %v, want expert dimension %d", dims, experts)
+ }
+
+ delete(tensors, "model.layers.1.mlp.experts.3.gate_proj.weight.global_scale")
+ if got := loadStackedExperts(tensors, cfg, true, "model.layers.1", "gate_proj"); got != nil {
+ t.Fatal("loadStackedExperts accepted an incomplete global-scale set")
+ }
+ })
+}
diff --git a/x/models/dflash/dflash.go b/x/models/dflash/dflash.go
index 0b8f727d0..e64ebe363 100644
--- a/x/models/dflash/dflash.go
+++ b/x/models/dflash/dflash.go
@@ -456,18 +456,19 @@ func stackLinears(a, b nn.LinearLayer) (nn.LinearLayer, error) {
return out, nil
}
-// perRowGlobal expands a per-tensor (or nil, meaning 1.0) global scale to a
-// per-row vector; an already per-row scale passes through unchanged.
+// perRowGlobal expands a per-tensor global scale to a per-row vector; an
+// already per-row scale passes through unchanged. A nil scale fills with the
+// identity, which in MLX's representation is Nvfp4MaxProduct rather than 1.
func perRowGlobal(g *mlx.Array, rows int32) *mlx.Array {
- ones := make([]float32, rows)
- for i := range ones {
- ones[i] = 1
+ identity := make([]float32, rows)
+ for i := range identity {
+ identity[i] = mlx.Nvfp4MaxProduct
}
- v := mlx.FromValues(ones, int(rows))
+ v := mlx.FromValues(identity, int(rows))
if g == nil {
return v
}
- return mlx.Mul(v, g)
+ return mlx.Mul(mlx.DivScalar(v, mlx.Nvfp4MaxProduct), g)
}
func concatBias(a *mlx.Array, aRows int32, b *mlx.Array, bRows int32) *mlx.Array {
diff --git a/x/models/gemma4/gemma4.go b/x/models/gemma4/gemma4.go
index e402807dd..badaaacb3 100644
--- a/x/models/gemma4/gemma4.go
+++ b/x/models/gemma4/gemma4.go
@@ -141,12 +141,13 @@ type MLP struct {
// stackedExpertResult holds the result of collecting and stacking per-expert weights.
type stackedExpertResult struct {
- Weight *mlx.Array
- Scales *mlx.Array
- Biases *mlx.Array
- Bits int
- GroupSize int
- Mode string
+ Weight *mlx.Array
+ Scales *mlx.Array
+ Biases *mlx.Array
+ GlobalScales *mlx.Array
+ Bits int
+ GroupSize int
+ Mode string
}
// firstNonNil returns the first non-nil tensor found under any of the given keys.
@@ -197,11 +198,13 @@ func transposeForGatherMM(w *mlx.Array) *mlx.Array {
// prefix: e.g. "model.language_model.layers.0.moe.experts"
// proj: e.g. "gate_proj"
func collectExpertProjection(tensors map[string]*mlx.Array, cfg *TextConfig, prefix, proj string, numExperts int32) *stackedExpertResult {
- weights := make([]*mlx.Array, 0, numExperts)
- scales := make([]*mlx.Array, 0, numExperts)
- biases := make([]*mlx.Array, 0, numExperts)
- bits, groupSize := 0, 0
- mode := cfg.QuantMode
+ type expertPart struct {
+ weight, scales, biases *mlx.Array
+ globalScale *mlx.Array
+ groupSize, bits int
+ mode string
+ }
+ parts := make([]expertPart, 0, numExperts)
for e := range numExperts {
// Try "prefix.E.proj.weight" then "prefix.E.proj"
@@ -218,42 +221,104 @@ func collectExpertProjection(tensors map[string]*mlx.Array, cfg *TextConfig, pre
s := tensors[key+"_scale"]
if s == nil {
- weights = append(weights, w)
+ parts = append(parts, expertPart{weight: w})
continue
}
qb := tensors[key+"_qbias"]
+ globalScale, _ := model.ReadGlobalScale(tensors, key, base+".weight", base)
gs, b, m := model.ResolveLinearQuantParams(
cfg.QuantGroupSize, cfg.QuantBits, cfg.QuantMode,
cfg.TensorQuant, key, w, s,
)
- if bits == 0 {
- bits = b
- groupSize = gs
- mode = m
+ parts = append(parts, expertPart{
+ weight: w, scales: s, biases: qb,
+ globalScale: globalScale,
+ groupSize: gs, bits: b, mode: m,
+ })
+ }
+
+ if len(parts) == 0 {
+ return nil
+ }
+
+ hasBiases := parts[0].biases != nil
+ hasGlobalScales := parts[0].globalScale != nil
+ for _, part := range parts[1:] {
+ if (part.biases != nil) != hasBiases || (part.globalScale != nil) != hasGlobalScales {
+ return nil
}
- // Keep quantized weights for GatherQMM (supports affine, nvfp4, mxfp8).
- weights = append(weights, w)
- scales = append(scales, s)
- if qb != nil {
- biases = append(biases, qb)
+ }
+
+ allQuantized := parts[0].scales != nil
+ for _, part := range parts[1:] {
+ allQuantized = allQuantized && part.scales != nil &&
+ part.groupSize == parts[0].groupSize && part.bits == parts[0].bits && part.mode == parts[0].mode
+ }
+ if !allQuantized {
+ weights := make([]*mlx.Array, 0, len(parts))
+ for _, part := range parts {
+ weight := part.weight
+ if part.scales != nil {
+ weight = mlx.Dequantize(
+ part.weight, part.scales, part.biases,
+ part.groupSize, part.bits, part.mode, part.globalScale,
+ )
+ }
+ weights = append(weights, weight)
}
+ return &stackedExpertResult{Weight: mlx.Stack(weights, 0).Clone()}
}
- if len(weights) == 0 {
- return nil
+ weights := make([]*mlx.Array, 0, len(parts))
+ scales := make([]*mlx.Array, 0, len(parts))
+ biases := make([]*mlx.Array, 0, len(parts))
+ globalScales := make([]*mlx.Array, 0, len(parts))
+ for _, part := range parts {
+ weights = append(weights, part.weight)
+ scales = append(scales, part.scales)
+ if hasBiases {
+ biases = append(biases, part.biases)
+ }
+ if hasGlobalScales {
+ globalScales = append(globalScales, part.globalScale)
+ }
}
- stacked := mlx.Stack(weights, 0).Clone()
- out := &stackedExpertResult{Weight: stacked, Bits: bits, GroupSize: groupSize, Mode: mode}
- if len(scales) == len(weights) {
- out.Scales = mlx.Stack(scales, 0).Clone()
+ out := &stackedExpertResult{
+ Weight: mlx.Stack(weights, 0).Clone(),
+ Scales: mlx.Stack(scales, 0).Clone(),
+ Bits: parts[0].bits, GroupSize: parts[0].groupSize, Mode: parts[0].mode,
}
- if len(biases) == len(weights) {
+ if hasBiases {
out.Biases = mlx.Stack(biases, 0).Clone()
}
+ if hasGlobalScales {
+ out.GlobalScales = mlx.Reshape(mlx.Stack(globalScales, 0).Clone(), int32(len(parts)))
+ }
return out
}
+func collectExpertProjections(tensors map[string]*mlx.Array, cfg *TextConfig, prefixes []string, numExperts int32) (gate, up, down *stackedExpertResult) {
+ for _, prefix := range prefixes {
+ gate = collectExpertProjection(tensors, cfg, prefix, "gate_proj", numExperts)
+ up = collectExpertProjection(tensors, cfg, prefix, "up_proj", numExperts)
+ down = collectExpertProjection(tensors, cfg, prefix, "down_proj", numExperts)
+ if gate != nil || up != nil || down != nil {
+ return
+ }
+ }
+ return
+}
+
+func denseStackedExpertResult(w *stackedExpertResult) *mlx.Array {
+ if w.Scales == nil {
+ return w.Weight
+ }
+ return mlx.Dequantize(
+ w.Weight, w.Scales, w.Biases, w.GroupSize, w.Bits, w.Mode, w.GlobalScales,
+ )
+}
+
// loadFusedExperts configures an MoE block from a fused, pre-stacked gate_up
// projection and its down projection. It keeps the fused gate_up as a single
// tensor and chooses GatherQMM (one quantized call) when scale companions are
@@ -271,19 +336,29 @@ func (m *Model) loadFusedExperts(moe *MoEBlock, tensors map[string]*mlx.Array, g
return
}
+ gateUpBiases := firstNonNil(tensors, gateUpKey+"_qbias", gateUpKey+".bias")
+ downBiases := firstNonNil(tensors, downKey+"_qbias", downKey+".bias")
+ gateUpGlobalScale, _ := model.ReadGlobalScale(tensors, gateUpKey, gateUpKey+".weight")
+ downGlobalScale, _ := model.ReadGlobalScale(tensors, downKey, downKey+".weight")
+ gateUpGroupSize, gateUpBits, gateUpMode := model.ResolveLinearQuantParams(
+ m.QuantGroupSize, m.QuantBits, m.QuantMode, m.TensorQuant, gateUpKey, gateUp, gateUpScales)
+ downGroupSize, downBits, downMode := model.ResolveLinearQuantParams(
+ m.QuantGroupSize, m.QuantBits, m.QuantMode, m.TensorQuant, downKey, down, downScales)
+ gateUpGlobalScale = model.PrepareGatherQMMGlobalScale(gateUpGlobalScale, gateUp.Dim(0))
+ downGlobalScale = model.PrepareGatherQMMGlobalScale(downGlobalScale, down.Dim(0))
+
// Quantized: keep the fused gate_up packed for a single GatherQMM call.
moe.UseQuantized = true
moe.GateUpWeightQ = gateUp
moe.GateUpScales = gateUpScales
- moe.GateUpBiases = firstNonNil(tensors, gateUpKey+"_qbias", gateUpKey+".bias")
+ moe.GateUpBiases = gateUpBiases
moe.DownWeightQ = down
moe.DownScales = downScales
- moe.DownBiases = firstNonNil(tensors, downKey+"_qbias", downKey+".bias")
-
- moe.GateUpGroupSize, moe.GateUpBits, moe.QuantMode = model.ResolveLinearQuantParams(
- m.QuantGroupSize, m.QuantBits, m.QuantMode, m.TensorQuant, gateUpKey, gateUp, gateUpScales)
- moe.DownGroupSize, moe.DownBits, moe.DownQuantMode = model.ResolveLinearQuantParams(
- m.QuantGroupSize, m.QuantBits, m.QuantMode, m.TensorQuant, downKey, down, downScales)
+ moe.DownBiases = downBiases
+ moe.GateUpGlobalScales = gateUpGlobalScale
+ moe.DownGlobalScales = downGlobalScale
+ moe.GateUpGroupSize, moe.GateUpBits, moe.QuantMode = gateUpGroupSize, gateUpBits, gateUpMode
+ moe.DownGroupSize, moe.DownBits, moe.DownQuantMode = downGroupSize, downBits, downMode
}
// Router implements Gemma 4's expert routing mechanism.
@@ -307,7 +382,12 @@ type MoEBlock struct {
UpWeightQ, UpScales, UpBiases *mlx.Array
DownWeightQ, DownScales, DownBiases *mlx.Array
- PerExpertScale *mlx.Array // [num_experts]
+ GateUpGlobalScales *mlx.Array // [num_experts] (fused gate+up)
+ GateGlobalScales *mlx.Array // [num_experts] (gate)
+ UpGlobalScales *mlx.Array // [num_experts] (up)
+ DownGlobalScales *mlx.Array // [num_experts] (down)
+ PerExpertScale *mlx.Array // [num_experts] router per-expert scale
+
UseQuantized bool
UseFusedGateUp bool // true when gate+up are stored as single tensor
@@ -878,12 +958,11 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
} else {
// Per-expert tensors (from create path).
// Try separate gate_proj/up_proj first, then fused gate_up_proj.
- gateStacked := collectExpertProjection(tensors, m.TextConfig,
- layerPrefix+".moe.experts", "gate_proj", m.NumExperts)
- upStacked := collectExpertProjection(tensors, m.TextConfig,
- layerPrefix+".moe.experts", "up_proj", m.NumExperts)
- downStacked := collectExpertProjection(tensors, m.TextConfig,
- layerPrefix+".moe.experts", "down_proj", m.NumExperts)
+ gateStacked, upStacked, downStacked := collectExpertProjections(
+ tensors, m.TextConfig,
+ []string{layerPrefix + ".experts", layerPrefix + ".moe.experts"},
+ m.NumExperts,
+ )
if gateStacked == nil && upStacked == nil {
// Try fused gate_up_proj format — split along axis 1 (out-dim).
@@ -918,6 +997,8 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
gateStacked.Biases = sliceAxis1(gateUpStacked.Biases, 0, bMid)
upStacked.Biases = sliceAxis1(gateUpStacked.Biases, bMid, int32(bDims[1]))
}
+ gateStacked.GlobalScales = gateUpStacked.GlobalScales
+ upStacked.GlobalScales = gateUpStacked.GlobalScales
}
}
}
@@ -930,12 +1011,15 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
moe.GateWeightQ = gateStacked.Weight
moe.GateScales = gateStacked.Scales
moe.GateBiases = gateStacked.Biases
+ moe.GateGlobalScales = gateStacked.GlobalScales
moe.UpWeightQ = upStacked.Weight
moe.UpScales = upStacked.Scales
moe.UpBiases = upStacked.Biases
+ moe.UpGlobalScales = upStacked.GlobalScales
moe.DownWeightQ = downStacked.Weight
moe.DownScales = downStacked.Scales
moe.DownBiases = downStacked.Biases
+ moe.DownGlobalScales = downStacked.GlobalScales
moe.UseQuantized = true
moe.GateGroupSize = gateStacked.GroupSize
moe.GateBits = gateStacked.Bits
@@ -947,9 +1031,9 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
moe.DownQuantMode = downStacked.Mode
} else {
// Unquantized: transpose for GatherMM (expects [experts, in, out]).
- moe.GateWeight = transposeForGatherMM(gateStacked.Weight)
- moe.UpWeight = transposeForGatherMM(upStacked.Weight)
- moe.DownWeight = transposeForGatherMM(downStacked.Weight)
+ moe.GateWeight = transposeForGatherMM(denseStackedExpertResult(gateStacked))
+ moe.UpWeight = transposeForGatherMM(denseStackedExpertResult(upStacked))
+ moe.DownWeight = transposeForGatherMM(denseStackedExpertResult(downStacked))
}
}
layer.MoE = moe
@@ -1477,7 +1561,8 @@ func (m *MoEBlock) Forward(x *mlx.Array, scores, inds *mlx.Array, cfg *TextConfi
if m.UseFusedGateUp {
// Fused gate+up: single GatherQMM produces [B*L*topK, 1, 1, 2*intermediate]
gateUp := mlx.GatherQMM(xFlat, m.GateUpWeightQ, m.GateUpScales, m.GateUpBiases,
- nil, idxFlat, true, m.GateUpGroupSize, m.GateUpBits, m.QuantMode, doSort)
+ nil, idxFlat, true, m.GateUpGroupSize, m.GateUpBits, m.QuantMode,
+ m.GateUpGlobalScales, doSort)
// Split along last dim into gate and up
guDims := gateUp.Dims()
mid := int32(guDims[len(guDims)-1] / 2)
@@ -1490,9 +1575,9 @@ func (m *MoEBlock) Forward(x *mlx.Array, scores, inds *mlx.Array, cfg *TextConfi
hidden = mlx.GeGLU(gate, up)
} else {
gate := mlx.GatherQMM(xFlat, m.GateWeightQ, m.GateScales, m.GateBiases,
- nil, idxFlat, true, m.GateGroupSize, m.GateBits, m.QuantMode, doSort)
+ nil, idxFlat, true, m.GateGroupSize, m.GateBits, m.QuantMode, m.GateGlobalScales, doSort)
up := mlx.GatherQMM(xFlat, m.UpWeightQ, m.UpScales, m.UpBiases,
- nil, idxFlat, true, m.UpGroupSize, m.UpBits, m.QuantMode, doSort)
+ nil, idxFlat, true, m.UpGroupSize, m.UpBits, m.QuantMode, m.UpGlobalScales, doSort)
hidden = mlx.GeGLU(gate, up)
}
downMode := m.DownQuantMode
@@ -1500,7 +1585,7 @@ func (m *MoEBlock) Forward(x *mlx.Array, scores, inds *mlx.Array, cfg *TextConfi
downMode = m.QuantMode
}
down = mlx.GatherQMM(hidden, m.DownWeightQ, m.DownScales, m.DownBiases,
- nil, idxFlat, true, m.DownGroupSize, m.DownBits, downMode, doSort)
+ nil, idxFlat, true, m.DownGroupSize, m.DownBits, downMode, m.DownGlobalScales, doSort)
} else {
if m.UseFusedGateUp && m.GateUpWeight != nil {
gateUp := mlx.GatherMM(xFlat, m.GateUpWeight, nil, idxFlat, doSort)
diff --git a/x/models/gemma4/gemma4_moe_test.go b/x/models/gemma4/gemma4_moe_test.go
index 2c3adf361..2f8371d5b 100644
--- a/x/models/gemma4/gemma4_moe_test.go
+++ b/x/models/gemma4/gemma4_moe_test.go
@@ -1,6 +1,7 @@
package gemma4
import (
+ "fmt"
"testing"
"github.com/ollama/ollama/x/internal/mlxtest"
@@ -166,6 +167,36 @@ func TestLoadFusedExpertsQuantized(t *testing.T) {
}
}
+func TestLoadFusedExpertsGlobalScale(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ const experts, intermediate, hidden = 4, 32, 64
+ m := &Model{TextConfig: &TextConfig{QuantGroupSize: 16, QuantBits: 4, QuantMode: "nvfp4"}}
+ gateUpKey := "model.language_model.layers.0.experts.gate_up_proj.weight"
+ downKey := "model.language_model.layers.0.experts.down_proj.weight"
+ tensors := map[string]*mlx.Array{
+ gateUpKey: mlx.Zeros(mlx.DTypeUint32, experts, 2*intermediate, hidden/8),
+ gateUpKey + "_scale": mlx.Zeros(mlx.DTypeUint8, experts, 2*intermediate, hidden/16),
+ gateUpKey + ".global_scale": mlx.FromValues([]float32{0.5, 1, 2, 4}, experts),
+ downKey: mlx.Zeros(mlx.DTypeUint32, experts, hidden, intermediate/8),
+ downKey + "_scale": mlx.Zeros(mlx.DTypeUint8, experts, hidden, intermediate/16),
+ downKey + ".global_scale": mlx.FromValues([]float32{4, 2, 1, 0.5}, experts),
+ }
+
+ moe := &MoEBlock{}
+ m.loadFusedExperts(moe, tensors, gateUpKey, tensors[gateUpKey], downKey, tensors[downKey])
+
+ if !moe.UseQuantized || moe.GateUpGlobalScales == nil || moe.DownGlobalScales == nil {
+ t.Fatal("global-scale experts did not stay quantized")
+ }
+ if got := moe.GateUpGlobalScales.Dims(); len(got) != 1 || got[0] != experts {
+ t.Fatalf("gate_up kernel scale shape = %v, want [%d]", got, experts)
+ }
+ if got := moe.DownGlobalScales.Dims(); len(got) != 1 || got[0] != experts {
+ t.Fatalf("down kernel scale shape = %v, want [%d]", got, experts)
+ }
+ })
+}
+
// TestLoadFusedExpertsDense verifies that a fused gate_up projection with no
// scale companions is loaded onto the dense GatherMM path, kept fused.
func TestLoadFusedExpertsDense(t *testing.T) {
@@ -198,6 +229,53 @@ func TestLoadFusedExpertsDense(t *testing.T) {
})
}
+func TestCollectExpertProjectionsPrefixes(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ const experts, intermediate, hidden = 2, 16, 32
+ cfg := &TextConfig{QuantGroupSize: 16, QuantBits: 4, QuantMode: "nvfp4"}
+ prefix := "model.language_model.layers.0.experts"
+ tensors := make(map[string]*mlx.Array)
+ for expert := range experts {
+ for _, projection := range []struct {
+ name string
+ rows int
+ cols int
+ }{
+ {name: "gate_proj", rows: intermediate, cols: hidden},
+ {name: "up_proj", rows: intermediate, cols: hidden},
+ {name: "down_proj", rows: hidden, cols: intermediate},
+ } {
+ key := fmt.Sprintf("%s.%d.%s.weight", prefix, expert, projection.name)
+ tensors[key] = mlx.Zeros(mlx.DTypeUint32, projection.rows, projection.cols/8)
+ tensors[key+"_scale"] = mlx.Zeros(mlx.DTypeUint8, projection.rows, projection.cols/16)
+ }
+ }
+
+ gate, up, down := collectExpertProjections(
+ tensors, cfg,
+ []string{"model.language_model.layers.0.moe.experts", prefix},
+ experts,
+ )
+ for name, projection := range map[string]*stackedExpertResult{
+ "gate": gate,
+ "up": up,
+ "down": down,
+ } {
+ if projection == nil || projection.Scales == nil {
+ t.Fatalf("%s projection was not collected as quantized", name)
+ }
+ if got := projection.Weight.Dim(0); got != experts {
+ t.Fatalf("%s expert count = %d, want %d", name, got, experts)
+ }
+ }
+
+ tensors[prefix+".0.gate_proj.weight.global_scale"] = mlx.FromValue(float32(1))
+ if got := collectExpertProjection(tensors, cfg, prefix, "gate_proj", experts); got != nil {
+ t.Fatal("collectExpertProjection accepted an incomplete global-scale set")
+ }
+ })
+}
+
// TestRouterForwardMatchesLegacy verifies the optimized Router.Forward —
// which takes the top-k of the raw logits and softmaxes only the selected
// values — produces the same indices and (within tolerance) the same
diff --git a/x/models/glm4_moe_lite/config_test.go b/x/models/glm4_moe_lite/config_test.go
new file mode 100644
index 000000000..a8d932648
--- /dev/null
+++ b/x/models/glm4_moe_lite/config_test.go
@@ -0,0 +1,88 @@
+package glm4_moe_lite
+
+import (
+ "encoding/json"
+ "math"
+ "testing"
+
+ "github.com/ollama/ollama/x/internal/mlxtest"
+ "github.com/ollama/ollama/x/mlxrunner/mlx"
+)
+
+func TestConfigNestedRopeTheta(t *testing.T) {
+ var cfg Config
+ if err := json.Unmarshal([]byte(`{"rope_parameters":{"rope_theta":1000000}}`), &cfg); err != nil {
+ t.Fatal(err)
+ }
+ cfg.normalize()
+ if cfg.RopeTheta != 1000000 {
+ t.Fatalf("rope theta = %v, want 1000000", cfg.RopeTheta)
+ }
+}
+
+func TestSanitizeMLAWeightsGlobalScale(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ const heads, headDim, latentDim, groupSize = 2, 8, 16, 16
+ packed := make([]uint32, heads*headDim*latentDim/8)
+ for i := range packed {
+ for j := range 8 {
+ packed[i] |= uint32((i*8+j)%15+1) << (4 * j)
+ }
+ }
+ blockScales := make([]uint8, heads*headDim*latentDim/groupSize)
+ for i := range blockScales {
+ blockScales[i] = 0x38
+ }
+
+ weight := mlx.FromValues(packed, heads*headDim, latentDim/8)
+ scales := mlx.FromValues(blockScales, heads*headDim, latentDim/groupSize)
+ globalScale := mlx.FromValues([]float32{0.5}, 1)
+ cfg := &Config{
+ NumAttentionHeads: heads,
+ QKNopeHeadDim: headDim / 2,
+ VHeadDim: headDim / 2,
+ KVLoraRank: latentDim,
+ QuantGroupSize: groupSize,
+ QuantBits: 4,
+ QuantMode: "nvfp4",
+ }
+
+ gotEmbed, gotUnembed := sanitizeMLAWeights(map[string]*mlx.Array{
+ "layer.self_attn.kv_b_proj.weight": weight,
+ "layer.self_attn.kv_b_proj.weight_scale": scales,
+ "layer.self_attn.kv_b_proj.weight.global_scale": globalScale,
+ }, "layer", cfg)
+
+ unscaledEmbed, unscaledUnembed := sanitizeMLAWeights(map[string]*mlx.Array{
+ "layer.self_attn.kv_b_proj.weight": weight,
+ "layer.self_attn.kv_b_proj.weight_scale": scales,
+ }, "layer", cfg)
+ gotEmbed = gotEmbed.AsType(mlx.DTypeFloat32)
+ gotUnembed = gotUnembed.AsType(mlx.DTypeFloat32)
+ wantEmbed := mlx.MulScalar(unscaledEmbed.AsType(mlx.DTypeFloat32), 0.5)
+ wantUnembed := mlx.MulScalar(unscaledUnembed.AsType(mlx.DTypeFloat32), 0.5)
+ mlx.Eval(gotEmbed, gotUnembed, wantEmbed, wantUnembed)
+
+ for _, pair := range [][2][]float32{
+ {gotEmbed.Floats(), wantEmbed.Floats()},
+ {gotUnembed.Floats(), wantUnembed.Floats()},
+ } {
+ for i := range pair[0] {
+ if math.Abs(float64(pair[0][i]-pair[1][i])) > 1e-6 {
+ t.Fatalf("value[%d] = %v, want %v", i, pair[0][i], pair[1][i])
+ }
+ }
+ }
+ })
+}
+
+func TestConfigTopLevelRopeThetaTakesPrecedence(t *testing.T) {
+ var cfg Config
+ if err := json.Unmarshal([]byte(`{"rope_theta":10000,"rope_parameters":{"rope_theta":1000000}}`), &cfg); err != nil {
+ t.Fatal(err)
+ }
+ cfg.normalize()
+ if cfg.RopeTheta != 10000 {
+ t.Fatalf("rope theta = %v, want 10000", cfg.RopeTheta)
+ }
+}
diff --git a/x/models/glm4_moe_lite/glm4_moe_lite.go b/x/models/glm4_moe_lite/glm4_moe_lite.go
index bef8e26f5..911934675 100644
--- a/x/models/glm4_moe_lite/glm4_moe_lite.go
+++ b/x/models/glm4_moe_lite/glm4_moe_lite.go
@@ -27,19 +27,24 @@ type RopeScaling struct {
MscaleAllDim float32 `json:"mscale_all_dim"`
}
+type RopeParameters struct {
+ Theta float32 `json:"rope_theta"`
+}
+
// Config holds GLM4-MoE-Lite model configuration
type Config struct {
- HiddenSize int32 `json:"hidden_size"`
- NumHiddenLayers int32 `json:"num_hidden_layers"`
- IntermediateSize int32 `json:"intermediate_size"`
- MoEIntermediateSize int32 `json:"moe_intermediate_size"`
- NumAttentionHeads int32 `json:"num_attention_heads"`
- NumKeyValueHeads int32 `json:"num_key_value_heads"`
- VocabSize int32 `json:"vocab_size"`
- RMSNormEps float32 `json:"rms_norm_eps"`
- RopeTheta float32 `json:"rope_theta"`
- MaxPositionEmbeddings int32 `json:"max_position_embeddings"`
- AttentionBias bool `json:"attention_bias"`
+ HiddenSize int32 `json:"hidden_size"`
+ NumHiddenLayers int32 `json:"num_hidden_layers"`
+ IntermediateSize int32 `json:"intermediate_size"`
+ MoEIntermediateSize int32 `json:"moe_intermediate_size"`
+ NumAttentionHeads int32 `json:"num_attention_heads"`
+ NumKeyValueHeads int32 `json:"num_key_value_heads"`
+ VocabSize int32 `json:"vocab_size"`
+ RMSNormEps float32 `json:"rms_norm_eps"`
+ RopeTheta float32 `json:"rope_theta"`
+ RopeParameters *RopeParameters `json:"rope_parameters"`
+ MaxPositionEmbeddings int32 `json:"max_position_embeddings"`
+ AttentionBias bool `json:"attention_bias"`
// MLA (Multi-head Latent Attention) parameters
QLoraRank int32 `json:"q_lora_rank"`
@@ -72,6 +77,12 @@ type Config struct {
Scale float32 `json:"-"` // 1/sqrt(QHeadDim) with mscale adjustment
}
+func (c *Config) normalize() {
+ if c.RopeTheta == 0 && c.RopeParameters != nil {
+ c.RopeTheta = c.RopeParameters.Theta
+ }
+}
+
// MLAAttention implements Multi-head Latent Attention with absorption.
type MLAAttention struct {
QAProj nn.LinearLayer
@@ -196,9 +207,10 @@ type SwitchMLP struct {
UpWeight *mlx.Array
DownWeight *mlx.Array
- GateWeightQ, GateScales, GateBiases *mlx.Array
- UpWeightQ, UpScales, UpBiases *mlx.Array
- DownWeightQ, DownScales, DownBiases *mlx.Array
+ GateWeightQ, GateScales, GateBiases *mlx.Array
+ UpWeightQ, UpScales, UpBiases *mlx.Array
+ DownWeightQ, DownScales, DownBiases *mlx.Array
+ GateGlobalScales, UpGlobalScales, DownGlobalScales *mlx.Array
GateBits int
UpBits int
@@ -207,6 +219,9 @@ type SwitchMLP struct {
GateGroupSize int
UpGroupSize int
DownGroupSize int
+ GateMode string
+ UpMode string
+ DownMode string
UseQuantized bool
}
@@ -239,14 +254,17 @@ func (s *SwitchMLP) Forward(x *mlx.Array, indices *mlx.Array, cfg *Config) *mlx.
if s.UseQuantized {
gate = mlx.GatherQMM(xFlat, s.GateWeightQ, s.GateScales, s.GateBiases,
- nil, idxFlat, true, s.GateGroupSize, s.GateBits, cfg.QuantMode, doSort)
+ nil, idxFlat, true, s.GateGroupSize, s.GateBits, s.GateMode,
+ s.GateGlobalScales, doSort)
up = mlx.GatherQMM(xFlat, s.UpWeightQ, s.UpScales, s.UpBiases,
- nil, idxFlat, true, s.UpGroupSize, s.UpBits, cfg.QuantMode, doSort)
+ nil, idxFlat, true, s.UpGroupSize, s.UpBits, s.UpMode,
+ s.UpGlobalScales, doSort)
hidden = mlx.SwiGLU(gate, up)
down = mlx.GatherQMM(hidden, s.DownWeightQ, s.DownScales, s.DownBiases,
- nil, idxFlat, true, s.DownGroupSize, s.DownBits, cfg.QuantMode, doSort)
+ nil, idxFlat, true, s.DownGroupSize, s.DownBits, s.DownMode,
+ s.DownGlobalScales, doSort)
} else {
gate = mlx.GatherMM(xFlat, mlx.Transpose(s.GateWeight, 0, 2, 1), nil, idxFlat, doSort)
up = mlx.GatherMM(xFlat, mlx.Transpose(s.UpWeight, 0, 2, 1), nil, idxFlat, doSort)
@@ -366,19 +384,30 @@ func computeScale(cfg *Config) float32 {
// supportsGatherQMM returns true if the quantization mode has GatherQMM kernel support.
func supportsGatherQMM(mode string, bits int) bool {
- return mode == "affine" && (bits == 4 || bits == 8)
+ switch mode {
+ case "affine":
+ return bits == 4 || bits == 8
+ case "mxfp8":
+ return bits == 8
+ case "nvfp4", "mxfp4":
+ return bits == 4
+ default:
+ return false
+ }
}
// ExpertWeight holds a single expert's weight with optional quantization components.
type ExpertWeight struct {
- Weight *mlx.Array
- Scales *mlx.Array
- Biases *mlx.Array
- Bits int
- GroupSize int
+ Weight *mlx.Array
+ Scales *mlx.Array
+ Biases *mlx.Array
+ GlobalScale *mlx.Array
+ Bits int
+ GroupSize int
+ Mode string
+ SourceQuantized bool
}
-// loadExpertWeight loads an expert weight from the tensor map.
func loadExpertWeight(tensors map[string]*mlx.Array, path string, useQuantized bool, cfg *Config) *ExpertWeight {
w := tensors[path+".weight"]
if w == nil {
@@ -399,11 +428,20 @@ func loadExpertWeight(tensors map[string]*mlx.Array, path string, useQuantized b
scales,
)
+ globalScale, _ := model.ReadGlobalScale(tensors, path+".weight", path)
if useQuantized && supportsGatherQMM(mode, bits) {
- return &ExpertWeight{Weight: w, Scales: scales, Biases: qbiases, Bits: bits, GroupSize: groupSize}
+ return &ExpertWeight{
+ Weight: w, Scales: scales, Biases: qbiases,
+ GlobalScale: globalScale,
+ Bits: bits, GroupSize: groupSize, Mode: mode, SourceQuantized: true,
+ }
}
- return &ExpertWeight{Weight: mlx.Dequantize(w, scales, qbiases, groupSize, bits, mode, nil)}
+ return &ExpertWeight{
+ Weight: mlx.Dequantize(w, scales, qbiases, groupSize, bits, mode, globalScale),
+ Biases: qbiases,
+ Bits: bits, GroupSize: groupSize, Mode: mode, SourceQuantized: true,
+ }
}
return &ExpertWeight{Weight: w}
@@ -411,11 +449,13 @@ func loadExpertWeight(tensors map[string]*mlx.Array, path string, useQuantized b
// StackedExpertWeights holds stacked weights for all experts.
type StackedExpertWeights struct {
- Weight *mlx.Array
- Scales *mlx.Array
- Biases *mlx.Array
- Bits int
- GroupSize int
+ Weight *mlx.Array
+ Scales *mlx.Array
+ Biases *mlx.Array
+ GlobalScales *mlx.Array
+ Bits int
+ GroupSize int
+ Mode string
}
// loadStackedProjection loads an expert projection stored as a single stacked
@@ -433,15 +473,21 @@ func loadStackedProjection(tensors map[string]*mlx.Array, base string, useQuanti
}
qbiases := tensors[key+"_qbias"]
+ globalScale, _ := model.ReadGlobalScale(tensors, key, key+".weight")
groupSize, bits, mode := model.ResolveLinearQuantParams(
cfg.QuantGroupSize, cfg.QuantBits, cfg.QuantMode, cfg.TensorQuant,
key, w, scales,
)
+ globalScale = model.PrepareGatherQMMGlobalScale(globalScale, w.Dim(0))
if useQuantized && supportsGatherQMM(mode, bits) {
- return &StackedExpertWeights{Weight: w, Scales: scales, Biases: qbiases, Bits: bits, GroupSize: groupSize}
+ return &StackedExpertWeights{
+ Weight: w, Scales: scales, Biases: qbiases,
+ GlobalScales: globalScale,
+ Bits: bits, GroupSize: groupSize, Mode: mode,
+ }
}
- return &StackedExpertWeights{Weight: mlx.Dequantize(w, scales, qbiases, groupSize, bits, mode, nil)}
+ return &StackedExpertWeights{Weight: mlx.Dequantize(w, scales, qbiases, groupSize, bits, mode, globalScale), Mode: mode}
}
// loadStackedExperts loads a stacked expert projection by its .experts name,
@@ -462,14 +508,26 @@ func collectAndStackExpertWeights(
useQuantized bool,
cfg *Config,
) *StackedExpertWeights {
- var w, s, b []*mlx.Array
+ var w, s, b, g []*mlx.Array
var bits, groupSize int
+ var mode string
+ var quantized bool
+ var sourceQuantized bool
for e := range numExperts {
path := fmt.Sprintf("%s.mlp.experts.%d.%s", prefix, e, projName)
ew := loadExpertWeight(tensors, path, useQuantized, cfg)
if ew == nil {
- continue
+ return nil
+ }
+ if e == 0 {
+ quantized = ew.Scales != nil
+ sourceQuantized = ew.SourceQuantized
+ bits, groupSize, mode = ew.Bits, ew.GroupSize, ew.Mode
+ } else if quantized != (ew.Scales != nil) ||
+ sourceQuantized != ew.SourceQuantized ||
+ (sourceQuantized && (ew.Bits != bits || ew.GroupSize != groupSize || ew.Mode != mode)) {
+ return nil
}
w = append(w, ew.Weight)
if ew.Scales != nil {
@@ -478,25 +536,40 @@ func collectAndStackExpertWeights(
if ew.Biases != nil {
b = append(b, ew.Biases)
}
- if e == 0 {
- bits = ew.Bits
- groupSize = ew.GroupSize
+ if ew.GlobalScale != nil {
+ g = append(g, ew.GlobalScale)
}
}
- result := &StackedExpertWeights{Bits: bits, GroupSize: groupSize}
+ if (len(b) != 0 && len(b) != len(w)) ||
+ (len(g) != 0 && len(g) != len(w)) {
+ return nil
+ }
+ result := &StackedExpertWeights{Bits: bits, GroupSize: groupSize, Mode: mode}
if len(w) > 0 {
result.Weight = mlx.Stack(w, 0)
- if len(s) > 0 {
+ if quantized {
result.Scales = mlx.Stack(s, 0)
}
- if len(b) > 0 {
+ if quantized && len(b) == len(w) {
result.Biases = mlx.Stack(b, 0)
}
+ if quantized && len(g) == len(w) {
+ result.GlobalScales = mlx.Reshape(mlx.Stack(g, 0), int32(len(w)))
+ }
}
return result
}
+func denseStackedExpertWeight(w *StackedExpertWeights) *mlx.Array {
+ if w.Scales == nil {
+ return w.Weight
+ }
+ return mlx.Dequantize(
+ w.Weight, w.Scales, w.Biases, w.GroupSize, w.Bits, w.Mode, w.GlobalScales,
+ )
+}
+
// sanitizeExpertWeights resolves the three MoE projections, preferring the
// stacked on-disk layout and falling back to per-expert tensors.
func sanitizeExpertWeights(tensors map[string]*mlx.Array, prefix string, numExperts int32, useQuantized bool, cfg *Config) (gate, up, down *StackedExpertWeights) {
@@ -523,6 +596,7 @@ func sanitizeMLAWeights(tensors map[string]*mlx.Array, prefix string, cfg *Confi
// Check if quantized and dequantize
if scales := tensors[path+".weight_scale"]; scales != nil {
qbiases := tensors[path+".weight_qbias"]
+ globalScale, _ := model.ReadGlobalScale(tensors, path+".weight")
groupSize, bits, mode := model.ResolveLinearQuantParams(
cfg.QuantGroupSize,
cfg.QuantBits,
@@ -532,7 +606,7 @@ func sanitizeMLAWeights(tensors map[string]*mlx.Array, prefix string, cfg *Confi
w,
scales,
)
- w = mlx.Dequantize(w, scales, qbiases, groupSize, bits, mode, nil)
+ w = mlx.Dequantize(w, scales, qbiases, groupSize, bits, mode, globalScale)
}
headDim := cfg.QKNopeHeadDim + cfg.VHeadDim
@@ -559,6 +633,7 @@ func newModel(root *model.Root) (base.Model, error) {
if err := json.Unmarshal(configData, &cfg); err != nil {
return nil, fmt.Errorf("parse config: %w", err)
}
+ cfg.normalize()
cfg.QHeadDim = cfg.QKNopeHeadDim + cfg.QKRopeHeadDim
cfg.Scale = computeScale(&cfg)
@@ -691,28 +766,38 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
// Stack expert weights
gate, up, down := sanitizeExpertWeights(tensors, prefix, cfg.NRoutedExperts, useQuantized, cfg)
+ if gate == nil || up == nil || down == nil {
+ return fmt.Errorf("layer %d: missing or inconsistent expert weights", i)
+ }
- switchMLP := &SwitchMLP{UseQuantized: useQuantized}
- if useQuantized {
+ useQuantizedLayer := gate.Scales != nil && up.Scales != nil && down.Scales != nil
+ switchMLP := &SwitchMLP{UseQuantized: useQuantizedLayer}
+ if useQuantizedLayer {
switchMLP.GateWeightQ = gate.Weight
switchMLP.GateScales = gate.Scales
switchMLP.GateBiases = gate.Biases
+ switchMLP.GateGlobalScales = gate.GlobalScales
switchMLP.GateBits = gate.Bits
switchMLP.GateGroupSize = gate.GroupSize
+ switchMLP.GateMode = gate.Mode
switchMLP.UpWeightQ = up.Weight
switchMLP.UpScales = up.Scales
switchMLP.UpBiases = up.Biases
+ switchMLP.UpGlobalScales = up.GlobalScales
switchMLP.UpBits = up.Bits
switchMLP.UpGroupSize = up.GroupSize
+ switchMLP.UpMode = up.Mode
switchMLP.DownWeightQ = down.Weight
switchMLP.DownScales = down.Scales
switchMLP.DownBiases = down.Biases
+ switchMLP.DownGlobalScales = down.GlobalScales
switchMLP.DownBits = down.Bits
switchMLP.DownGroupSize = down.GroupSize
+ switchMLP.DownMode = down.Mode
} else {
- switchMLP.GateWeight = gate.Weight
- switchMLP.UpWeight = up.Weight
- switchMLP.DownWeight = down.Weight
+ switchMLP.GateWeight = denseStackedExpertWeight(gate)
+ switchMLP.UpWeight = denseStackedExpertWeight(up)
+ switchMLP.DownWeight = denseStackedExpertWeight(down)
}
moeGate := &MoEGate{}
diff --git a/x/models/laguna/laguna.go b/x/models/laguna/laguna.go
index fd000e5f8..202df40c4 100644
--- a/x/models/laguna/laguna.go
+++ b/x/models/laguna/laguna.go
@@ -154,6 +154,7 @@ type SwitchMLP struct {
GateWeightQ, GateScales, GateBiases *mlx.Array
UpWeightQ, UpScales, UpBiases *mlx.Array
DownWeightQ, DownScales, DownBiases *mlx.Array
+ GateUpGlobalScale *mlx.Array
GateGlobalScale, UpGlobalScale *mlx.Array
DownGlobalScale *mlx.Array
@@ -613,17 +614,10 @@ func denseExpertWeight(w *stackedExpertWeights) *mlx.Array {
}
weight := w.Weight
if w.Scales != nil {
- weight = mlx.Dequantize(w.Weight, w.Scales, w.Biases, w.GroupSize, w.Bits, w.Mode, nil)
- if w.GlobalScales != nil {
- scale := w.GlobalScales
- if scale.DType() != weight.DType() {
- scale = scale.AsType(weight.DType())
- }
- if !(scale.NumDims() == 0 || (scale.NumDims() == 1 && scale.Dim(0) == 1)) {
- scale = mlx.ExpandDims(mlx.ExpandDims(scale, -1), -1)
- }
- weight = mlx.Mul(weight, scale)
- }
+ weight = mlx.Dequantize(
+ w.Weight, w.Scales, w.Biases,
+ w.GroupSize, w.Bits, w.Mode, w.GlobalScales,
+ )
}
return weight
}
@@ -653,7 +647,9 @@ func canFuseQuantizedGateUp(gateW, upW *stackedExpertWeights) bool {
if gateW == nil || upW == nil || gateW.Scales == nil || upW.Scales == nil {
return false
}
- if gateW.GlobalScales != nil || upW.GlobalScales != nil {
+ // One scale per expert covers the whole bank row, so gate and up can share
+ // a fused bank when their scales agree.
+ if !model.SameGlobalScales(gateW.GlobalScales, upW.GlobalScales) {
return false
}
if gateW.Bits != upW.Bits || gateW.GroupSize != upW.GroupSize || gateW.Mode != upW.Mode {
@@ -691,10 +687,7 @@ func canFuseDenseQuantizedLinears(a, b *nn.QuantizedLinear) bool {
}
func isScalarGlobalScale(scale *mlx.Array) bool {
- if scale == nil {
- return true
- }
- return scale.NumDims() == 0 || (scale.NumDims() == 1 && scale.Dim(0) == 1)
+ return scale == nil || scale.Size() == 1
}
func fuseDenseQuantizedLinears(a, b nn.LinearLayer) nn.LinearLayer {
@@ -736,7 +729,7 @@ func applyDenseGlobalScale(x, globalScale *mlx.Array) *mlx.Array {
if globalScale == nil {
return x
}
- return mlx.Mul(x, globalScale).AsType(x.DType())
+ return mlx.Mul(x, mlx.DivScalar(globalScale, mlx.Nvfp4MaxProduct)).AsType(x.DType())
}
func splitLastDim(x *mlx.Array, first int32) (*mlx.Array, *mlx.Array) {
@@ -761,26 +754,7 @@ func fuseExpertStacks(a, b *mlx.Array, axis int) *mlx.Array {
return mlx.Concatenate([]*mlx.Array{a, b}, axis).Clone()
}
-func applyExpertGlobalScale(x, globalScale, idx *mlx.Array) *mlx.Array {
- if globalScale == nil {
- return x
- }
- if globalScale.NumDims() == 0 || (globalScale.NumDims() == 1 && globalScale.Dim(0) == 1) {
- return mlx.Mul(x, globalScale).AsType(x.DType())
- }
- scale := mlx.ExpandDims(mlx.ExpandDims(mlx.Take(globalScale, idx, 0), -1), -1)
- return mlx.Mul(x, scale).AsType(x.DType())
-}
-
-var lagunaSwiGLUGatheredGateScale = mlx.Compile(
- "LagunaSwiGLUGatheredGateScale",
- func(in ...*mlx.Array) []*mlx.Array {
- gate := applyExpertGlobalScale(in[0], in[2], in[3])
- return []*mlx.Array{mlx.SwiGLU(gate, in[1])}
- },
-)
-
-func newLagunaSigmoidTopKRouter(name string, normalize, scaleScores bool) mlx.CompileFunc {
+func newLagunaSigmoidTopKRouter(name string, normalize bool) mlx.CompileFunc {
return mlx.Compile(name, func(in ...*mlx.Array) []*mlx.Array {
gates, bias := in[0].AsType(mlx.DTypeFloat32), in[1]
probs, neg := mlx.SigmoidRouter(gates, bias)
@@ -790,23 +764,15 @@ func newLagunaSigmoidTopKRouter(name string, normalize, scaleScores bool) mlx.Co
if normalize {
scores = mlx.Div(scores, mlx.Sum(scores, -1, true))
}
- if scaleScores {
- scores = scaleScoresByExpert(scores, inds, in[2])
- scores = scaleScoresByExpert(scores, inds, in[3])
- }
return []*mlx.Array{scores, inds}
})
}
var (
lagunaSigmoidTopK8 = newLagunaSigmoidTopKRouter(
- "LagunaSigmoidTopK8", false, false)
+ "LagunaSigmoidTopK8", false)
lagunaSigmoidTopK8Normalized = newLagunaSigmoidTopKRouter(
- "LagunaSigmoidTopK8Normalized", true, false)
- lagunaSigmoidTopK8Scaled = newLagunaSigmoidTopKRouter(
- "LagunaSigmoidTopK8Scaled", false, true)
- lagunaSigmoidTopK8ScaledNormalized = newLagunaSigmoidTopKRouter(
- "LagunaSigmoidTopK8ScaledNormalized", true, true)
+ "LagunaSigmoidTopK8Normalized", true)
)
func lagunaWeightedSum(expert, scores, scale *mlx.Array) *mlx.Array {
@@ -833,23 +799,7 @@ var (
)
func combinedTensorGlobalScale(tensors map[string]*mlx.Array, key string) (*mlx.Array, []string) {
- var names []string
- weightGlobal := tensors[key+".global_scale"]
- if weightGlobal == nil {
- weightGlobal = tensors[key+".weight.global_scale"]
- }
- if weightGlobal != nil {
- names = append(names, key+".global_scale", key+".weight.global_scale")
- }
- if tensors[key+".input_global_scale"] != nil || tensors[key+".weight.input_global_scale"] != nil {
- names = append(names, key+".input_global_scale", key+".weight.input_global_scale")
- }
- switch {
- case weightGlobal != nil:
- return weightGlobal, names
- default:
- return nil, nil
- }
+ return model.ReadGlobalScale(tensors, key, key+".weight")
}
func collectPerExpertProjection(tensors map[string]*mlx.Array, cfg *Config, useQuantized bool, layerPrefix, proj string, numExperts int32) *stackedExpertWeights {
@@ -861,6 +811,8 @@ func collectPerExpertProjection(tensors map[string]*mlx.Array, cfg *Config, useQ
bits := 0
groupSize := 0
mode := cfg.QuantMode
+ quantized := false
+ sourceQuantized := false
for e := range numExperts {
base := fmt.Sprintf("%s.mlp.experts.%d.%s", layerPrefix, e, proj)
@@ -874,9 +826,19 @@ func collectPerExpertProjection(tensors map[string]*mlx.Array, cfg *Config, useQ
s = tensors[key+".scale"]
}
if s == nil {
+ if e == 0 {
+ sourceQuantized = false
+ } else if sourceQuantized {
+ return nil
+ }
weights = append(weights, w)
continue
}
+ if e == 0 {
+ sourceQuantized = true
+ } else if !sourceQuantized {
+ return nil
+ }
consumedKeys = append(consumedKeys, key+"_scale", key+".scale")
qb := tensors[key+"_qbias"]
if qb == nil {
@@ -895,34 +857,41 @@ func collectPerExpertProjection(tensors map[string]*mlx.Array, cfg *Config, useQ
groupSize = gs
mode = m
}
- if useQuantized && supportsGatherQMM(m, b) {
+ keepQuantized := useQuantized && supportsGatherQMM(m, b)
+ if e == 0 {
+ quantized = keepQuantized
+ } else if quantized != keepQuantized ||
+ (sourceQuantized && (b != bits || gs != groupSize || m != mode)) {
+ return nil
+ }
+ if qb != nil {
+ biases = append(biases, qb)
+ }
+ if keepQuantized {
weights = append(weights, w)
scales = append(scales, s)
if globalScale != nil {
globalScales = append(globalScales, globalScale)
}
- if qb != nil {
- biases = append(biases, qb)
- }
} else {
- deq := mlx.Dequantize(w, s, qb, gs, b, m, nil)
- if globalScale != nil {
- deq = mlx.Mul(deq, globalScale)
- globalScales = append(globalScales, globalScale)
- }
+ deq := mlx.Dequantize(w, s, qb, gs, b, m, globalScale)
weights = append(weights, deq)
}
}
+ if (len(biases) != 0 && len(biases) != len(weights)) ||
+ (len(globalScales) != 0 && len(globalScales) != len(weights)) {
+ return nil
+ }
out := &stackedExpertWeights{Weight: stackAndClone(weights), Bits: bits, GroupSize: groupSize, Mode: mode}
if len(scales) == len(weights) {
out.Scales = stackAndClone(scales)
}
- if len(biases) == len(weights) {
+ if quantized && len(biases) == len(weights) {
out.Biases = stackAndClone(biases)
}
if len(globalScales) == len(weights) {
- out.GlobalScales = stackAndClone(globalScales)
+ out.GlobalScales = mlx.Reshape(stackAndClone(globalScales), int32(len(weights)))
}
freeTensorKeys(tensors, consumedKeys...)
return out
@@ -962,16 +931,18 @@ func loadStackedProjection(tensors map[string]*mlx.Array, cfg *Config, useQuanti
globalScale, globalScaleKeys := combinedTensorGlobalScale(tensors, key)
consumedKeys = append(consumedKeys, globalScaleKeys...)
gs, b, m := model.ResolveLinearQuantParams(cfg.QuantGroupSize, cfg.QuantBits, cfg.QuantMode, cfg.TensorQuant, key, w, s)
+ globalScale = model.PrepareGatherQMMGlobalScale(globalScale, w.Dim(0))
if useQuantized && supportsGatherQMM(m, b) {
freeTensorKeys(tensors, consumedKeys...)
- return &stackedExpertWeights{Weight: w, Scales: s, Biases: qb, GlobalScales: globalScale, Bits: b, GroupSize: gs, Mode: m}
- }
- deq := mlx.Dequantize(w, s, qb, gs, b, m, nil)
- if globalScale != nil {
- deq = mlx.Mul(deq, globalScale)
+ return &stackedExpertWeights{
+ Weight: w, Scales: s, Biases: qb,
+ GlobalScales: globalScale,
+ Bits: b, GroupSize: gs, Mode: m,
+ }
}
+ deq := mlx.Dequantize(w, s, qb, gs, b, m, globalScale)
freeTensorKeys(tensors, consumedKeys...)
- return &stackedExpertWeights{Weight: deq, GlobalScales: globalScale, Bits: b, GroupSize: gs, Mode: m}
+ return &stackedExpertWeights{Weight: deq, Bits: b, GroupSize: gs, Mode: m}
}
return nil
}
@@ -1092,6 +1063,7 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
sw.GateUpWeightQ = fuseExpertStacks(gateW.Weight, upW.Weight, 1)
sw.GateUpScales = fuseExpertStacks(gateW.Scales, upW.Scales, 1)
sw.GateUpBiases = fuseExpertStacks(gateW.Biases, upW.Biases, 1)
+ sw.GateUpGlobalScale = gateW.GlobalScales
sw.GateUpBits, sw.GateUpGroupSize, sw.GateUpMode = gateW.Bits, gateW.GroupSize, gateW.Mode
} else {
sw.GateWeightQ, sw.GateScales, sw.GateBiases = gateW.Weight, gateW.Scales, gateW.Biases
@@ -1242,20 +1214,18 @@ func (s *SwitchMLP) Forward(x *mlx.Array, indices *mlx.Array, cfg *Config) *mlx.
var gate, up, hidden *mlx.Array
switch {
case s.GateUpWeightQ != nil:
- gateUp := mlx.GatherQMM(xFlat, s.GateUpWeightQ, s.GateUpScales, s.GateUpBiases, nil, idxFlat, true, s.GateUpGroupSize, s.GateUpBits, s.GateUpMode, doSort)
+ gateUp := mlx.GatherQMM(xFlat, s.GateUpWeightQ, s.GateUpScales, s.GateUpBiases, nil, idxFlat, true, s.GateUpGroupSize, s.GateUpBits, s.GateUpMode, s.GateUpGlobalScale, doSort)
guDims := gateUp.Dims()
mid := int32(guDims[len(guDims)-1] / 2)
gate = mlx.SliceStartStop(gateUp, []int32{0, 0, 0, 0}, []int32{int32(guDims[0]), int32(guDims[1]), int32(guDims[2]), mid})
up = mlx.SliceStartStop(gateUp, []int32{0, 0, 0, mid}, []int32{int32(guDims[0]), int32(guDims[1]), int32(guDims[2]), int32(guDims[len(guDims)-1])})
hidden = mlx.SwiGLU(gate, up)
case s.GateWeightQ != nil && s.UpWeightQ != nil:
- gate = mlx.GatherQMM(xFlat, s.GateWeightQ, s.GateScales, s.GateBiases, nil, idxFlat, true, s.GateGroupSize, s.GateBits, s.GateMode, doSort)
- up = mlx.GatherQMM(xFlat, s.UpWeightQ, s.UpScales, s.UpBiases, nil, idxFlat, true, s.UpGroupSize, s.UpBits, s.UpMode, doSort)
- if s.GateGlobalScale != nil {
- hidden = lagunaSwiGLUGatheredGateScale(gate, up, s.GateGlobalScale, idxFlat)[0]
- } else {
- hidden = mlx.SwiGLU(gate, up)
- }
+ gate = mlx.GatherQMM(xFlat, s.GateWeightQ, s.GateScales, s.GateBiases, nil, idxFlat, true, s.GateGroupSize, s.GateBits, s.GateMode,
+ s.GateGlobalScale, doSort)
+ up = mlx.GatherQMM(xFlat, s.UpWeightQ, s.UpScales, s.UpBiases, nil, idxFlat, true, s.UpGroupSize, s.UpBits, s.UpMode,
+ s.UpGlobalScale, doSort)
+ hidden = mlx.SwiGLU(gate, up)
case s.GateUpWeight != nil:
gateUp := mlx.GatherMM(xFlat, s.GateUpWeight, nil, idxFlat, doSort)
guDims := gateUp.Dims()
@@ -1271,7 +1241,8 @@ func (s *SwitchMLP) Forward(x *mlx.Array, indices *mlx.Array, cfg *Config) *mlx.
var down *mlx.Array
if s.DownWeightQ != nil {
- down = mlx.GatherQMM(hidden, s.DownWeightQ, s.DownScales, s.DownBiases, nil, idxFlat, true, s.DownGroupSize, s.DownBits, s.DownMode, doSort)
+ down = mlx.GatherQMM(hidden, s.DownWeightQ, s.DownScales, s.DownBiases, nil, idxFlat, true, s.DownGroupSize, s.DownBits, s.DownMode,
+ s.DownGlobalScale, doSort)
} else {
down = mlx.GatherMM(hidden, weightForGatherMM(s.DownWeight, s.DownWeightSourceLayout), nil, idxFlat, doSort)
}
@@ -1283,39 +1254,17 @@ func (s *SwitchMLP) Forward(x *mlx.Array, indices *mlx.Array, cfg *Config) *mlx.
return mlx.Reshape(down, B, L, topK, cfg.HiddenSize)
}
-func scaleScoresByExpert(scores, inds, globalScale *mlx.Array) *mlx.Array {
- if globalScale == nil {
- return scores
- }
- scale := globalScale
- if scale.DType() != scores.DType() {
- scale = scale.AsType(scores.DType())
- }
- if scale.NumDims() == 0 || (scale.NumDims() == 1 && scale.Dim(0) == 1) {
- return mlx.Mul(scores, scale)
- }
- return mlx.Mul(scores, mlx.Take(scale, inds, 0))
-}
-
-func (m *SparseMoE) route(xFlat *mlx.Array, cfg *Config) (scores, inds *mlx.Array, scalesFolded bool) {
+func (m *SparseMoE) route(xFlat *mlx.Array, cfg *Config) (scores, inds *mlx.Array) {
gates := m.Gate.Forward(xFlat)
var probs, neg *mlx.Array
if m.EScoreCorrectionBias != nil && cfg.NumExpertsPerTok == 8 {
normalize := cfg.NormTopKProb
- if m.SwitchMLP != nil && m.SwitchMLP.UpGlobalScale != nil && m.SwitchMLP.DownGlobalScale != nil {
- fn := lagunaSigmoidTopK8Scaled
- if normalize {
- fn = lagunaSigmoidTopK8ScaledNormalized
- }
- out := fn(gates, m.EScoreCorrectionBias, m.SwitchMLP.UpGlobalScale, m.SwitchMLP.DownGlobalScale)
- return out[0], out[1], true
- }
fn := lagunaSigmoidTopK8
if normalize {
fn = lagunaSigmoidTopK8Normalized
}
out := fn(gates, m.EScoreCorrectionBias)
- return out[0], out[1], false
+ return out[0], out[1]
}
if m.EScoreCorrectionBias != nil {
gates = gates.AsType(mlx.DTypeFloat32)
@@ -1331,7 +1280,7 @@ func (m *SparseMoE) route(xFlat *mlx.Array, cfg *Config) (scores, inds *mlx.Arra
if cfg.NormTopKProb && cfg.NumExpertsPerTok > 1 {
scores = mlx.Div(scores, mlx.Sum(scores, -1, true))
}
- return scores, inds, false
+ return scores, inds
}
func (m *SparseMoE) Forward(x *mlx.Array, cfg *Config) *mlx.Array {
@@ -1349,11 +1298,7 @@ func (m *SparseMoE) forward(x, residual *mlx.Array, cfg *Config) *mlx.Array {
shared := m.SharedExpert.Forward(x, cfg)
xFlat := mlx.Reshape(x, BL, cfg.HiddenSize)
- scores, inds, scalesFolded := m.route(xFlat, cfg)
- if !scalesFolded {
- scores = scaleScoresByExpert(scores, inds, m.SwitchMLP.UpGlobalScale)
- scores = scaleScoresByExpert(scores, inds, m.SwitchMLP.DownGlobalScale)
- }
+ scores, inds := m.route(xFlat, cfg)
expertOut := m.SwitchMLP.Forward(x, inds, cfg)
scoreDims := mlx.Reshape(scores, B, L, cfg.NumExpertsPerTok)
diff --git a/x/models/laguna/laguna_test.go b/x/models/laguna/laguna_test.go
index 4310a1430..02c727300 100644
--- a/x/models/laguna/laguna_test.go
+++ b/x/models/laguna/laguna_test.go
@@ -2,13 +2,13 @@ package laguna
import (
"math"
- "slices"
"strings"
"testing"
"github.com/ollama/ollama/x/internal/mlxtest"
"github.com/ollama/ollama/x/mlxrunner/batch"
"github.com/ollama/ollama/x/mlxrunner/mlx"
+ "github.com/ollama/ollama/x/mlxrunner/model"
"github.com/ollama/ollama/x/models/nn"
)
@@ -482,10 +482,7 @@ func TestSparseMoERouteBiasAffectsSelectionNotRoutingWeights(t *testing.T) {
}
xFlat := mlx.FromValues([]float32{1}, 1, int(cfg.HiddenSize)).AsType(mlx.DTypeBFloat16)
- scores, inds, scalesFolded := moe.route(xFlat, cfg)
- if scalesFolded {
- t.Fatal("route folded scales without expert projection scales")
- }
+ scores, inds := moe.route(xFlat, cfg)
scores = scores.AsType(mlx.DTypeFloat32)
inds = inds.AsType(mlx.DTypeInt32)
mlx.Eval(scores, inds)
@@ -509,76 +506,6 @@ func TestSparseMoERouteBiasAffectsSelectionNotRoutingWeights(t *testing.T) {
})
}
-func TestLagunaSigmoidTopK8CompiledMatchesEager(t *testing.T) {
- mlxtest.Run(t, func(t *mlxtest.T) {
- gates := make([]float32, 2*16)
- for i := range gates {
- gates[i] = float32((i%13)-6) * 0.2
- }
- bias := make([]float32, 16)
- scaleA := make([]float32, 16)
- scaleB := make([]float32, 16)
- for i := range bias {
- bias[i] = float32((i%5)-2) * 0.03
- scaleA[i] = 0.5 + float32(i)*0.01
- scaleB[i] = 0.75 + float32(i)*0.005
- }
-
- gatesArray := mlx.FromValues(gates, 2, 16).AsType(mlx.DTypeBFloat16)
- biasArray := mlx.FromValues(bias, 16)
- scaleAArray := mlx.FromValues(scaleA, 16)
- scaleBArray := mlx.FromValues(scaleB, 16)
- got := lagunaSigmoidTopK8ScaledNormalized(gatesArray, biasArray, scaleAArray, scaleBArray)
-
- probs, neg := mlx.SigmoidRouter(gatesArray.AsType(mlx.DTypeFloat32), biasArray)
- wantIndices := mlx.Argpartition(neg, 7, -1)
- wantIndices = mlx.SliceStartStop(wantIndices, []int32{0, 0}, []int32{2, 8})
- wantScores := mlx.TakeAlongAxis(probs, wantIndices, -1)
- wantScores = mlx.Div(wantScores, mlx.Sum(wantScores, -1, true))
- wantScores = scaleScoresByExpert(wantScores, wantIndices, scaleAArray)
- wantScores = scaleScoresByExpert(wantScores, wantIndices, scaleBArray)
-
- gotScores := got[0].AsType(mlx.DTypeFloat32)
- gotIndices := got[1].AsType(mlx.DTypeInt32)
- wantScores = wantScores.AsType(mlx.DTypeFloat32)
- wantIndices = wantIndices.AsType(mlx.DTypeInt32)
- mlx.Eval(gotScores, gotIndices, wantScores, wantIndices)
- assertFloatSlicesClose(t, gotScores.Floats(), wantScores.Floats(), 1e-6)
- if got, want := gotIndices.Ints(), wantIndices.Ints(); !slices.Equal(got, want) {
- t.Fatalf("indices = %v, want %v", got, want)
- }
- })
-}
-
-func TestLagunaSwiGLUGatheredGateScaleCompiledMatchesEager(t *testing.T) {
- mlxtest.Run(t, func(t *mlxtest.T) {
- gateValues := make([]float32, 2*8*4)
- upValues := make([]float32, len(gateValues))
- for i := range gateValues {
- gateValues[i] = float32((i%17)-8) * 0.04
- upValues[i] = float32((i%11)-5) * 0.03
- }
- scaleValues := make([]float32, 16)
- for i := range scaleValues {
- scaleValues[i] = 0.5 + float32(i)*0.025
- }
- indices := mlx.FromValues([]int32{
- 0, 3, 6, 9, 12, 15, 2, 5,
- 1, 4, 7, 10, 13, 14, 8, 11,
- }, 2, 8)
- gate := mlx.FromValues(gateValues, 2, 8, 1, 4).AsType(mlx.DTypeBFloat16)
- up := mlx.FromValues(upValues, 2, 8, 1, 4).AsType(mlx.DTypeBFloat16)
- scales := mlx.FromValues(scaleValues, 16)
-
- got := lagunaSwiGLUGatheredGateScale(gate, up, scales, indices)[0]
- want := mlx.SwiGLU(applyExpertGlobalScale(gate, scales, indices), up)
- got = got.AsType(mlx.DTypeFloat32)
- want = want.AsType(mlx.DTypeFloat32)
- mlx.Eval(got, want)
- assertFloatSlicesClose(t, got.Floats(), want.Floats(), 1e-6)
- })
-}
-
func TestLagunaMoEWeightedSumCompiledMatchesEager(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
expertValues := make([]float32, 1*2*8*4)
@@ -690,6 +617,67 @@ func TestSwitchMLPMixedQuantizedGateUpDenseDownMatchesDense(t *testing.T) {
})
}
+// Routed gate and up fuse into one nvfp4 bank only when their per-expert
+// global scales agree. gather_qmm applies one scale per expert across the
+// whole bank row, so the fused bank carries that scale and has to match
+// running the two projections separately.
+func TestSwitchMLPFusedGateUpGlobalScaleMatchesSeparate(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ if !mlx.MetalIsAvailable() && !mlx.CUDAIsAvailable() {
+ t.Skip("gather_qmm global scales require a GPU backend")
+ }
+ cfg := &Config{HiddenSize: 32, NumExpertsPerTok: 2}
+ x := makePatternExpertWeight(1, 2, int(cfg.HiddenSize), 0.013)
+ indices := mlx.FromValues([]int32{0, 1, 1, 0}, 2, int(cfg.NumExpertsPerTok))
+
+ gateWeight := makePatternExpertWeight(2, 32, 32, 0.011)
+ upWeight := makePatternExpertWeight(2, 32, 32, 0.017)
+ downWeight := makePatternExpertWeight(2, 32, 32, 0.013)
+ gateQ, gateScales, _ := mlx.Quantize(gateWeight, 16, 4, "nvfp4")
+ upQ, upScales, _ := mlx.Quantize(upWeight, 16, 4, "nvfp4")
+ mlx.Eval(gateQ, gateScales, upQ, upScales)
+
+ shared := model.PrepareGatherQMMGlobalScale(mlx.FromValues([]float32{0.5, 2}, 2), 2)
+ differing := model.PrepareGatherQMMGlobalScale(mlx.FromValues([]float32{2, 0.5}, 2), 2)
+
+ gateW := &stackedExpertWeights{
+ Weight: gateQ, Scales: gateScales, GlobalScales: shared,
+ Bits: 4, GroupSize: 16, Mode: "nvfp4",
+ }
+ upW := &stackedExpertWeights{
+ Weight: upQ, Scales: upScales, GlobalScales: shared,
+ Bits: 4, GroupSize: 16, Mode: "nvfp4",
+ }
+ if !canFuseQuantizedGateUp(gateW, upW) {
+ t.Fatal("gate and up sharing a global scale did not fuse")
+ }
+ upW.GlobalScales = differing
+ if canFuseQuantizedGateUp(gateW, upW) {
+ t.Fatal("gate and up with differing global scales fused")
+ }
+
+ fused := &SwitchMLP{
+ GateUpWeightQ: fuseExpertStacks(gateQ, upQ, 1),
+ GateUpScales: fuseExpertStacks(gateScales, upScales, 1),
+ GateUpGlobalScale: shared,
+ GateUpBits: 4, GateUpGroupSize: 16, GateUpMode: "nvfp4",
+ DownWeight: downWeight, DownWeightSourceLayout: true,
+ }
+ separate := &SwitchMLP{
+ GateWeightQ: gateQ, GateScales: gateScales, GateGlobalScale: shared,
+ GateBits: 4, GateGroupSize: 16, GateMode: "nvfp4",
+ UpWeightQ: upQ, UpScales: upScales, UpGlobalScale: shared,
+ UpBits: 4, UpGroupSize: 16, UpMode: "nvfp4",
+ DownWeight: downWeight, DownWeightSourceLayout: true,
+ }
+
+ got := fused.Forward(x, indices, cfg).AsType(mlx.DTypeFloat32)
+ want := separate.Forward(x, indices, cfg).AsType(mlx.DTypeFloat32)
+ mlx.Eval(got, want)
+ assertFloatSlicesClose(t, got.Floats(), want.Floats(), 1e-4)
+ })
+}
+
func TestDenseExpertWeightForGatherMMDequantizesQuantizedWeight(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
weight := makePatternExpertWeight(2, 4, 32, 0.011)
@@ -730,9 +718,10 @@ func TestCombinedTensorGlobalScaleIgnoresInputGlobalScale(t *testing.T) {
t.Fatal("combinedTensorGlobalScale returned nil")
}
mlx.Eval(got)
+ // The reader converts to MLX's representation on the way out.
vals := got.Floats()
- if len(vals) != 1 || vals[0] != 0.25 {
- t.Fatalf("combinedTensorGlobalScale = %v, want [0.25]", vals)
+ if want := float32(0.25 * mlx.Nvfp4MaxProduct); len(vals) != 1 || vals[0] != want {
+ t.Fatalf("combinedTensorGlobalScale = %v, want [%v]", vals, want)
}
})
}
diff --git a/x/models/nemotron_h/nemotron_h.go b/x/models/nemotron_h/nemotron_h.go
index 51584ed8b..a64efe8e0 100644
--- a/x/models/nemotron_h/nemotron_h.go
+++ b/x/models/nemotron_h/nemotron_h.go
@@ -31,22 +31,23 @@ var (
)
type Config struct {
- ModelType string `json:"model_type"`
- VocabSize int32 `json:"vocab_size"`
- HiddenSize int32 `json:"hidden_size"`
- IntermediateSize int32 `json:"intermediate_size"`
- NumHiddenLayers int32 `json:"num_hidden_layers"`
- HybridOverridePattern string `json:"hybrid_override_pattern"`
- NumAttentionHeads int32 `json:"num_attention_heads"`
- NumKeyValueHeads int32 `json:"num_key_value_heads"`
- HeadDim int32 `json:"head_dim"`
- LayerNormEpsilon float32 `json:"layer_norm_epsilon"`
- RMSNormEps float32 `json:"rms_norm_eps"`
- TieWordEmbeddings bool `json:"tie_word_embeddings"`
- MaxPositionEmbeddings int32 `json:"max_position_embeddings"`
- AttentionBias bool `json:"attention_bias"`
- MLPBias bool `json:"mlp_bias"`
- UseBias bool `json:"use_bias"`
+ ModelType string `json:"model_type"`
+ VocabSize int32 `json:"vocab_size"`
+ HiddenSize int32 `json:"hidden_size"`
+ IntermediateSize int32 `json:"intermediate_size"`
+ NumHiddenLayers int32 `json:"num_hidden_layers"`
+ HybridOverridePattern string `json:"hybrid_override_pattern"`
+ LayersBlockType []string `json:"layers_block_type"`
+ NumAttentionHeads int32 `json:"num_attention_heads"`
+ NumKeyValueHeads int32 `json:"num_key_value_heads"`
+ HeadDim int32 `json:"head_dim"`
+ LayerNormEpsilon float32 `json:"layer_norm_epsilon"`
+ RMSNormEps float32 `json:"rms_norm_eps"`
+ TieWordEmbeddings bool `json:"tie_word_embeddings"`
+ MaxPositionEmbeddings int32 `json:"max_position_embeddings"`
+ AttentionBias bool `json:"attention_bias"`
+ MLPBias bool `json:"mlp_bias"`
+ UseBias bool `json:"use_bias"`
ConvKernel int32 `json:"conv_kernel"`
SSMStateSize int32 `json:"ssm_state_size"`
@@ -136,20 +137,22 @@ type SparseMoE struct {
UseQuantized bool
- UpWeight *mlx.Array
- UpWeightQ *mlx.Array
- UpScales *mlx.Array
- UpBiases *mlx.Array
- UpGroupSize int
- UpBits int
- UpMode string
- DownWeight *mlx.Array
- DownWeightQ *mlx.Array
- DownScales *mlx.Array
- DownBiases *mlx.Array
- DownGroupSize int
- DownBits int
- DownMode string
+ UpWeight *mlx.Array
+ UpWeightQ *mlx.Array
+ UpScales *mlx.Array
+ UpBiases *mlx.Array
+ UpGroupSize int
+ UpBits int
+ UpMode string
+ DownWeight *mlx.Array
+ DownWeightQ *mlx.Array
+ DownScales *mlx.Array
+ DownBiases *mlx.Array
+ DownGroupSize int
+ DownBits int
+ DownMode string
+ UpGlobalScales *mlx.Array
+ DownGlobalScales *mlx.Array
SharedUp nn.LinearLayer
SharedDown nn.LinearLayer
@@ -158,12 +161,13 @@ type SparseMoE struct {
}
type stackedExpertWeights struct {
- Weight *mlx.Array
- Scales *mlx.Array
- Biases *mlx.Array
- Bits int
- GroupSize int
- Mode string
+ Weight *mlx.Array
+ Scales *mlx.Array
+ Biases *mlx.Array
+ GlobalScales *mlx.Array
+ Bits int
+ GroupSize int
+ Mode string
}
type configEnvelope struct {
@@ -183,6 +187,25 @@ func parseConfig(data []byte) (Config, error) {
if env.LLMConfig != nil {
cfg = *env.LLMConfig
}
+ if cfg.HybridOverridePattern == "" && len(cfg.LayersBlockType) > 0 {
+ pattern := make([]byte, len(cfg.LayersBlockType))
+ for i, layerType := range cfg.LayersBlockType {
+ switch layerType {
+ case "linear_attention":
+ pattern[i] = 'M'
+ case "full_attention":
+ pattern[i] = '*'
+ case "moe":
+ pattern[i] = 'E'
+ default:
+ return Config{}, fmt.Errorf("unsupported layers_block_type %q at layer %d", layerType, i)
+ }
+ }
+ cfg.HybridOverridePattern = string(pattern)
+ if cfg.NumHiddenLayers == 0 {
+ cfg.NumHiddenLayers = int32(len(pattern))
+ }
+ }
if cfg.HiddenSize <= 0 {
return Config{}, fmt.Errorf("invalid hidden_size: %d", cfg.HiddenSize)
@@ -382,24 +405,16 @@ func freeTensorKeys(tensors map[string]*mlx.Array, keys ...string) {
}
func combinedTensorGlobalScale(tensors map[string]*mlx.Array, key string) (*mlx.Array, []string) {
- var keys []string
- weightGlobal := tensors[key+".global_scale"]
- if weightGlobal == nil {
- weightGlobal = tensors[key+".weight.global_scale"]
- }
- if weightGlobal != nil {
- keys = append(keys, key+".global_scale", key+".weight.global_scale")
- }
- if tensors[key+".input_global_scale"] != nil || tensors[key+".weight.input_global_scale"] != nil {
- keys = append(keys, key+".input_global_scale", key+".weight.input_global_scale")
- }
- return weightGlobal, keys
+ return model.ReadGlobalScale(tensors, key, key+".weight")
}
func applyExpertWeightGlobalScale(weight, scale *mlx.Array) *mlx.Array {
if scale == nil {
return weight
}
+ // Divide out MLX's representation while still in float32: these multipliers
+ // are ~1e-3, so narrowing first would cost most of the mantissa.
+ scale = mlx.DivScalar(scale, mlx.Nvfp4MaxProduct)
if scale.DType() != weight.DType() {
scale = scale.AsType(weight.DType())
}
@@ -476,6 +491,9 @@ func foldSharedExperts(m *SparseMoE, cfg *Config) bool {
return true
}
+// foldQuantizedSharedExperts appends the shared expert's quantized weights to
+// the routed banks so one gather covers both, slicing the shared projections
+// into routed-expert-sized parts.
func foldQuantizedSharedExperts(m *SparseMoE, cfg *Config, parts int32) bool {
up, ok := m.SharedUp.(*nn.QuantizedLinear)
if !ok || up == nil {
@@ -485,7 +503,7 @@ func foldQuantizedSharedExperts(m *SparseMoE, cfg *Config, parts int32) bool {
if !ok || down == nil {
return false
}
- if up.Bias != nil || up.GlobalScale != nil || down.Bias != nil || down.GlobalScale != nil {
+ if up.Bias != nil || down.Bias != nil {
return false
}
if m.UpWeightQ == nil || m.UpScales == nil || m.DownWeightQ == nil || m.DownScales == nil {
@@ -503,6 +521,15 @@ func foldQuantizedSharedExperts(m *SparseMoE, cfg *Config, parts int32) bool {
if up.Weight.Dim(0) != int(cfg.MoESharedExpertIntermediateSize) || down.Weight.Dim(0) != int(cfg.HiddenSize) {
return false
}
+ upSharedScale, upFoldable := foldSharedExpertGlobalScale(up.GlobalScale)
+ if !upFoldable {
+ return false
+ }
+ downSharedScale, downFoldable := foldSharedExpertGlobalScale(down.GlobalScale)
+ if !downFoldable {
+ return false
+ }
+ routed := int32(m.UpWeightQ.Dim(0))
upWeightStack := stackQuantizedUpParts(up.Weight, cfg.MoEIntermediateSize, parts)
upScaleStack := stackQuantizedUpParts(up.Scales, cfg.MoEIntermediateSize, parts)
@@ -552,10 +579,41 @@ func foldQuantizedSharedExperts(m *SparseMoE, cfg *Config, parts int32) bool {
if downBiasStack != nil {
m.DownBiases = appendAndClone(m.DownBiases, downBiasStack)
}
+ // The weight banks grew by parts, so the scale banks must too.
+ m.UpGlobalScales = extendFoldedGlobalScales(m.UpGlobalScales, upSharedScale, routed, parts)
+ m.DownGlobalScales = extendFoldedGlobalScales(m.DownGlobalScales, downSharedScale, routed, parts)
return true
}
+// foldSharedExpertGlobalScale prepares a shared expert's global scale for the
+// folded bank. Per-row scales do not fit one-scale-per-expert, so folding is
+// skipped for them.
+func foldSharedExpertGlobalScale(globalScale *mlx.Array) (*mlx.Array, bool) {
+ if globalScale == nil {
+ return nil, true
+ }
+ if globalScale.Size() != 1 {
+ return nil, false
+ }
+ return globalScale, true
+}
+
+// extendFoldedGlobalScales appends the folded shared expert's per-part scales,
+// substituting the identity for whichever side has no scale of its own.
+func extendFoldedGlobalScales(bank, sharedScale *mlx.Array, routed, parts int32) *mlx.Array {
+ if bank == nil && sharedScale == nil {
+ return nil
+ }
+ if bank == nil {
+ bank = mlx.BroadcastTo(model.GatherQMMIdentityScale(), routed)
+ }
+ if sharedScale == nil {
+ sharedScale = model.GatherQMMIdentityScale()
+ }
+ return appendAndClone(bank, mlx.BroadcastTo(sharedScale, parts))
+}
+
func stackQuantizedUpParts(a *mlx.Array, partSize int32, parts int32) *mlx.Array {
if a == nil || a.NumDims() != 2 || a.Dim(0) != int(partSize*parts) {
return nil
@@ -622,19 +680,21 @@ func loadStackedExpertProjection(tensors map[string]*mlx.Array, cfg *Config, use
freeTensorKeys(tensors, key+"_qbias")
}
- if useQuantized && supportsGatherQMM(mode, bits) && globalScale == nil {
+ globalScale = model.PrepareGatherQMMGlobalScale(globalScale, w.Dim(0))
+ if useQuantized && supportsGatherQMM(mode, bits) {
return &stackedExpertWeights{
- Weight: w,
- Scales: scales,
- Biases: qbiases,
- Bits: bits,
- GroupSize: groupSize,
- Mode: mode,
+ Weight: w,
+ Scales: scales,
+ Biases: qbiases,
+ GlobalScales: globalScale,
+ Bits: bits,
+ GroupSize: groupSize,
+ Mode: mode,
}
}
return &stackedExpertWeights{
- Weight: applyExpertWeightGlobalScale(mlx.Dequantize(w, scales, qbiases, groupSize, bits, mode, nil), globalScale),
+ Weight: mlx.Dequantize(w, scales, qbiases, groupSize, bits, mode, globalScale),
Bits: bits,
GroupSize: groupSize,
Mode: mode,
@@ -645,10 +705,13 @@ func collectExpertProjection(tensors map[string]*mlx.Array, cfg *Config, useQuan
weights := make([]*mlx.Array, 0, numExperts)
scales := make([]*mlx.Array, 0, numExperts)
biases := make([]*mlx.Array, 0, numExperts)
+ globalScales := make([]*mlx.Array, 0, numExperts)
consumed := make([]string, 0, numExperts*3)
bits := 0
groupSize := 0
mode := cfg.QuantMode
+ quantized := false
+ sourceQuantized := false
for e := range numExperts {
key := fmt.Sprintf("%s.mixer.experts.%d.%s.weight", layerPrefix, e, proj)
@@ -661,9 +724,19 @@ func collectExpertProjection(tensors map[string]*mlx.Array, cfg *Config, useQuan
scaleKey := key + "_scale"
scale := tensors[scaleKey]
if scale == nil {
+ if e == 0 {
+ sourceQuantized = false
+ } else if sourceQuantized {
+ return nil
+ }
weights = append(weights, w)
continue
}
+ if e == 0 {
+ sourceQuantized = true
+ } else if !sourceQuantized {
+ return nil
+ }
consumed = append(consumed, scaleKey)
qbiasKey := key + "_qbias"
@@ -688,18 +761,32 @@ func collectExpertProjection(tensors map[string]*mlx.Array, cfg *Config, useQuan
groupSize = gs
mode = m
}
- if useQuantized && supportsGatherQMM(m, b) && globalScale == nil {
+ keepQuantized := useQuantized && supportsGatherQMM(m, b)
+ if e == 0 {
+ quantized = keepQuantized
+ } else if quantized != keepQuantized ||
+ (sourceQuantized && (b != bits || gs != groupSize || m != mode)) {
+ return nil
+ }
+ if qbias != nil {
+ biases = append(biases, qbias)
+ }
+ if keepQuantized {
weights = append(weights, w)
scales = append(scales, scale)
- if qbias != nil {
- biases = append(biases, qbias)
+ if globalScale != nil {
+ globalScales = append(globalScales, globalScale)
}
continue
}
- weights = append(weights, applyExpertWeightGlobalScale(mlx.Dequantize(w, scale, qbias, gs, b, m, nil), globalScale))
+ weights = append(weights, mlx.Dequantize(w, scale, qbias, gs, b, m, globalScale))
}
+ if (len(biases) != 0 && len(biases) != len(weights)) ||
+ (len(globalScales) != 0 && len(globalScales) != len(weights)) {
+ return nil
+ }
out := &stackedExpertWeights{
Weight: stackAndClone(weights),
Bits: bits,
@@ -709,9 +796,12 @@ func collectExpertProjection(tensors map[string]*mlx.Array, cfg *Config, useQuan
if len(scales) == len(weights) {
out.Scales = stackAndClone(scales)
}
- if len(biases) == len(weights) {
+ if quantized && len(biases) == len(weights) {
out.Biases = stackAndClone(biases)
}
+ if len(globalScales) == len(weights) {
+ out.GlobalScales = mlx.Reshape(stackAndClone(globalScales), int32(len(weights)))
+ }
freeTensorKeys(tensors, consumed...)
return out
}
@@ -904,6 +994,7 @@ func loadLayer(linears model.LinearFactory, tensors map[string]*mlx.Array, cfg *
moe.UpWeightQ = up.Weight
moe.UpScales = up.Scales
moe.UpBiases = up.Biases
+ moe.UpGlobalScales = up.GlobalScales
moe.UpGroupSize = up.GroupSize
moe.UpBits = up.Bits
moe.UpMode = up.Mode
@@ -914,6 +1005,7 @@ func loadLayer(linears model.LinearFactory, tensors map[string]*mlx.Array, cfg *
moe.DownWeightQ = down.Weight
moe.DownScales = down.Scales
moe.DownBiases = down.Biases
+ moe.DownGlobalScales = down.GlobalScales
moe.DownGroupSize = down.GroupSize
moe.DownBits = down.Bits
moe.DownMode = down.Mode
@@ -1158,6 +1250,7 @@ func (m *SparseMoE) gatherExpertUp(xFlat, idxFlat *mlx.Array, doSort bool) *mlx.
m.UpGroupSize,
m.UpBits,
m.UpMode,
+ m.UpGlobalScales,
doSort,
)
}
@@ -1177,6 +1270,7 @@ func (m *SparseMoE) gatherExpertDown(hidden, idxFlat *mlx.Array, doSort bool) *m
m.DownGroupSize,
m.DownBits,
m.DownMode,
+ m.DownGlobalScales,
doSort,
)
}
diff --git a/x/models/nemotron_h/nemotron_h_test.go b/x/models/nemotron_h/nemotron_h_test.go
index b1fcf9c3e..1d3d404d3 100644
--- a/x/models/nemotron_h/nemotron_h_test.go
+++ b/x/models/nemotron_h/nemotron_h_test.go
@@ -9,6 +9,7 @@ import (
"github.com/ollama/ollama/x/internal/mlxtest"
"github.com/ollama/ollama/x/mlxrunner/cache"
"github.com/ollama/ollama/x/mlxrunner/mlx"
+ "github.com/ollama/ollama/x/models/nn"
)
func TestParseConfigNestedWrapper(t *testing.T) {
@@ -52,6 +53,39 @@ func TestParseConfigNestedWrapper(t *testing.T) {
}
}
+func TestParseConfigLayersBlockType(t *testing.T) {
+ cfg, err := parseConfig([]byte(`{
+ "model_type": "nemotron_h",
+ "hidden_size": 8,
+ "num_attention_heads": 2,
+ "layers_block_type": ["linear_attention", "moe", "full_attention"]
+ }`))
+ if err != nil {
+ t.Fatalf("parseConfig returned error: %v", err)
+ }
+
+ if got, want := cfg.NumHiddenLayers, int32(3); got != want {
+ t.Fatalf("NumHiddenLayers = %d, want %d", got, want)
+ }
+ if got, want := cfg.HybridOverridePattern, "ME*"; got != want {
+ t.Fatalf("HybridOverridePattern = %q, want %q", got, want)
+ }
+ if got, want := string(cfg.LayerTypes), "ME*"; got != want {
+ t.Fatalf("LayerTypes = %q, want %q", got, want)
+ }
+}
+
+func TestParseConfigRejectsUnknownLayerBlockType(t *testing.T) {
+ _, err := parseConfig([]byte(`{
+ "hidden_size": 8,
+ "num_attention_heads": 2,
+ "layers_block_type": ["linear_attention", "dense"]
+ }`))
+ if err == nil || !strings.Contains(err.Error(), `unsupported layers_block_type "dense" at layer 1`) {
+ t.Fatalf("parseConfig error = %v, want unsupported layer type error", err)
+ }
+}
+
func TestParseConfigRejectsBadPattern(t *testing.T) {
_, err := parseConfig([]byte(`{
"hidden_size": 4,
@@ -330,7 +364,8 @@ func TestApplyExpertWeightGlobalScale(t *testing.T) {
5, 6,
7, 8,
}, 2, 2, 2)
- scale := mlx.FromValues([]float32{2, 3}, 2)
+ // Scales reach this function already in MLX's representation.
+ scale := mlx.FromValues([]float32{2 * mlx.Nvfp4MaxProduct, 3 * mlx.Nvfp4MaxProduct}, 2)
got := applyExpertWeightGlobalScale(weight, scale)
mlx.Eval(got)
@@ -394,3 +429,111 @@ func assertAllClose(t *mlxtest.T, name string, got, want []float32, tol float64)
}
}
}
+
+// Folding shared experts into the routed banks must keep the global scale
+// banks aligned with the weight banks: rows are added, so scales are added
+// too — the shared expert's own scale when it has one, MLX's identity scale
+// when it does not.
+func TestFoldSharedExpertsExtendsGlobalScales(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ const routed, inter, sharedInter, hidden = 3, 16, 32, 32
+ cfg := &Config{
+ NSharedExperts: 1,
+ MoEIntermediateSize: inter,
+ MoESharedExpertIntermediateSize: sharedInter,
+ HiddenSize: hidden,
+ }
+
+ newMoE := func(routedKernelScales []float32, sharedGlobalScale *mlx.Array) *SparseMoE {
+ m := &SparseMoE{
+ UseQuantized: true,
+ UpWeightQ: mlx.Zeros(mlx.DTypeUint32, routed, inter, hidden/8),
+ UpScales: mlx.Zeros(mlx.DTypeUint8, routed, inter, hidden/16),
+ UpGroupSize: 16,
+ UpBits: 4,
+ UpMode: "nvfp4",
+ DownWeightQ: mlx.Zeros(mlx.DTypeUint32, routed, hidden, inter/8),
+ DownScales: mlx.Zeros(mlx.DTypeUint8, routed, hidden, inter/16),
+ DownGroupSize: 16,
+ DownBits: 4,
+ DownMode: "nvfp4",
+ SharedUp: &nn.QuantizedLinear{
+ Weight: mlx.Zeros(mlx.DTypeUint32, sharedInter, hidden/8),
+ Scales: mlx.Zeros(mlx.DTypeUint8, sharedInter, hidden/16),
+ GroupSize: 16,
+ Bits: 4,
+ Mode: "nvfp4",
+ GlobalScale: sharedGlobalScale,
+ },
+ SharedDown: &nn.QuantizedLinear{
+ Weight: mlx.Zeros(mlx.DTypeUint32, hidden, sharedInter/8),
+ Scales: mlx.Zeros(mlx.DTypeUint8, hidden, sharedInter/16),
+ GroupSize: 16,
+ Bits: 4,
+ Mode: "nvfp4",
+ GlobalScale: sharedGlobalScale,
+ },
+ }
+ if routedKernelScales != nil {
+ m.UpGlobalScales = mlx.FromValues(routedKernelScales, routed)
+ m.DownGlobalScales = mlx.FromValues(routedKernelScales, routed)
+ }
+ return m
+ }
+
+ checkScales := func(name string, m *SparseMoE, want []float32) {
+ t.Helper()
+ for _, gs := range []*mlx.Array{m.UpGlobalScales, m.DownGlobalScales} {
+ mlx.Eval(gs)
+ if dims := gs.Dims(); len(dims) != 1 || dims[0] != len(want) {
+ t.Fatalf("%s dims = %v, want [%d]", name, dims, len(want))
+ }
+ assertAllClose(t, name, gs.Floats(), want, 1e-5)
+ }
+ }
+
+ // Routed experts carry kernel scales; the scaleless shared expert folds
+ // as the identity scale.
+ m := newMoE([]float32{1, 2, 3}, nil)
+ if !foldSharedExperts(m, cfg) {
+ t.Fatal("foldSharedExperts failed with routed global scales and a scaleless shared expert")
+ }
+ checkScales("identity extension", m, []float32{1, 2, 3, mlx.Nvfp4MaxProduct, mlx.Nvfp4MaxProduct})
+
+ // The shared expert's own per-tensor scale folds as a routed expert's.
+ m = newMoE([]float32{1, 2, 3}, mlx.FromValues([]float32{0.25 * mlx.Nvfp4MaxProduct}, 1))
+ if !foldSharedExperts(m, cfg) {
+ t.Fatal("foldSharedExperts failed with a per-tensor shared expert scale")
+ }
+ shared := float32(0.25 * mlx.Nvfp4MaxProduct)
+ checkScales("shared scale extension", m, []float32{1, 2, 3, shared, shared})
+
+ // Scaleless routed experts fold against an identity bank when the
+ // shared expert carries a scale.
+ m = newMoE(nil, mlx.FromValues([]float32{0.25 * mlx.Nvfp4MaxProduct}, 1))
+ if !foldSharedExperts(m, cfg) {
+ t.Fatal("foldSharedExperts failed with a scaleless routed bank")
+ }
+ identity := float32(mlx.Nvfp4MaxProduct)
+ checkScales("identity bank", m, []float32{identity, identity, identity, shared, shared})
+
+ // Nothing to scale: the banks stay nil.
+ m = newMoE(nil, nil)
+ if !foldSharedExperts(m, cfg) {
+ t.Fatal("foldSharedExperts failed without global scales")
+ }
+ if m.UpGlobalScales != nil || m.DownGlobalScales != nil {
+ t.Fatal("fold without global scales materialized a scale bank")
+ }
+
+ // A per-row shared expert scale cannot be represented per expert bank
+ // row, so the fold is skipped.
+ m = newMoE([]float32{1, 2, 3}, mlx.FromValues([]float32{1 * mlx.Nvfp4MaxProduct, 2 * mlx.Nvfp4MaxProduct}, 2))
+ if foldSharedExperts(m, cfg) {
+ t.Fatal("foldSharedExperts accepted a per-row shared expert scale")
+ }
+ if dims := m.UpWeightQ.Dims(); dims[0] != routed {
+ t.Fatalf("skipped fold mutated the weight bank: dims = %v", dims)
+ }
+ })
+}
diff --git a/x/models/nn/nn.go b/x/models/nn/nn.go
index 95e5c0875..e23dd6722 100644
--- a/x/models/nn/nn.go
+++ b/x/models/nn/nn.go
@@ -112,24 +112,10 @@ func NewQuantizedLinear(weight *mlx.Array, bias *mlx.Array, groupSize, bits int,
}
}
-var quantizedLinearOutputScale = mlx.Compile2(
- "QuantizedLinearOutputScale",
- func(out, scale *mlx.Array) *mlx.Array {
- return mlx.Mul(out, scale).AsType(out.DType())
- },
- mlx.Shapeless(),
-)
-
func (ql *QuantizedLinear) Forward(x *mlx.Array) *mlx.Array {
- out := mlx.QuantizedMatmul(x, ql.Weight, ql.Scales, ql.QBiases, true, ql.GroupSize, ql.Bits, ql.Mode)
- if ql.GlobalScale != nil {
- // Double-scale nvfp4 (e.g., NVIDIA ModelOpt): standard quantized_matmul
- // followed by global_scale multiply. The global_scale is F32, per-tensor
- // (weight_scale_2 in NVIDIA's format) or per-row.
- // TODO: switch to a fused double-scale matmul once MLX has kernel
- // coverage for this path.
- out = quantizedLinearOutputScale(out, ql.GlobalScale)
- }
+ // Double-scale nvfp4 (e.g., NVIDIA ModelOpt) applies the per-tensor or
+ // per-row global scale inside QuantizedMatmul.
+ out := mlx.QuantizedMatmul(x, ql.Weight, ql.Scales, ql.QBiases, true, ql.GroupSize, ql.Bits, ql.Mode, ql.GlobalScale)
if ql.Bias != nil {
bias := ql.Bias
if bias.DType() != out.DType() {
diff --git a/x/models/nn/nn_test.go b/x/models/nn/nn_test.go
index b9c7ca339..6d6e5c911 100644
--- a/x/models/nn/nn_test.go
+++ b/x/models/nn/nn_test.go
@@ -216,3 +216,55 @@ func TestQuantizedEmbeddingAsLinearPreservesGlobalScale(t *testing.T) {
t.Fatalf("AsLinear quant params = (%d, %d, %q), want (16, 4, %q)", linear.GroupSize, linear.Bits, linear.Mode, "nvfp4")
}
}
+
+// A dense nvfp4 projection carries the checkpoint's global scale through
+// QuantizedMatmul, which applies it to the output in a single fused kernel.
+// The dequantized weights are the reference.
+func TestQuantizedLinearGlobalScaleMatchesDequantized(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ if !mlx.MetalIsAvailable() && !mlx.CUDAIsAvailable() {
+ t.Skip("nvfp4 quantized_matmul requires a GPU backend")
+ }
+ const rows, cols, group = 64, 64, 16
+
+ weightValues := make([]float32, rows*cols)
+ for i := range weightValues {
+ weightValues[i] = float32((i%23)-11) * 0.011
+ }
+ weight := mlx.FromValues(weightValues, rows, cols).AsType(mlx.DTypeBFloat16)
+ packed, scales, _ := mlx.Quantize(weight, group, 4, "nvfp4")
+ mlx.Eval(packed, scales)
+
+ globalScale := mlx.FromValues([]float32{0.375}, 1)
+ linear := &QuantizedLinear{
+ Weight: packed, Scales: scales, GlobalScale: globalScale,
+ GroupSize: group, Bits: 4, Mode: "nvfp4",
+ }
+
+ xValues := make([]float32, cols)
+ for i := range xValues {
+ xValues[i] = float32(i%7-3) / 8
+ }
+ x := mlx.FromValues(xValues, 1, cols).AsType(mlx.DTypeBFloat16)
+
+ got := linear.Forward(x).AsType(mlx.DTypeFloat32)
+ dense := mlx.Dequantize(packed, scales, nil, group, 4, "nvfp4", globalScale)
+ want := mlx.Matmul(x.AsType(mlx.DTypeFloat32), mlx.Transpose(dense.AsType(mlx.DTypeFloat32), 1, 0))
+ mlx.Eval(got, want)
+
+ gotValues, wantValues := got.Floats(), want.Floats()
+ if len(gotValues) != len(wantValues) {
+ t.Fatalf("output length = %d, want %d", len(gotValues), len(wantValues))
+ }
+ for i := range gotValues {
+ if math.IsNaN(float64(gotValues[i])) || math.IsInf(float64(gotValues[i]), 0) {
+ t.Fatalf("output[%d] = %v, want finite", i, gotValues[i])
+ }
+ delta := math.Abs(float64(gotValues[i] - wantValues[i]))
+ tolerance := 0.02 * math.Max(math.Abs(float64(wantValues[i])), 1)
+ if delta > tolerance {
+ t.Fatalf("output[%d] = %v, want %v (delta %v > %v)", i, gotValues[i], wantValues[i], delta, tolerance)
+ }
+ }
+ })
+}
diff --git a/x/models/qwen3_5/gdn_projections.go b/x/models/qwen3_5/gdn_projections.go
index 69d48b87d..1deb3dcdd 100644
--- a/x/models/qwen3_5/gdn_projections.go
+++ b/x/models/qwen3_5/gdn_projections.go
@@ -191,7 +191,8 @@ func concatGlobalScales(hi, lo, hiRows, loRows *mlx.Array) *mlx.Array {
expand := func(scale *mlx.Array, rows int32) *mlx.Array {
switch {
case scale == nil:
- return mlx.Tile(mlx.FromValues([]float32{1}, 1), []int32{rows})
+ // Identity in MLX's representation, not 1.
+ return mlx.Tile(mlx.FromValues([]float32{mlx.Nvfp4MaxProduct}, 1), []int32{rows})
case scale.Size() == 1:
return mlx.Tile(mlx.Reshape(scale.AsType(mlx.DTypeFloat32), 1), []int32{rows})
default:
diff --git a/x/models/qwen3_5/qwen3_5.go b/x/models/qwen3_5/qwen3_5.go
index 9076f8508..85a7a03bd 100644
--- a/x/models/qwen3_5/qwen3_5.go
+++ b/x/models/qwen3_5/qwen3_5.go
@@ -176,15 +176,20 @@ type SparseMoE struct {
SharedExpertGate nn.LinearLayer
}
-// SwitchMLP executes selected expert MLPs. Gate and up are always held
-// packed as one gate_up tensor; checkpoints that ship them separately are
-// fused at load.
+// SwitchMLP executes selected expert MLPs. Gate and up stay fused when the
+// checkpoint layout and quantization parameters allow it.
type SwitchMLP struct {
GateUpWeight *mlx.Array
DownWeight *mlx.Array
+ GateWeight *mlx.Array
+ UpWeight *mlx.Array
GateUpWeightQ, GateUpScales, GateUpBias *mlx.Array
DownWeightQ, DownScales, DownBiases *mlx.Array
+ GateUpGlobalScales, DownGlobalScales *mlx.Array
+ GateWeightQ, GateScales, GateBiases *mlx.Array
+ UpWeightQ, UpScales, UpBiases *mlx.Array
+ GateGlobalScales, UpGlobalScales *mlx.Array
GateUpBits int
DownBits int
@@ -192,15 +197,22 @@ type SwitchMLP struct {
DownGroupSize int
GateUpMode string
DownMode string
+ GateBits int
+ UpBits int
+ GateGroupSize int
+ UpGroupSize int
+ GateMode string
+ UpMode string
}
type stackedExpertWeights struct {
- Weight *mlx.Array
- Scales *mlx.Array
- Biases *mlx.Array
- Bits int
- GroupSize int
- Mode string
+ Weight *mlx.Array
+ Scales *mlx.Array
+ Biases *mlx.Array
+ GlobalScales *mlx.Array
+ Bits int
+ GroupSize int
+ Mode string
}
func parseConfig(configData []byte) (Config, error) {
@@ -497,7 +509,8 @@ func fuseExpertStacks(a, b *mlx.Array, axis int) *mlx.Array {
}
// fuseGateUpProjections joins gate and up stacks along the output dimension,
-// which is exact for quantized stacks: groups run along the input dimension.
+// which is exact for quantized stacks: groups run along the input dimension,
+// and a global scale covers the whole bank row.
func fuseGateUpProjections(gate, up *stackedExpertWeights) *stackedExpertWeights {
if gate == nil || up == nil {
return nil
@@ -506,14 +519,16 @@ func fuseGateUpProjections(gate, up *stackedExpertWeights) *stackedExpertWeights
return nil
}
if gate.Scales != nil && up.Scales != nil &&
+ model.SameGlobalScales(gate.GlobalScales, up.GlobalScales) &&
gate.Bits == up.Bits && gate.GroupSize == up.GroupSize && gate.Mode == up.Mode &&
(gate.Biases == nil) == (up.Biases == nil) {
fused := &stackedExpertWeights{
- Weight: fuseExpertStacks(gate.Weight, up.Weight, 1),
- Scales: fuseExpertStacks(gate.Scales, up.Scales, 1),
- Bits: gate.Bits,
- GroupSize: gate.GroupSize,
- Mode: gate.Mode,
+ Weight: fuseExpertStacks(gate.Weight, up.Weight, 1),
+ Scales: fuseExpertStacks(gate.Scales, up.Scales, 1),
+ GlobalScales: gate.GlobalScales,
+ Bits: gate.Bits,
+ GroupSize: gate.GroupSize,
+ Mode: gate.Mode,
}
if gate.Biases != nil {
fused.Biases = fuseExpertStacks(gate.Biases, up.Biases, 1)
@@ -521,20 +536,10 @@ func fuseGateUpProjections(gate, up *stackedExpertWeights) *stackedExpertWeights
return fused
}
if gate.Scales != nil || up.Scales != nil {
- slog.Warn("dequantizing gate/up experts: quantization parameters differ",
- "gate_mode", gate.Mode, "gate_bits", gate.Bits, "gate_group_size", gate.GroupSize,
- "up_mode", up.Mode, "up_bits", up.Bits, "up_group_size", up.GroupSize)
- }
- gateWeight := gate.Weight
- if gate.Scales != nil {
- gateWeight = mlx.Dequantize(gate.Weight, gate.Scales, gate.Biases, gate.GroupSize, gate.Bits, gate.Mode, nil)
- }
- upWeight := up.Weight
- if up.Scales != nil {
- upWeight = mlx.Dequantize(up.Weight, up.Scales, up.Biases, up.GroupSize, up.Bits, up.Mode, nil)
+ return nil
}
return &stackedExpertWeights{
- Weight: mlx.Concatenate([]*mlx.Array{gateWeight, upWeight}, 1),
+ Weight: mlx.Concatenate([]*mlx.Array{gate.Weight, up.Weight}, 1),
Bits: gate.Bits,
GroupSize: gate.GroupSize,
Mode: gate.Mode,
@@ -554,6 +559,7 @@ func loadStackedProjection(tensors map[string]*mlx.Array, cfg *Config, useQuanti
}
qbiases := tensors[key+"_qbias"]
+ globalScale, _ := model.ReadGlobalScale(tensors, key, base+".weight", base)
groupSize, bits, mode := model.ResolveLinearQuantParams(
cfg.QuantGroupSize,
cfg.QuantBits,
@@ -563,14 +569,16 @@ func loadStackedProjection(tensors map[string]*mlx.Array, cfg *Config, useQuanti
w,
scales,
)
+ globalScale = model.PrepareGatherQMMGlobalScale(globalScale, w.Dim(0))
if useQuantized && supportsGatherQMM(mode, bits) {
return &stackedExpertWeights{
- Weight: w,
- Scales: scales,
- Biases: qbiases,
- Bits: bits,
- GroupSize: groupSize,
- Mode: mode,
+ Weight: w,
+ Scales: scales,
+ Biases: qbiases,
+ GlobalScales: globalScale,
+ Bits: bits,
+ GroupSize: groupSize,
+ Mode: mode,
}
}
@@ -578,7 +586,7 @@ func loadStackedProjection(tensors map[string]*mlx.Array, cfg *Config, useQuanti
slog.Warn("dequantizing expert weights: no gather kernel for format", "tensor", key, "mode", mode, "bits", bits)
}
return &stackedExpertWeights{
- Weight: mlx.Dequantize(w, scales, qbiases, groupSize, bits, mode, nil),
+ Weight: mlx.Dequantize(w, scales, qbiases, groupSize, bits, mode, globalScale),
Bits: bits,
GroupSize: groupSize,
Mode: mode,
@@ -592,25 +600,39 @@ func collectPerExpertProjection(tensors map[string]*mlx.Array, cfg *Config, useQ
weights := make([]*mlx.Array, 0, numExperts)
scales := make([]*mlx.Array, 0, numExperts)
biases := make([]*mlx.Array, 0, numExperts)
+ globalScales := make([]*mlx.Array, 0, numExperts)
+ numGlobalScales := 0
consumedKeys := make([]string, 0, numExperts*3)
numDequantized := 0
bits := 0
groupSize := 0
mode := cfg.QuantMode
+ quantized := false
+ sourceQuantized := false
for e := range numExperts {
base := fmt.Sprintf("%s.mlp.experts.%d.%s", layerPrefix, e, proj)
w, key := tensorByBase(tensors, base)
if w == nil {
- continue
+ return nil
}
consumedKeys = append(consumedKeys, key)
s := tensors[key+"_scale"]
if s == nil {
+ if e == 0 {
+ sourceQuantized = false
+ } else if sourceQuantized {
+ return nil
+ }
weights = append(weights, w)
continue
}
+ if e == 0 {
+ sourceQuantized = true
+ } else if !sourceQuantized {
+ return nil
+ }
consumedKeys = append(consumedKeys, key+"_scale")
qb := tensors[key+"_qbias"]
if qb != nil {
@@ -630,14 +652,29 @@ func collectPerExpertProjection(tensors map[string]*mlx.Array, cfg *Config, useQ
groupSize = gs
mode = m
}
- if useQuantized && supportsGatherQMM(m, b) {
+ globalScale, globalScaleKeys := model.ReadGlobalScale(tensors, key, base+".weight", base)
+ consumedKeys = append(consumedKeys, globalScaleKeys...)
+ keepQuantized := useQuantized && supportsGatherQMM(m, b)
+ if e == 0 {
+ quantized = keepQuantized
+ } else if quantized != keepQuantized ||
+ (sourceQuantized && (b != bits || gs != groupSize || m != mode)) {
+ return nil
+ }
+ if qb != nil {
+ biases = append(biases, qb)
+ }
+ if globalScale != nil {
+ numGlobalScales++
+ }
+ if keepQuantized {
weights = append(weights, w)
scales = append(scales, s)
- if qb != nil {
- biases = append(biases, qb)
+ if globalScale != nil {
+ globalScales = append(globalScales, globalScale)
}
} else {
- weights = append(weights, mlx.Dequantize(w, s, qb, gs, b, m, nil))
+ weights = append(weights, mlx.Dequantize(w, s, qb, gs, b, m, globalScale))
numDequantized++
}
}
@@ -649,14 +686,23 @@ func collectPerExpertProjection(tensors map[string]*mlx.Array, cfg *Config, useQ
if len(weights) == 0 {
return nil
}
+ // A global scale on some experts but not others is a malformed checkpoint.
+ if (len(biases) != 0 && len(biases) != len(weights)) ||
+ (len(globalScales) != 0 && len(globalScales) != len(weights)) ||
+ (numGlobalScales != 0 && numGlobalScales != len(weights)) {
+ return nil
+ }
out := &stackedExpertWeights{Weight: stackAndClone(weights), Bits: bits, GroupSize: groupSize, Mode: mode}
if len(scales) == len(weights) {
out.Scales = stackAndClone(scales)
}
- if len(biases) == len(weights) {
+ if quantized && len(biases) == len(weights) {
out.Biases = stackAndClone(biases)
}
+ if len(globalScales) == len(weights) {
+ out.GlobalScales = mlx.Reshape(stackAndClone(globalScales), int32(len(weights)))
+ }
freeTensorKeys(tensors, consumedKeys...)
return out
}
@@ -679,6 +725,9 @@ func combinedGateUpProjection(tensors map[string]*mlx.Array, cfg *Config, useQua
}
qbiases := tensors[key+"_qbias"]
+ globalScale, _ := model.ReadGlobalScale(tensors, key,
+ layerPrefix+".mlp.experts.gate_up_proj.weight",
+ layerPrefix+".mlp.experts.gate_up_proj")
groupSize, bits, mode := model.ResolveLinearQuantParams(
cfg.QuantGroupSize,
cfg.QuantBits,
@@ -688,21 +737,23 @@ func combinedGateUpProjection(tensors map[string]*mlx.Array, cfg *Config, useQua
gateUp,
scales,
)
+ globalScale = model.PrepareGatherQMMGlobalScale(globalScale, gateUp.Dim(0))
if useQuantized && supportsGatherQMM(mode, bits) {
return &stackedExpertWeights{
- Weight: gateUp,
- Scales: scales,
- Biases: qbiases,
- Bits: bits,
- GroupSize: groupSize,
- Mode: mode,
+ Weight: gateUp,
+ Scales: scales,
+ Biases: qbiases,
+ GlobalScales: globalScale,
+ Bits: bits,
+ GroupSize: groupSize,
+ Mode: mode,
}
}
if useQuantized {
slog.Warn("dequantizing expert weights: no gather kernel for format", "tensor", key, "mode", mode, "bits", bits)
}
return &stackedExpertWeights{
- Weight: mlx.Dequantize(gateUp, scales, qbiases, groupSize, bits, mode, nil),
+ Weight: mlx.Dequantize(gateUp, scales, qbiases, groupSize, bits, mode, globalScale),
Bits: bits,
GroupSize: groupSize,
Mode: mode,
@@ -729,17 +780,18 @@ func splitLastAxisHalves(a *mlx.Array) (lo, hi *mlx.Array) {
// loadSwitchMLP assembles a layer's routed experts from any supported
// checkpoint layout.
func loadSwitchMLP(tensors map[string]*mlx.Array, cfg *Config, useQuantized bool, layerPrefix string) (*SwitchMLP, error) {
+ var gateW, upW *stackedExpertWeights
gateUpW := combinedGateUpProjection(tensors, cfg, useQuantized, layerPrefix)
downW := loadStackedProjection(tensors, cfg, useQuantized,
layerPrefix+".mlp.switch_mlp.down_proj",
layerPrefix+".mlp.experts.down_proj",
)
if gateUpW == nil {
- gateW := loadStackedProjection(tensors, cfg, useQuantized,
+ gateW = loadStackedProjection(tensors, cfg, useQuantized,
layerPrefix+".mlp.switch_mlp.gate_proj",
layerPrefix+".mlp.experts.gate_proj",
)
- upW := loadStackedProjection(tensors, cfg, useQuantized,
+ upW = loadStackedProjection(tensors, cfg, useQuantized,
layerPrefix+".mlp.switch_mlp.up_proj",
layerPrefix+".mlp.experts.up_proj",
)
@@ -754,25 +806,52 @@ func loadSwitchMLP(tensors map[string]*mlx.Array, cfg *Config, useQuantized bool
if downW == nil {
downW = collectPerExpertProjection(tensors, cfg, useQuantized, layerPrefix, "down_proj", cfg.NumExperts)
}
- if gateUpW == nil || downW == nil {
+ if (gateUpW == nil && (gateW == nil || upW == nil)) || downW == nil {
return nil, fmt.Errorf("missing switch expert weights")
}
switchMLP := &SwitchMLP{}
- if gateUpW.Scales != nil {
- switchMLP.GateUpWeightQ = gateUpW.Weight
- switchMLP.GateUpScales = gateUpW.Scales
- switchMLP.GateUpBias = gateUpW.Biases
- switchMLP.GateUpBits = gateUpW.Bits
- switchMLP.GateUpGroupSize = gateUpW.GroupSize
- switchMLP.GateUpMode = gateUpW.Mode
+ if gateUpW != nil {
+ if gateUpW.Scales != nil {
+ switchMLP.GateUpWeightQ = gateUpW.Weight
+ switchMLP.GateUpScales = gateUpW.Scales
+ switchMLP.GateUpBias = gateUpW.Biases
+ switchMLP.GateUpGlobalScales = gateUpW.GlobalScales
+ switchMLP.GateUpBits = gateUpW.Bits
+ switchMLP.GateUpGroupSize = gateUpW.GroupSize
+ switchMLP.GateUpMode = gateUpW.Mode
+ } else {
+ switchMLP.GateUpWeight = transposeExpertWeightForGatherMM(gateUpW.Weight)
+ }
} else {
- switchMLP.GateUpWeight = transposeExpertWeightForGatherMM(gateUpW.Weight)
+ if gateW.Scales != nil {
+ switchMLP.GateWeightQ = gateW.Weight
+ switchMLP.GateScales = gateW.Scales
+ switchMLP.GateBiases = gateW.Biases
+ switchMLP.GateGlobalScales = gateW.GlobalScales
+ switchMLP.GateBits = gateW.Bits
+ switchMLP.GateGroupSize = gateW.GroupSize
+ switchMLP.GateMode = gateW.Mode
+ } else {
+ switchMLP.GateWeight = transposeExpertWeightForGatherMM(gateW.Weight)
+ }
+ if upW.Scales != nil {
+ switchMLP.UpWeightQ = upW.Weight
+ switchMLP.UpScales = upW.Scales
+ switchMLP.UpBiases = upW.Biases
+ switchMLP.UpGlobalScales = upW.GlobalScales
+ switchMLP.UpBits = upW.Bits
+ switchMLP.UpGroupSize = upW.GroupSize
+ switchMLP.UpMode = upW.Mode
+ } else {
+ switchMLP.UpWeight = transposeExpertWeightForGatherMM(upW.Weight)
+ }
}
if downW.Scales != nil {
switchMLP.DownWeightQ = downW.Weight
switchMLP.DownScales = downW.Scales
switchMLP.DownBiases = downW.Biases
+ switchMLP.DownGlobalScales = downW.GlobalScales
switchMLP.DownBits = downW.Bits
switchMLP.DownGroupSize = downW.GroupSize
switchMLP.DownMode = downW.Mode
@@ -1143,18 +1222,36 @@ func (s *SwitchMLP) Forward(x *mlx.Array, indices *mlx.Array, cfg *Config) *mlx.
idxFlat = mlx.Reshape(mlx.Take(idxAll, order, 0), n, 1)
}
- var gateUp, down *mlx.Array
+ var gate, up, down *mlx.Array
if s.GateUpWeightQ != nil {
- gateUp = mlx.GatherQMM(xFlat, s.GateUpWeightQ, s.GateUpScales, s.GateUpBias,
- nil, idxFlat, true, s.GateUpGroupSize, s.GateUpBits, s.GateUpMode, doSort)
+ gateUp := mlx.GatherQMM(xFlat, s.GateUpWeightQ, s.GateUpScales, s.GateUpBias,
+ nil, idxFlat, true, s.GateUpGroupSize, s.GateUpBits, s.GateUpMode,
+ s.GateUpGlobalScales, doSort)
+ gate, up = splitLastAxisHalves(gateUp)
+ } else if s.GateUpWeight != nil {
+ gateUp := mlx.GatherMM(xFlat, s.GateUpWeight, nil, idxFlat, doSort)
+ gate, up = splitLastAxisHalves(gateUp)
} else {
- gateUp = mlx.GatherMM(xFlat, s.GateUpWeight, nil, idxFlat, doSort)
+ if s.GateWeightQ != nil {
+ gate = mlx.GatherQMM(xFlat, s.GateWeightQ, s.GateScales, s.GateBiases,
+ nil, idxFlat, true, s.GateGroupSize, s.GateBits, s.GateMode,
+ s.GateGlobalScales, doSort)
+ } else {
+ gate = mlx.GatherMM(xFlat, s.GateWeight, nil, idxFlat, doSort)
+ }
+ if s.UpWeightQ != nil {
+ up = mlx.GatherQMM(xFlat, s.UpWeightQ, s.UpScales, s.UpBiases,
+ nil, idxFlat, true, s.UpGroupSize, s.UpBits, s.UpMode,
+ s.UpGlobalScales, doSort)
+ } else {
+ up = mlx.GatherMM(xFlat, s.UpWeight, nil, idxFlat, doSort)
+ }
}
- gate, up := splitLastAxisHalves(gateUp)
hidden := mlx.SwiGLU(gate, up)
if s.DownWeightQ != nil {
down = mlx.GatherQMM(hidden, s.DownWeightQ, s.DownScales, s.DownBiases,
- nil, idxFlat, true, s.DownGroupSize, s.DownBits, s.DownMode, doSort)
+ nil, idxFlat, true, s.DownGroupSize, s.DownBits, s.DownMode,
+ s.DownGlobalScales, doSort)
} else {
down = mlx.GatherMM(hidden, s.DownWeight, nil, idxFlat, doSort)
}
diff --git a/x/models/qwen3_5/qwen3_5_test.go b/x/models/qwen3_5/qwen3_5_test.go
index ea35f782a..b667567a4 100644
--- a/x/models/qwen3_5/qwen3_5_test.go
+++ b/x/models/qwen3_5/qwen3_5_test.go
@@ -1,6 +1,7 @@
package qwen3_5
import (
+ "math"
"testing"
"github.com/ollama/ollama/x/internal/mlxtest"
@@ -121,6 +122,129 @@ func TestSupportsGatherQMM(t *testing.T) {
}
}
+// Gate and up fuse into one quantized bank when their global scales agree,
+// since gather_qmm applies one scale per expert across the whole bank row.
+// Scales that disagree cannot share a bank and stay on separate projections.
+// Either way the result has to match the dequantized weights.
+func TestLoadSwitchMLPGlobalScaleFusion(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ const experts, width, group = 4, 64, 16
+ cfg := &Config{
+ HiddenSize: width,
+ NumExperts: experts,
+ QuantGroupSize: group,
+ QuantBits: 4,
+ QuantMode: "nvfp4",
+ NumExpertsPerTok: 2,
+ }
+ prefix := "model.layers.0"
+
+ // Nonzero nvfp4 payloads: packed fp4 codes cycle through all 16 values
+ // and every group scale is a power of two, so the dequantized weights
+ // are exact and the dense path is a faithful reference.
+ packed := make([]uint32, experts*width*width/8)
+ for i := range packed {
+ for j := range 8 {
+ packed[i] |= uint32((i*8+j)%16) << (4 * j)
+ }
+ }
+ scaleBits := make([]uint8, experts*width*width/group)
+ for i := range scaleBits {
+ exp := (i/(width/group)+i%(width/group))%4 - 1
+ scaleBits[i] = uint8((exp + 7) << 3)
+ }
+
+ for _, tt := range []struct {
+ name string
+ upScales []float32
+ wantFused bool
+ }{
+ {"matching scales fuse", []float32{0.5, 1, 2, 4}, true},
+ {"differing scales stay separate", []float32{4, 2, 1, 0.5}, false},
+ } {
+ func() {
+ buildTensors := func() map[string]*mlx.Array {
+ tensors := make(map[string]*mlx.Array)
+ for _, proj := range []string{"gate_proj", "up_proj", "down_proj"} {
+ globalScales := []float32{0.5, 1, 2, 4}
+ if proj == "up_proj" {
+ globalScales = tt.upScales
+ }
+ key := prefix + ".mlp.experts." + proj + ".weight"
+ tensors[key] = mlx.FromValues(packed, experts, width, width/8)
+ tensors[key+"_scale"] = mlx.FromValues(scaleBits, experts, width, width/group)
+ tensors[key+".global_scale"] = mlx.FromValues(globalScales, experts)
+ }
+ return tensors
+ }
+
+ switchMLP, err := loadSwitchMLP(buildTensors(), cfg, true, prefix)
+ if err != nil {
+ t.Fatalf("%s: loadSwitchMLP() failed: %v", tt.name, err)
+ }
+ if tt.wantFused {
+ if switchMLP.GateUpWeightQ == nil {
+ t.Fatalf("%s: gate and up sharing a global scale were not fused", tt.name)
+ }
+ if switchMLP.GateUpGlobalScales == nil {
+ t.Fatalf("%s: the fused bank dropped its global scale", tt.name)
+ }
+ } else {
+ if switchMLP.GateUpWeightQ != nil {
+ t.Fatalf("%s: gate and up with differing global scales were fused", tt.name)
+ }
+ if switchMLP.GateWeightQ == nil || switchMLP.UpWeightQ == nil {
+ t.Fatalf("%s: separate expert projections did not remain quantized", tt.name)
+ }
+ if switchMLP.GateGlobalScales == nil || switchMLP.UpGlobalScales == nil {
+ t.Fatalf("%s: separate expert global scales were not retained", tt.name)
+ }
+ }
+ if switchMLP.DownWeightQ == nil || switchMLP.DownGlobalScales == nil {
+ t.Fatalf("%s: the down projection lost its quantized bank or global scale", tt.name)
+ }
+
+ xValues := make([]float32, width)
+ for i := range xValues {
+ xValues[i] = float32(i%7-3) / 8
+ }
+ x := mlx.FromValues(xValues, 1, 1, width).AsType(mlx.DTypeBFloat16)
+ indices := mlx.FromValues([]int32{0, 3}, 1, 1, int(cfg.NumExpertsPerTok))
+ out := switchMLP.Forward(x, indices, cfg)
+
+ // The dense path dequantizes the same weights (global scales
+ // included) at load, giving a reference for the quantized
+ // path's rounding.
+ dense, err := loadSwitchMLP(buildTensors(), cfg, false, prefix)
+ if err != nil {
+ t.Fatalf("%s: loadSwitchMLP(useQuantized=false) failed: %v", tt.name, err)
+ }
+ if dense.GateWeightQ != nil || dense.UpWeightQ != nil || dense.DownWeightQ != nil {
+ t.Fatalf("%s: dense load kept quantized expert banks", tt.name)
+ }
+ ref := dense.Forward(x, indices, cfg)
+
+ mlx.Eval(out, ref)
+ gotVals := out.AsType(mlx.DTypeFloat32).Floats()
+ wantVals := ref.AsType(mlx.DTypeFloat32).Floats()
+ if len(gotVals) != len(wantVals) {
+ t.Fatalf("%s: output length = %d, want %d", tt.name, len(gotVals), len(wantVals))
+ }
+ for i, got := range gotVals {
+ if math.IsNaN(float64(got)) || math.IsInf(float64(got), 0) {
+ t.Fatalf("%s: output[%d] = %v, want finite", tt.name, i, got)
+ }
+ delta := math.Abs(float64(got - wantVals[i]))
+ tolerance := 0.02 * math.Max(math.Abs(float64(wantVals[i])), 1)
+ if delta > tolerance {
+ t.Fatalf("%s: output[%d] = %v, want %v (delta %v > %v)", tt.name, i, got, wantVals[i], delta, tolerance)
+ }
+ }
+ }()
+ }
+ })
+}
+
func TestResolveTensorPathLayout(t *testing.T) {
dummy := mlx.New("dummy")
diff --git a/x/models/qwen4_exp/blocks.go b/x/models/qwen4_exp/blocks.go
index 76bcd5b55..f48046762 100644
--- a/x/models/qwen4_exp/blocks.go
+++ b/x/models/qwen4_exp/blocks.go
@@ -176,7 +176,7 @@ func (m *sparseMoE) Forward(x *mlx.Array, cfg *Config) *mlx.Array {
var gateUp *mlx.Array
if m.GateUpScales != nil {
gateUp = mlx.GatherQMM(xFlat, m.GateUpExperts, m.GateUpScales, m.GateUpBiases,
- nil, indexFlat, true, m.GateUpGroup, m.GateUpBits, m.GateUpMode, doSort)
+ nil, indexFlat, true, m.GateUpGroup, m.GateUpBits, m.GateUpMode, nil, doSort)
} else {
gateUp = mlx.GatherMM(xFlat, m.GateUpExperts, nil, indexFlat, doSort)
}
@@ -185,7 +185,7 @@ func (m *sparseMoE) Forward(x *mlx.Array, cfg *Config) *mlx.Array {
var down *mlx.Array
if m.DownScales != nil {
down = mlx.GatherQMM(hidden, m.DownExperts, m.DownScales, m.DownBiases,
- nil, indexFlat, true, m.DownGroup, m.DownBits, m.DownMode, doSort)
+ nil, indexFlat, true, m.DownGroup, m.DownBits, m.DownMode, nil, doSort)
} else {
down = mlx.GatherMM(hidden, m.DownExperts, nil, indexFlat, doSort)
}