MLX: make Qwen3.8 Flash Next memory efficient (#18078)

* MLX: reduce Qwen3.8 Flash Next memory use

For NVFP4 creation, retain source precision for sensitive QSA projections
and non-expert MTP weights. Keep routed experts and PLE at NVFP4, and
promote other eligible weights to MXFP8.

Keep NVFP4 PLE tables host-backed, transferring only selected packed rows
and their scales to MLX. Honor scalar and per-expert NVFP4 global scales
in MoE, and per-shard global scales in host-backed PLE.

Use compressed QSA block selections in fused indexed Metal attention for
long prefill batches, retaining the graph fallback. Co-locate component
loading and forward methods, with explicit quantization and cache ownership.

* mlx: skip materializing host-backed tensors

Let models exclude tensors already owned by host storage from MLX loading.
Avoid allocating and discarding the full Qwen PLE tables at startup while
preserving the resident fallback.

* address comments
This commit is contained in:
Daniel Hiltgen authored and GitHub committed 2026-11-06 13:39:21 -08:00
1 parent eaf3f28586
commit c053d1e985
26 files changed
+2118 -912

No files matched your search

+38 -3
View File
@@ -12,11 +12,12 @@ func newQwen4ExpImportTransform(_ json.RawMessage) (quantizePolicy, error) {
}
func (qwen4ExpImportTransform) quantizationType(name string, shape []int32, quantize string) string {
quantize = normalizeQuantType(quantize)
// PLE is a hashed n-gram feature table rather than the model's token
// embedding. It dominates the checkpoint size, and its lookup path supports
// row-wise dequantization, so quantize its shards at the requested type.
// embedding. Its lookup path dequantizes selected rows, so quantize its
// shards at the requested type.
if qwen4ExpIsPLEEmbeddingShard(name) {
quantize = normalizeQuantType(quantize)
if len(shape) == 2 && isAligned(shape, quantize) {
return quantize
}
@@ -28,6 +29,25 @@ func (qwen4ExpImportTransform) quantizationType(name string, shape []int32, quan
if qwen35IsLowRankProjection(name) {
return ""
}
if quantize == "nvfp4" {
// Keep QSA Q/K/V and the indexer projection on the validated BF16 path.
// Keep the whole draft-side control path at source precision as well.
if qwen4ExpIsSensitiveQSA(name) ||
(strings.HasPrefix(name, "mtp.") && !qwen4ExpIsRoutedExpert(name)) {
return ""
}
if isEmbedTokensWeight(name) {
return promoteEmbedding(shape, quantize)
}
// Routed experts dominate the remaining model size and have validated NVFP4
// kernels. Use MXFP8 for the other eligible target weights to avoid the
// long-context quality loss seen with blanket NVFP4.
if !qwen4ExpIsRoutedExpert(name) {
return GetTensorQuantization(name, shape, "mxfp8")
}
}
return GetTensorQuantization(name, shape, quantize)
}
@@ -35,3 +55,18 @@ func qwen4ExpIsPLEEmbeddingShard(name string) bool {
return strings.Contains(name, ".ple.ple_embedding.ngram_embedding.shard_") &&
strings.HasSuffix(name, ".weight")
}
func qwen4ExpIsRoutedExpert(name string) bool {
return (strings.HasPrefix(name, "model.language_model.layers.") ||
strings.HasPrefix(name, "mtp.layers.")) &&
strings.Contains(name, ".mlp.experts.")
}
func qwen4ExpIsSensitiveQSA(name string) bool {
return strings.HasPrefix(name, "model.language_model.layers.") &&
strings.Contains(name, ".self_attn.") &&
(strings.HasSuffix(name, ".q_proj.weight") ||
strings.HasSuffix(name, ".k_proj.weight") ||
strings.HasSuffix(name, ".v_proj.weight") ||
strings.HasSuffix(name, ".indexer.index_qk_proj.weight"))
}
+51 -2
View File
@@ -13,18 +13,25 @@ func TestQwen4ExpQuantizationType(t *testing.T) {
want string
}{
{
name: "PLE shard",
name: "PLE shard uses requested NVFP4",
tensor: "model.language_model.layers.1.ple.ple_embedding.ngram_embedding.shard_0.weight",
shape: []int32{156250, 2560},
quantize: "nvfp4",
want: "nvfp4",
},
{
name: "PLE shard preserves explicit MXFP8 request",
tensor: "model.language_model.layers.1.ple.ple_embedding.ngram_embedding.shard_0.weight",
shape: []int32{156250, 2560},
quantize: "mxfp8",
want: "mxfp8",
},
{
name: "token embedding",
tensor: "model.language_model.embed_tokens.weight",
shape: []int32{248320, 2560},
quantize: "nvfp4",
want: "",
want: "mxfp8",
},
{
name: "low rank projection",
@@ -38,8 +45,50 @@ func TestQwen4ExpQuantizationType(t *testing.T) {
tensor: "model.language_model.layers.0.linear_attn.out_proj.weight",
shape: []int32{5120, 3072},
quantize: "nvfp4",
want: "mxfp8",
},
{
name: "QSA query projection",
tensor: "model.language_model.layers.3.self_attn.q_proj.weight",
shape: []int32{12288, 2560},
quantize: "nvfp4",
want: "",
},
{
name: "MTP routed expert",
tensor: "mtp.layers.0.mlp.experts.0.down_proj.weight",
shape: []int32{2560, 1024},
quantize: "nvfp4",
want: "nvfp4",
},
{
name: "MTP control path",
tensor: "mtp.layers.0.self_attn.q_proj.weight",
shape: []int32{12288, 2560},
quantize: "nvfp4",
want: "",
},
{
name: "main routed expert",
tensor: "model.language_model.layers.0.mlp.experts.0.down_proj.weight",
shape: []int32{2560, 1024},
quantize: "nvfp4",
want: "nvfp4",
},
{
name: "QSA query projection mxfp8",
tensor: "model.language_model.layers.3.self_attn.q_proj.weight",
shape: []int32{12288, 2560},
quantize: "mxfp8",
want: "mxfp8",
},
{
name: "hyperconnection projection",
tensor: "model.language_model.layers.0.attn_hyper_connection.block_inject_weight.weight",
shape: []int32{2560, 2560},
quantize: "nvfp4",
want: "mxfp8",
},
}
for _, tt := range tests {
+7
View File
@@ -60,6 +60,13 @@ func (td *TensorData) Reader() io.Reader {
return td.reader
}
// Offset returns the tensor's byte offset in its backing file or byte reader.
// It allows a caller mapping that same source to use the validated tensor range.
func (td *TensorData) Offset() int64 {
_, offset, _ := td.reader.Outer()
return offset
}
// safetensorsHeader builds the JSON header for a minimal safetensors blob
// containing a single tensor keyed by its name.
func (td *TensorData) safetensorsHeader() []byte {
+7
View File
@@ -306,6 +306,13 @@ func TestGetTensor(t *testing.T) {
if len(rawData) != 16 {
t.Errorf("raw data length = %d, want 16", len(rawData))
}
fileData, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if got := fileData[td.Offset() : td.Offset()+td.Size]; !bytes.Equal(got, data) {
t.Errorf("tensor range at offset %d = %v, want %v", td.Offset(), got, data)
}
}
func TestGetTensor_NotFound(t *testing.T) {
+272
View File
@@ -0,0 +1,272 @@
package mlx
import (
"fmt"
"math"
)
const indexedBlockAttentionMetalSource = `
uint row = threadgroup_position_in_grid.y;
uint simd_group = simdgroup_index_in_threadgroup;
uint lane = thread_index_in_simdgroup;
constexpr int SIMDGroups = 32;
constexpr int SIMDWidth = 32;
constexpr int ValuesPerLane = D / SIMDWidth;
thread float query[ValuesPerLane];
thread float values[ValuesPerLane];
threadgroup float outputs[SIMDGroups * SIMDWidth];
threadgroup float max_scores[SIMDGroups];
threadgroup float sum_scores[SIMDGroups];
int query_index = int(row % QueryLength);
int batch_head = int(row / QueryLength);
int batch = batch_head / QueryHeads;
int query_head = batch_head - batch * QueryHeads;
int kv_head = query_head / (QueryHeads / KVHeads);
int query_end = query_ends[batch * QueryLength + query_index];
int key_count = int(key_length);
auto query_ptr = q + ((batch_head * QueryLength + query_index) * D) + lane * ValuesPerLane;
auto output_ptr = out + ((batch_head * QueryLength + query_index) * D) + simd_group * ValuesPerLane;
for (int i = 0; i < ValuesPerLane; ++i) {
query[i] = float(scale) * static_cast<float>(query_ptr[i]);
values[i] = 0.0f;
}
int blocks_offset = (batch * QueryLength + query_index) * TopKBlocks;
float max_score = -3.402823466e+38F;
float sum_score = 0.0f;
// Each SIMD group owns an interleaved subset of the selected tokens and
// accumulates an independent online-softmax state.
for (int selected = int(simd_group); selected < TopKBlocks * BlockSize; selected += SIMDGroups) {
int block_slot = selected / BlockSize;
int block_offset = selected - block_slot * BlockSize;
int block = block_indices[blocks_offset + block_slot];
int key_index = block * BlockSize + block_offset;
bool valid = block >= 0 && key_index < key_count && key_index < query_end;
float score = -INFINITY;
if (valid) {
auto key_ptr = k + (((batch * KVHeads + kv_head) * key_count + key_index) * D) + lane * ValuesPerLane;
score = 0.0f;
for (int i = 0; i < ValuesPerLane; ++i) {
score += query[i] * static_cast<float>(key_ptr[i]);
}
score = simd_sum(score);
}
float next_max = metal::max(max_score, score);
float previous_factor = fast::exp(max_score - next_max);
float weight = valid ? fast::exp(score - next_max) : 0.0f;
max_score = next_max;
sum_score = sum_score * previous_factor + weight;
if (valid) {
auto value_ptr = v + (((batch * KVHeads + kv_head) * key_count + key_index) * D) + lane * ValuesPerLane;
for (int i = 0; i < ValuesPerLane; ++i) {
values[i] = values[i] * previous_factor + weight * static_cast<float>(value_ptr[i]);
}
} else {
for (int i = 0; i < ValuesPerLane; ++i) {
values[i] *= previous_factor;
}
}
}
// QSA always attends the incomplete compression block after the selected
// complete blocks. At most BlockSize-1 SIMD groups have a valid tail token.
int tail_start = (query_end / BlockSize) * BlockSize;
int tail_index = tail_start + int(simd_group);
bool valid_tail = tail_index < query_end && tail_index < key_count;
if (valid_tail) {
auto key_ptr = k + (((batch * KVHeads + kv_head) * key_count + tail_index) * D) + lane * ValuesPerLane;
float score = 0.0f;
for (int i = 0; i < ValuesPerLane; ++i) {
score += query[i] * static_cast<float>(key_ptr[i]);
}
score = simd_sum(score);
float next_max = metal::max(max_score, score);
float previous_factor = fast::exp(max_score - next_max);
float weight = fast::exp(score - next_max);
max_score = next_max;
sum_score = sum_score * previous_factor + weight;
auto value_ptr = v + (((batch * KVHeads + kv_head) * key_count + tail_index) * D) + lane * ValuesPerLane;
for (int i = 0; i < ValuesPerLane; ++i) {
values[i] = values[i] * previous_factor + weight * static_cast<float>(value_ptr[i]);
}
}
if (lane == 0) {
max_scores[simd_group] = max_score;
sum_scores[simd_group] = sum_score;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
max_score = max_scores[lane];
float row_max = simd_max(max_score);
float row_factor = fast::exp(max_score - row_max);
float row_sum = simd_sum(sum_scores[lane] * row_factor);
// Transpose the lane-by-SIMD-group accumulators through threadgroup memory.
// Each SIMD group then reduces and writes one contiguous output segment.
for (int i = 0; i < ValuesPerLane; ++i) {
outputs[lane * SIMDWidth + simd_group] = values[i];
threadgroup_barrier(mem_flags::mem_threadgroup);
values[i] = simd_sum(outputs[simd_group * SIMDWidth + lane] * row_factor);
values[i] /= row_sum;
threadgroup_barrier(mem_flags::mem_threadgroup);
}
if (lane == 0) {
for (int i = 0; i < ValuesPerLane; ++i) {
output_ptr[i] = static_cast<InT>(values[i]);
}
}
`
var indexedBlockAttention = &gpuKernel{
name: "indexed_block_scaled_dot_product_attention",
inputs: []string{"q", "k", "v", "block_indices", "query_ends", "scale", "key_length", "block_size"},
outputs: []string{"out"},
metal: gpuSource{
source: indexedBlockAttentionMetalSource,
header: "#include <metal_simdgroup>\nusing namespace metal;\n",
},
fallback: func(launch gpuLaunch) []*Array {
in := launch.inputs
return []*Array{indexedBlockScaledDotProductAttentionGraph(
in[0], in[1], in[2], in[3], in[4], int(in[7].Int()), in[5].Float(),
)}
},
}
// The graph path is faster for small query batches. At 1024 tokens the
// block-indexed kernel pulls ahead and avoids the graph's context-dependent
// intermediate growth.
const indexedBlockAttentionMinQueryLength = 1024
func indexedTokenScaledDotProductAttentionGraph(q, k, v, indices, valid *Array, scale float32) *Array {
outputType := q.DType()
B, queryHeads, L, D := int32(q.Dim(0)), int32(q.Dim(1)), int32(q.Dim(2)), int32(q.Dim(3))
kvHeads, K := int32(k.Dim(1)), int32(k.Dim(2))
repeats := queryHeads / kvHeads
offsets := make([]int32, B)
for i := range offsets {
offsets[i] = int32(i) * K
}
logical := Add(indices, FromValues(offsets, int(B), 1, 1))
gather := func(history *Array) *Array {
flattened := Reshape(Transpose(history, 1, 0, 2, 3), kvHeads, B*K, D)
return Transpose(Take(flattened, logical, 1), 1, 0, 2, 3, 4)
}
selectedK, selectedV := gather(k), gather(v)
qr := Reshape(q, B, kvHeads, repeats, L, 1, D)
kr := Transpose(ExpandDims(selectedK, 2), 0, 1, 2, 3, 5, 4)
scores := Squeeze(Matmul(qr.AsType(DTypeFloat32), kr.AsType(DTypeFloat32)), 4)
scores = MulScalar(scores, scale)
mask := ExpandDims(ExpandDims(valid, 1), 1)
fill := AddScalar(Zeros(scores.DType(), scores.Dims()...), -float32(math.MaxFloat32))
scores = Where(mask, scores, fill)
probs := SoftmaxAxis(scores, -1, true)
vr := ExpandDims(selectedV.AsType(DTypeFloat32), 2)
out := Matmul(ExpandDims(probs, 4), vr)
out = Squeeze(out, 4)
return Reshape(out, B, queryHeads, L, D).AsType(outputType)
}
func indexedBlockScaledDotProductAttentionGraph(q, k, v, blockIndices, queryEnds *Array, blockSize int, scale float32) *Array {
B, L, topK := int32(blockIndices.Dim(0)), int32(blockIndices.Dim(1)), int32(blockIndices.Dim(2))
keyLength := k.Dim(2)
offsets := Reshape(Arange(0, float64(blockSize), 1, DTypeInt32), 1, 1, 1, int32(blockSize))
indices := Add(MulScalar(ExpandDims(blockIndices, -1), float32(blockSize)), offsets)
validBlocks := ExpandDims(blockIndices.Greater(FromValue(-1)), -1)
queryLimit := ExpandDims(ExpandDims(queryEnds, -1), -1)
valid := Mul(validBlocks.AsType(DTypeInt32), indices.Less(queryLimit).AsType(DTypeInt32))
valid = Mul(valid, indices.Less(FromValue(keyLength)).AsType(DTypeInt32))
indices = Reshape(indices, B, L, topK*int32(blockSize))
valid = Reshape(valid, B, L, topK*int32(blockSize))
tailWidth := blockSize - 1
if tailWidth > 0 {
tailOffsets := Reshape(Arange(0, float64(tailWidth), 1, DTypeInt32), 1, 1, int32(tailWidth))
tailStart := MulScalar(ExpandDims(FloorDivideScalar(queryEnds, int32(blockSize)), -1), float32(blockSize))
tail := Add(tailStart, tailOffsets)
tailValid := Mul(tail.Less(ExpandDims(queryEnds, -1)).AsType(DTypeInt32), tail.Less(FromValue(keyLength)).AsType(DTypeInt32))
indices = Concatenate([]*Array{indices, tail}, -1)
valid = Concatenate([]*Array{valid, tailValid}, -1)
}
validMask := valid.Greater(FromValue(0))
indices = Where(validMask, indices, Zeros(DTypeInt32, indices.Dims()...)).AsType(DTypeInt32)
return indexedTokenScaledDotProductAttentionGraph(q, k, v, indices, validMask, scale)
}
// IndexedBlockScaledDotProductAttention attends to a per-query list of
// complete K/V blocks followed by that query's incomplete causal block.
// q is [B, QH, L, D], k and v are [B, KVH, K, D], blockIndices is
// [B, L, TopK], and queryEnds is [B, L]. Negative block indices are ignored.
// A finite initial online-softmax maximum keeps SIMD groups with no valid
// selected token from evaluating -Inf - -Inf.
func IndexedBlockScaledDotProductAttention(q, k, v, blockIndices, queryEnds *Array, blockSize int, scale float32) *Array {
if q == nil || k == nil || v == nil || blockIndices == nil || queryEnds == nil ||
q.NumDims() != 4 || k.NumDims() != 4 || v.NumDims() != 4 ||
blockIndices.NumDims() != 3 || queryEnds.NumDims() != 2 || blockSize <= 0 {
panic("mlx.IndexedBlockScaledDotProductAttention: invalid inputs")
}
B, queryHeads, L, D := q.Dim(0), q.Dim(1), q.Dim(2), q.Dim(3)
kvHeads, keyLength := k.Dim(1), k.Dim(2)
if k.Dim(0) != B || v.Dim(0) != B || v.Dim(1) != kvHeads || v.Dim(2) != keyLength ||
k.Dim(3) != D || v.Dim(3) != D || queryHeads%kvHeads != 0 ||
blockIndices.Dim(0) != B || blockIndices.Dim(1) != L ||
queryEnds.Dim(0) != B || queryEnds.Dim(1) != L {
panic(fmt.Sprintf(
"mlx.IndexedBlockScaledDotProductAttention: incompatible shapes q=%v k=%v v=%v blocks=%v queryEnds=%v",
q.Dims(), k.Dims(), v.Dims(), blockIndices.Dims(), queryEnds.Dims(),
))
}
if !MetalIsAvailable() || L < indexedBlockAttentionMinQueryLength || blockSize > 32 || D%32 != 0 ||
q.DType() != k.DType() || q.DType() != v.DType() ||
(q.DType() != DTypeBFloat16 && q.DType() != DTypeFloat16) ||
blockIndices.DType() != DTypeInt32 || queryEnds.DType() != DTypeInt32 {
return indexedBlockScaledDotProductAttentionGraph(q, k, v, blockIndices, queryEnds, blockSize, scale)
}
return indexedBlockScaledDotProductAttentionMetal(q, k, v, blockIndices, queryEnds, blockSize, scale)
}
func indexedBlockScaledDotProductAttentionMetal(q, k, v, blockIndices, queryEnds *Array, blockSize int, scale float32) *Array {
B, queryHeads, L, D := q.Dim(0), q.Dim(1), q.Dim(2), q.Dim(3)
kvHeads, keyLength, topK := k.Dim(1), k.Dim(2), blockIndices.Dim(2)
outs := indexedBlockAttention.run(gpuLaunch{
dtypes: []gpuDTypeArg{{"InT", q.DType()}},
ints: []gpuIntArg{
{"D", D},
{"QueryLength", L},
{"QueryHeads", queryHeads},
{"KVHeads", kvHeads},
{"BlockSize", blockSize},
{"TopKBlocks", topK},
},
outputs: []gpuOutputSpec{{
"INDEXED_BLOCK_SCALED_DOT_PRODUCT_ATTENTION",
[]int32{int32(B), int32(queryHeads), int32(L), int32(D)},
q.DType(),
}},
grid: [3]int{1024, B * queryHeads * L, 1},
threadGroup: [3]int{1024, 1, 1},
inputs: []*Array{
q, k, v, blockIndices, queryEnds,
FromValue(scale), FromValue(keyLength), FromValue(blockSize),
},
})
return outs[0]
}
+81
View File
@@ -0,0 +1,81 @@
package mlx
import (
"math"
"testing"
"github.com/ollama/ollama/mlx/mlxthread/mlxthreadtest"
)
func TestIndexedBlockScaledDotProductAttentionMatchesGraph(t *testing.T) {
for _, tc := range []struct {
name string
dtype DType
headDim, keyLength, blockSize int
causalTail bool
}{
{"complete blocks", DTypeBFloat16, 32, 64, 4, false},
{"bf16 causal tails", DTypeBFloat16, 256, 37, 16, true},
{"fp16 causal tails", DTypeFloat16, 256, 37, 16, true},
} {
t.Run(tc.name, func(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
if !MetalIsAvailable() {
t.Skip("requires Metal kernel")
}
Scoped(func() {
const (
batch = 2
queryHeads = 4
kvHeads = 2
queryLength = indexedBlockAttentionMinQueryLength
)
keyLength, headDim, blockSize := tc.keyLength, tc.headDim, tc.blockSize
topK := keyLength / blockSize
q := patternArray(tc.dtype, []int{batch, queryHeads, queryLength, headDim}, 0.1, 0.03, 7, 19)
k := patternArray(tc.dtype, []int{batch, kvHeads, keyLength, headDim}, -0.05, 0.02, 5, 17)
v := patternArray(tc.dtype, []int{batch, kvHeads, keyLength, headDim}, 0.2, 0.04, 3, 13)
blockValues := make([]int32, batch*queryLength*topK)
queryEndValues := make([]int32, batch*queryLength)
for b := range batch {
for row := range queryLength {
end := keyLength
if tc.causalTail {
end = (row+b)%keyLength + 1
}
i := (b*queryLength + row) * topK
for j := range topK {
blockValues[i+j] = -1
if j%2 == 0 && j/2 < end/blockSize {
blockValues[i+j] = int32(j / 2)
}
}
queryEndValues[b*queryLength+row] = int32(end)
}
}
blocks := FromValues(blockValues, batch, queryLength, topK)
queryEnds := FromValues(queryEndValues, batch, queryLength)
scale := float32(1 / math.Sqrt(float64(headDim)))
got := IndexedBlockScaledDotProductAttention(q, k, v, blocks, queryEnds, blockSize, scale)
if got.name != "INDEXED_BLOCK_SCALED_DOT_PRODUCT_ATTENTION" {
t.Fatalf("executed %s, want indexed Metal kernel", got.name)
}
got = got.AsType(DTypeFloat32)
want := indexedBlockScaledDotProductAttentionGraph(q, k, v, blocks, queryEnds, blockSize, scale).AsType(DTypeFloat32)
Eval(got, want)
gotValues, wantValues := got.Floats(), want.Floats()
for i := range wantValues {
if math.IsNaN(float64(gotValues[i])) || math.IsInf(float64(gotValues[i]), 0) {
t.Fatalf("out[%d] = %v, want finite output", i, gotValues[i])
}
if diff := float32(math.Abs(float64(gotValues[i] - wantValues[i]))); diff > 0.005 {
t.Fatalf("out[%d] = %v, want %v (diff %v)", i, gotValues[i], wantValues[i], diff)
}
}
})
})
})
}
}
+7
View File
@@ -31,6 +31,13 @@ type Model interface {
MaxContextLength() int
}
// SkippedTensorsModel identifies checkpoint tensors to exclude from MLX loading.
// Names use the original safetensors namespace, including any quantization
// companions. The model is responsible for accessing any required skipped tensors.
type SkippedTensorsModel interface {
SkippedTensorNames() []string
}
// DraftModel is an auxiliary model alongside a target that proposes speculative
// tokens.
type DraftModel interface {
-203
View File
@@ -1,203 +0,0 @@
package qwen4_exp
import (
"math"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/nn"
)
func (l *Layer) Forward(x *mlx.Array, b *batch.Batch, c, side cache.Cache, positions, ropePositions *mlx.Array, cfg *Config) *mlx.Array {
branch, state := l.AttentionConnection.Prepare(x, cfg)
if l.Linear != nil {
branch = l.Linear.Forward(branch, b, c, cfg)
} else {
branch = l.Attention.Forward(branch, b, c, side, positions, ropePositions, cfg)
}
x = l.AttentionConnection.Inject(state, branch, cfg)
branch, state = l.MLPConnection.Prepare(x, cfg)
branch = l.MoE.Forward(branch, cfg)
return l.MLPConnection.Inject(state, branch, cfg)
}
func (a *linearAttention) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, cfg *Config) *mlx.Array {
dims := x.Dims()
B, L := int32(dims[0]), int32(dims[1])
valueDim := cfg.LinearNumValueHeads * cfg.LinearValueHeadDim
qkv := a.QKV.Forward(x)
z := mlx.Reshape(a.Z.Forward(x), B, L, cfg.LinearNumValueHeads, cfg.LinearValueHeadDim)
ba := mlx.Concatenate([]*mlx.Array{a.B.Forward(x), a.A.Forward(x)}, -1)
convTail := cfg.LinearConvKernelDim - 1
options := []nn.RecurrentOption{nn.WithConvSiLU()}
var recurrent *cache.RecurrentCache
if value, ok := c.(*cache.RecurrentCache); ok {
recurrent = value
options = append(options, nn.WithRecurrentHistory(recurrent.Get(b, x.DType())))
if splits := recurrent.SnapshotSplits(int(L)); len(splits) > 0 {
options = append(options, nn.WithSnapshotSplits(splits))
}
} else {
options = append(options, nn.WithRecurrentState(
mlx.Zeros(x.DType(), int(B), int(convTail), qkv.Dim(2)),
mlx.Zeros(mlx.DTypeFloat32, int(B), int(cfg.LinearNumValueHeads), int(cfg.LinearValueHeadDim), int(cfg.LinearKeyHeadDim)),
))
}
convOut, convState := nn.CausalConv1D(b, qkv, a.Conv, int(convTail), options...)
out, deltaState := nn.GatedDelta(b, convOut, ba, a.DtBias, a.AExp, options...)
outType := out.DType()
out = mlx.RMSNormFn(out, a.NormWeight, cfg.RMSNormEps)
// Qwen 4 uses a sigmoid Gated DeltaNet output gate rather than the SiLU
// gate used by Qwen3.5.
gate := mlx.Sigmoid(z.AsType(mlx.DTypeFloat32))
out = mlx.Mul(out.AsType(mlx.DTypeFloat32), gate).AsType(outType)
out = a.Out.Forward(mlx.Reshape(out, B, L, valueDim))
if recurrent != nil {
recurrent.Put(b, convState, deltaState)
}
return out
}
func (a *fullAttention) Forward(x *mlx.Array, b *batch.Batch, c, side cache.Cache, positions, ropePositions *mlx.Array, cfg *Config) *mlx.Array {
dims := x.Dims()
B, L := int32(dims[0]), int32(dims[1])
qg := mlx.Reshape(a.QProj.Forward(x), B, L, cfg.NumAttentionHeads, cfg.HeadDim*2)
q := mlx.SliceStartStop(qg, []int32{0, 0, 0, 0}, []int32{B, L, cfg.NumAttentionHeads, cfg.HeadDim})
gate := mlx.SliceStartStop(qg, []int32{0, 0, 0, cfg.HeadDim}, []int32{B, L, cfg.NumAttentionHeads, cfg.HeadDim * 2})
gate = mlx.Reshape(gate, B, L, cfg.NumAttentionHeads*cfg.HeadDim)
k := mlx.Reshape(a.KProj.Forward(x), B, L, cfg.NumKeyValueHeads, cfg.HeadDim)
v := mlx.Reshape(a.VProj.Forward(x), B, L, cfg.NumKeyValueHeads, cfg.HeadDim)
q = a.QNorm.Forward(q, cfg.RMSNormEps)
k = a.KNorm.Forward(k, cfg.RMSNormEps)
q = mlx.Transpose(q, 0, 2, 1, 3)
k = mlx.Transpose(k, 0, 2, 1, 3)
v = mlx.Transpose(v, 0, 2, 1, 3)
cos, sin := qsaRopeCosSin(cfg, ropePositions)
q = applyQwenRoPE(q, cos, sin, cfg.RopeDim)
k = applyQwenRoPE(k, cos, sin, cfg.RopeDim)
projected := a.Indexer.QKProj.Forward(x)
indexQ := mlx.SliceStartStop(projected,
[]int32{0, 0, 0},
[]int32{B, L, cfg.IndexerNumHeads * cfg.IndexerHeadDim},
)
rawIndexK := mlx.SliceStartStop(projected,
[]int32{0, 0, cfg.IndexerNumHeads * cfg.IndexerHeadDim},
[]int32{B, L, (cfg.IndexerNumHeads + cfg.IndexerKVHeads) * cfg.IndexerHeadDim},
)
indexQ = mlx.Reshape(indexQ, B, L, cfg.IndexerNumHeads, cfg.IndexerHeadDim)
indexQ = a.Indexer.QNorm.Forward(indexQ, cfg.RMSNormEps)
indexQ = mlx.Transpose(indexQ, 0, 2, 1, 3)
indexQ = applyQwenRoPE(indexQ, cos, sin, cfg.RopeDim)
rawIndexK = mlx.Transpose(
mlx.Reshape(rawIndexK, B, L, cfg.IndexerKVHeads, cfg.IndexerHeadDim),
0, 2, 1, 3,
)
var mainHistory, indexHistory *nn.KVHistory
if c != nil {
mainHistory = c.(cache.Attention).Update(b, k, v)
if side == nil {
panic("QSA side cache is missing")
}
indexHistory = side.(cache.Attention).Update(b, rawIndexK, ropePositions)
}
var out *mlx.Array
keyLength := L
for _, offset := range b.SeqOffsets {
keyLength = max(keyLength, offset+L)
}
if mainHistory == nil {
out = nn.ScaledDotProductAttention(b, q, cfg.Scale,
nn.WithKV(k, v, b.SeqQueryLens), nn.WithMask(nn.CausalMask()))
} else if keyLength <= cfg.IndexerBudget {
// QSA selects the entire visible history within the indexer budget.
out = nn.ScaledDotProductAttention(b, q, cfg.Scale,
nn.WithKVHistory(mainHistory), nn.WithMask(nn.CausalMask()))
} else {
compressed := qsaCompressedKeys(indexHistory.K(), indexHistory.V(), a.Indexer, cfg)
scores := mlx.Matmul(indexQ.AsType(mlx.DTypeFloat32), mlx.Transpose(compressed.AsType(mlx.DTypeFloat32), 0, 1, 3, 2))
scores = mlx.DivScalar(mlx.Sum(mlx.ReLU(scores), 1, false), float32(math.Sqrt(float64(cfg.IndexerHeadDim))))
logical, valid := qsaLogicalIndices(scores, b, keyLength, cfg)
out = qsaSparseAttention(q, mainHistory, logical, valid, cfg)
}
out = mlx.Reshape(mlx.Transpose(out, 0, 2, 1, 3), B, L, cfg.NumAttentionHeads*cfg.HeadDim)
out = mlx.Mul(out, mlx.Sigmoid(gate))
return a.OProj.Forward(out)
}
func splitLastAxis(a *mlx.Array) (*mlx.Array, *mlx.Array) {
dims := a.Dims()
start := make([]int32, len(dims))
stop := make([]int32, len(dims))
for i, dim := range dims {
stop[i] = int32(dim)
}
mid := int32(dims[len(dims)-1]) / 2
leftStop := append([]int32(nil), stop...)
leftStop[len(leftStop)-1] = mid
rightStart := append([]int32(nil), start...)
rightStart[len(rightStart)-1] = mid
return mlx.SliceStartStop(a, start, leftStop), mlx.SliceStartStop(a, rightStart, stop)
}
func (m *sparseMoE) Forward(x *mlx.Array, cfg *Config) *mlx.Array {
dims := x.Dims()
B, L := int32(dims[0]), int32(dims[1])
topK := cfg.NumExpertsPerTok
probs := mlx.SoftmaxAxis(m.Gate.Forward(x), -1, true)
indices := mlx.Argpartition(mlx.Neg(probs), int(topK)-1, -1)
shape := indices.Dims()
indices = mlx.SliceStartStop(indices, []int32{0, 0, 0}, []int32{int32(shape[0]), int32(shape[1]), topK})
scores := mlx.TakeAlongAxis(probs, indices, -1)
scores = mlx.Div(scores, mlx.Sum(scores, -1, true))
xFlat := mlx.Reshape(mlx.ExpandDims(mlx.ExpandDims(x, -2), -2), B*L, 1, 1, cfg.HiddenSize)
indexFlat := mlx.Reshape(indices, B*L, topK)
doSort := B*L >= 64
var inverse *mlx.Array
if doSort {
all := mlx.Flatten(indexFlat)
order := mlx.Argsort(all, 0)
inverse = mlx.Argsort(order, 0)
xFlat = mlx.ExpandDims(mlx.Take(mlx.Squeeze(xFlat, 1), mlx.FloorDivideScalar(order, topK), 0), 1)
indexFlat = mlx.Reshape(mlx.Take(all, order, 0), B*L*topK, 1)
}
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, nil, doSort)
} else {
gateUp = mlx.GatherMM(xFlat, m.GateUpExperts, nil, indexFlat, doSort)
}
gate, up := splitLastAxis(gateUp)
hidden := mlx.SwiGLU(gate, up)
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, nil, doSort)
} else {
down = mlx.GatherMM(hidden, m.DownExperts, nil, indexFlat, doSort)
}
if doSort {
down = mlx.Reshape(mlx.Take(mlx.Squeeze(mlx.Squeeze(down, 2), 1), inverse, 0), B*L, topK, cfg.HiddenSize)
} else {
down = mlx.Squeeze(down, 2)
}
differentiated := mlx.Reshape(down, B, L, topK, cfg.HiddenSize)
out := mlx.Sum(mlx.Mul(differentiated, mlx.ExpandDims(scores, -1)), 2, false)
shared := m.SharedDownProj.Forward(mlx.SwiGLU(m.SharedGateProj.Forward(x), m.SharedUpProj.Forward(x)))
shared = mlx.Mul(shared, mlx.Sigmoid(m.SharedGate.Forward(x)))
return mlx.Add(out, shared)
}
+94 -23
View File
@@ -1,25 +1,98 @@
package qwen4_exp
import (
"fmt"
"math"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/nn"
)
func (n *streamRMSNorm) Forward(x *mlx.Array, eps float32) *mlx.Array {
originalShape := x.Dims()
if originalShape[len(originalShape)-1] == n.Weight.Size() {
shape := append([]int(nil), originalShape[:len(originalShape)-1]...)
shape = append(shape, n.Weight.Dim(0), n.Weight.Dim(1))
x = x.Reshape(shape...)
// PLE is the model's n-gram embedding block. The checkpoint stores one logical
// table in split vocabulary shards.
type PLE struct {
Conv *nn.Conv1d
KeyProj nn.LinearLayer
ValueProj nn.LinearLayer
NormConv *streamRMSNorm
NormKey *streamRMSNorm
NormQuery *streamRMSNorm
LayerMultipliers *mlx.Array
HeadOffsets *mlx.Array
HeadVocabSizes *mlx.Array
EmbeddingShards []nn.EmbeddingLayer
ShardRows int
hostEmbedding *hostPLETable
}
func (m *Model) loadPLE(linears model.LinearFactory, tensors map[string]*mlx.Array, prefix string) (*PLE, error) {
p := &PLE{}
var err error
convWeight, err := requiredArray(tensors, prefix+".conv1d.weight", prefix+".conv1d")
if err != nil {
return nil, err
}
dtype := x.DType()
values := x.AsType(mlx.DTypeFloat32)
meanSquare := mlx.Mean(mlx.Mul(values, values), -1, true)
invRMS := mlx.Div(mlx.NewScalarArray(1), mlx.AddScalar(meanSquare, eps).Sqrt())
normalized := mlx.Mul(mlx.Mul(values, invRMS), n.Weight.AsType(mlx.DTypeFloat32)).AsType(dtype)
return normalized.Reshape(originalShape...)
if convWeight.NumDims() != 3 || convWeight.Dim(1) != 1 || convWeight.Dim(2) != int(m.PLEConvKernelSize) {
return nil, fmt.Errorf("%s.conv1d has shape %v, want [%d, 1, %d]", prefix, convWeight.Dims(), m.HCCount*m.HiddenSize, m.PLEConvKernelSize)
}
convWeight = mlx.Transpose(convWeight, 0, 2, 1)
p.Conv = nn.NewConv1d(convWeight, nil, 1, 0, m.NGramSize, m.HCCount*m.HiddenSize)
if p.KeyProj, err = requiredLinear(linears, prefix+".key_proj"); err != nil {
return nil, err
}
if p.ValueProj, err = requiredLinear(linears, prefix+".value_proj"); err != nil {
return nil, err
}
if p.NormConv, err = loadStreamNorm(tensors, prefix+".norm_conv", m.Config); err != nil {
return nil, err
}
if p.NormKey, err = loadStreamNorm(tensors, prefix+".norm_key", m.Config); err != nil {
return nil, err
}
if p.NormQuery, err = loadStreamNorm(tensors, prefix+".norm_query", m.Config); err != nil {
return nil, err
}
if p.LayerMultipliers, err = requiredArray(tensors, prefix+".ple_embedding.layer_multipliers"); err != nil {
return nil, err
}
if p.HeadOffsets, err = requiredArray(tensors, prefix+".ple_embedding.ngram_heads_offsets"); err != nil {
return nil, err
}
if p.HeadVocabSizes, err = requiredArray(tensors, prefix+".ple_embedding.ngram_heads_vocab_sizes"); err != nil {
return nil, err
}
if table := m.hostPLE[prefix]; table != nil {
p.hostEmbedding = table
p.ShardRows = table.rows
return p, nil
}
p.EmbeddingShards = make([]nn.EmbeddingLayer, m.SplitNGramParts)
for i := range m.SplitNGramParts {
path := fmt.Sprintf("%s.ple_embedding.ngram_embedding.shard_%d", prefix, i)
weight, err := requiredArray(tensors, path+".weight")
if err != nil {
return nil, err
}
if i == 0 {
p.ShardRows = weight.Dim(0)
} else if weight.Dim(0) != p.ShardRows {
return nil, fmt.Errorf("%s has %d rows, want %d", path, weight.Dim(0), p.ShardRows)
}
p.EmbeddingShards[i] = model.MakeEmbeddingLayer(tensors, path, m.quantGroup, m.quantBits, m.quantMode, m.tensorQuant)
if p.EmbeddingShards[i] == nil {
return nil, fmt.Errorf("missing embedding %q", path)
}
}
return p, nil
}
func (p *PLE) NewCache(cfg *Config) *engramCache {
return newEngramCache(int(cfg.NGramSize-1), int((cfg.PLEConvKernelSize-1)*cfg.NGramSize), int(cfg.HCCount*cfg.HiddenSize), cfg.EOSTokenID)
}
func (p *PLE) hashes(b *batch.Batch, history *mlx.Array, cfg *Config) (*mlx.Array, *mlx.Array) {
@@ -30,15 +103,10 @@ func (p *PLE) hashes(b *batch.Batch, history *mlx.Array, cfg *Config) (*mlx.Arra
eos := mlx.FromValues([]int64{cfg.EOSTokenID}, 1)
for k := range cfg.NGramSize {
start := int(cfg.NGramSize - 1 - k)
shifts[k] = mlx.SliceStartStop(joined,
[]int32{0, int32(start)},
[]int32{int32(joined.Dim(0)), int32(start + length)},
)
shifts[k] = joined.Slice(mlx.Slice(), mlx.Slice(start, start+length))
for previous := int32(1); previous <= k; previous++ {
boundary := mlx.SliceStartStop(joined,
[]int32{0, cfg.NGramSize - 1 - previous},
[]int32{int32(joined.Dim(0)), cfg.NGramSize - 1 - previous + int32(length)},
)
start := int(cfg.NGramSize - 1 - previous)
boundary := joined.Slice(mlx.Slice(), mlx.Slice(start, start+length))
shifts[k] = mlx.Where(boundary.Equal(eos), eos, shifts[k])
}
}
@@ -62,15 +130,18 @@ func (p *PLE) hashes(b *batch.Batch, history *mlx.Array, cfg *Config) (*mlx.Arra
}
func (p *PLE) lookup(globalIDs *mlx.Array) *mlx.Array {
if p.hostEmbedding != nil {
return p.hostEmbedding.lookup(globalIDs)
}
rows := mlx.FromValues([]int64{int64(p.ShardRows)}, 1)
shardIDs := globalIDs.FloorDivide(rows)
localIDs := globalIDs.Remainder(rows)
zeroID := mlx.FromValues([]int64{0}, 1)
// The checkpoint partitions one logical table into equal contiguous row
// shards. This portable fallback touches every shard, then masks and sums
// the selected rows. It prioritizes reference bring-up over performance;
// production support should replace it with a fused split-table lookup.
// shards. Non-NVFP4 tables remain resident: gather each shard and mask out
// rows belonging to the others. NVFP4 tables use the host-backed path above.
var result *mlx.Array
for i, embedding := range p.EmbeddingShards {
mask := shardIDs.Equal(mlx.FromValues([]int64{int64(i)}, 1))
+164 -9
View File
@@ -1,12 +1,114 @@
package qwen4_exp
import "github.com/ollama/ollama/mlx"
import (
"fmt"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/nn"
)
type hyperConnection struct {
Norm *streamRMSNorm
InputMixDown nn.LinearLayer
InputMixUp nn.LinearLayer
BlockInject nn.LinearLayer
PackedInput nn.LinearLayer
MixDownDim int32
}
type hyperConnectionState struct {
residual *mlx.Array
normed *mlx.Array
inject *mlx.Array
}
func loadHyperConnection(linears model.LinearFactory, tensors map[string]*mlx.Array, prefix string, withInjection bool, cfg *Config) (*hyperConnection, error) {
h := &hyperConnection{}
var err error
if h.Norm, err = loadStreamNorm(tensors, prefix+".hc_norm", cfg); err != nil {
return nil, err
}
if h.InputMixDown, err = requiredLinear(linears, prefix+".input_mix_weight_down"); err != nil {
return nil, err
}
h.MixDownDim = h.InputMixDown.OutputDim()
if h.InputMixUp, err = requiredLinear(linears, prefix+".input_mix_weight_up"); err != nil {
return nil, err
}
if withInjection {
if h.BlockInject, err = requiredLinear(linears, prefix+".block_inject_weight"); err != nil {
return nil, err
}
if packed := packHyperConnectionInput(h.InputMixDown, h.BlockInject); packed != nil {
h.PackedInput = packed
h.InputMixDown = nil
h.BlockInject = nil
}
}
return h, nil
}
func packHyperConnectionInput(down, inject nn.LinearLayer) nn.LinearLayer {
switch down := down.(type) {
case *nn.Linear:
inject, ok := inject.(*nn.Linear)
if !ok || down.Bias != nil || inject.Bias != nil || down.Weight.Dim(1) != inject.Weight.Dim(1) {
return nil
}
return nn.NewLinear(mlx.Concatenate([]*mlx.Array{down.Weight, inject.Weight}, 0), nil)
case *nn.QuantizedLinear:
inject, ok := inject.(*nn.QuantizedLinear)
if !ok || down.Bias != nil || inject.Bias != nil ||
down.Scales == nil || inject.Scales == nil ||
down.QBiases != nil || inject.QBiases != nil ||
down.GlobalScale != nil || inject.GlobalScale != nil ||
down.GroupSize != inject.GroupSize || down.Bits != inject.Bits || down.Mode != inject.Mode ||
down.Weight.NumDims() != 2 || inject.Weight.NumDims() != 2 ||
down.Scales.NumDims() != 2 || inject.Scales.NumDims() != 2 ||
down.Weight.Dim(1) != inject.Weight.Dim(1) || down.Scales.Dim(1) != inject.Scales.Dim(1) {
return nil
}
return &nn.QuantizedLinear{
Weight: mlx.Concatenate([]*mlx.Array{down.Weight, inject.Weight}, 0),
Scales: mlx.Concatenate([]*mlx.Array{down.Scales, inject.Scales}, 0),
GroupSize: down.GroupSize,
Bits: down.Bits,
Mode: down.Mode,
}
}
return nil
}
var (
hyperConnectionSiLU = mlx.Compile2(
"Qwen4HyperConnectionSiLU",
func(x, count *mlx.Array) *mlx.Array {
return mlx.SiLU(mlx.Div(x, count))
},
mlx.Shapeless(),
)
hyperConnectionMix = mlx.Compile3(
"Qwen4HyperConnectionMix",
func(streams, mix, count *mlx.Array) *mlx.Array {
return mlx.Div(mlx.Sum(mlx.Mul(streams, mlx.Sigmoid(mix)), 2, false), count)
},
mlx.Shapeless(),
)
hyperConnectionInject = mlx.Compile(
"Qwen4HyperConnectionInject",
func(in ...*mlx.Array) []*mlx.Array {
residual, branch, logits, count := in[0], in[1], in[2], in[3]
weight := mlx.Sigmoid(mlx.Div(logits, count))
two := mlx.FromValue(float32(2)).AsType(weight.DType())
weight = mlx.Mul(weight, two)
update := mlx.Mul(mlx.ExpandDims(weight, -1), mlx.ExpandDims(branch, -2))
return []*mlx.Array{mlx.Add(residual, update)}
},
mlx.Shapeless(),
)
)
func expandStreams(x *mlx.Array, cfg *Config) *mlx.Array {
dims := x.Dims()
B, L := int32(dims[0]), int32(dims[1])
@@ -20,12 +122,22 @@ func (h *hyperConnection) Prepare(residual *mlx.Array, cfg *Config) (*mlx.Array,
dims := residual.Dims()
B, L := int32(dims[0]), int32(dims[1])
normed := h.Norm.Forward(residual, cfg.RMSNormEps)
mixHidden := mlx.SiLU(mlx.DivScalar(h.InputMixDown.Forward(normed), float32(cfg.HCCount)))
var down, inject *mlx.Array
if h.PackedInput != nil {
packed := h.PackedInput.Forward(normed)
down = packed.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(0, int(h.MixDownDim)))
inject = packed.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(int(h.MixDownDim), mlx.End))
} else {
down = h.InputMixDown.Forward(normed)
}
count := mlx.NewScalarArray(float32(cfg.HCCount)).AsType(down.DType())
mixHidden := hyperConnectionSiLU(down, count)
mix := h.InputMixUp.Forward(mixHidden)
mix = mlx.Reshape(mix, B, L, cfg.HCCount, cfg.HiddenSize)
streams := mlx.Reshape(normed, B, L, cfg.HCCount, cfg.HiddenSize)
branch := mlx.DivScalar(mlx.Sum(mlx.Mul(streams, mlx.Sigmoid(mix)), 2, false), float32(cfg.HCCount))
return branch, hyperConnectionState{residual: residual, normed: normed}
count = mlx.NewScalarArray(float32(cfg.HCCount)).AsType(streams.DType())
branch := hyperConnectionMix(streams, mix, count)
return branch, hyperConnectionState{residual: residual, normed: normed, inject: inject}
}
// Inject broadcasts one branch result back into the residual streams. The
@@ -34,12 +146,14 @@ func (h *hyperConnection) Prepare(residual *mlx.Array, cfg *Config) (*mlx.Array,
func (h *hyperConnection) Inject(state hyperConnectionState, branch *mlx.Array, cfg *Config) *mlx.Array {
dims := branch.Dims()
B, L := int32(dims[0]), int32(dims[1])
weight := mlx.MulScalar(mlx.Sigmoid(mlx.DivScalar(h.BlockInject.Forward(state.normed), float32(cfg.HCCount))), 2)
weight = mlx.ExpandDims(weight, -1)
branch = mlx.ExpandDims(branch, -2)
update := mlx.Mul(weight, branch)
logits := state.inject
if logits == nil {
logits = h.BlockInject.Forward(state.normed)
}
count := mlx.NewScalarArray(float32(cfg.HCCount)).AsType(logits.DType())
residual := mlx.Reshape(state.residual, B, L, cfg.HCCount, cfg.HiddenSize)
return mlx.Reshape(mlx.Add(residual, update), B, L, cfg.HCCount*cfg.HiddenSize)
out := hyperConnectionInject(residual, branch, logits, count)[0]
return mlx.Reshape(out, B, L, cfg.HCCount*cfg.HiddenSize)
}
// Reduce applies the trained input mixer as the final stream reduction. The
@@ -48,3 +162,44 @@ func (h *hyperConnection) Reduce(residual *mlx.Array, cfg *Config) *mlx.Array {
branch, _ := h.Prepare(residual, cfg)
return branch
}
type streamRMSNorm struct {
Weight *mlx.Array
}
func loadStreamNorm(tensors map[string]*mlx.Array, name string, cfg *Config) (*streamRMSNorm, error) {
weight, err := requiredArray(tensors, name+".weight", name)
if err != nil {
return nil, err
}
if weight.Size() != int(cfg.HCCount*cfg.HiddenSize) {
return nil, fmt.Errorf("%s has %d elements, want %d", name, weight.Size(), cfg.HCCount*cfg.HiddenSize)
}
weight = mlx.Reshape(mlx.AddScalar(weight, 1), cfg.HCCount, cfg.HiddenSize)
return &streamRMSNorm{Weight: weight}, nil
}
var streamRMSNormFn = mlx.Compile(
"Qwen4StreamRMSNorm",
func(in ...*mlx.Array) []*mlx.Array {
x, weight, eps := in[0], in[1], in[2]
dtype := x.DType()
values := x.AsType(mlx.DTypeFloat32)
meanSquare := mlx.Mean(mlx.Mul(values, values), -1, true)
invRMS := mlx.Div(mlx.NewScalarArray(1), mlx.Add(meanSquare, eps).Sqrt())
return []*mlx.Array{mlx.Mul(mlx.Mul(values, invRMS), weight.AsType(mlx.DTypeFloat32)).AsType(dtype)}
},
mlx.Shapeless(),
)
func (n *streamRMSNorm) Forward(x *mlx.Array, eps float32) *mlx.Array {
originalShape := x.Dims()
if originalShape[len(originalShape)-1] == n.Weight.Size() {
shape := append([]int(nil), originalShape[:len(originalShape)-1]...)
shape = append(shape, n.Weight.Dim(0), n.Weight.Dim(1))
x = x.Reshape(shape...)
}
epsArray := mlx.NewScalarArray(eps)
normalized := streamRMSNormFn(x, n.Weight, epsArray)[0]
return normalized.Reshape(originalShape...)
}
@@ -11,6 +11,9 @@ import (
func TestHyperConnectionMatchesReferenceFormula(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
mlx.EnableCompile()
defer mlx.DisableCompile()
cfg := &Config{HCCount: 2, HiddenSize: 2, HCLowRank: 2, RMSNormEps: 1e-6}
normWeight := []float32{1.1, 0.9, 1.2, 0.8}
downWeight := [][]float32{{0.2, -0.3, 0.4, 0.1}, {-0.1, 0.5, 0.2, -0.4}}
@@ -18,11 +21,13 @@ func TestHyperConnectionMatchesReferenceFormula(t *testing.T) {
injectWeight := [][]float32{{0.2, -0.1, 0.3, 0.4}, {-0.3, 0.2, 0.1, 0.5}}
input := []float32{1, 2, 3, 4}
downProj := nn.NewLinear(matrix(downWeight), nil)
injectProj := nn.NewLinear(matrix(injectWeight), nil)
h := &hyperConnection{
Norm: &streamRMSNorm{Weight: mlx.FromValues(normWeight, 2, 2)},
InputMixDown: nn.NewLinear(matrix(downWeight), nil),
InputMixUp: nn.NewLinear(matrix(upWeight), nil),
BlockInject: nn.NewLinear(matrix(injectWeight), nil),
Norm: &streamRMSNorm{Weight: mlx.FromValues(normWeight, 2, 2)},
InputMixUp: nn.NewLinear(matrix(upWeight), nil),
PackedInput: packHyperConnectionInput(downProj, injectProj),
MixDownDim: downProj.OutputDim(),
}
residual := mlx.FromValues(input, 1, 1, 4)
branch, state := h.Prepare(residual, cfg)
@@ -0,0 +1,109 @@
package qwen4_exp
import (
"fmt"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/nn"
)
type linearAttention struct {
QKV nn.LinearLayer
Z nn.LinearLayer
B nn.LinearLayer
A nn.LinearLayer
Out nn.LinearLayer
Conv *nn.Conv1d
NormWeight *mlx.Array
DtBias *mlx.Array
ALog *mlx.Array
AExp *mlx.Array
}
func loadLinearAttention(linears model.LinearFactory, tensors map[string]*mlx.Array, prefix string) (*linearAttention, error) {
a := &linearAttention{
QKV: linears.Make(prefix + ".in_proj_qkv"),
Z: linears.Make(prefix + ".in_proj_z"),
B: linears.Make(prefix + ".in_proj_b"),
A: linears.Make(prefix + ".in_proj_a"),
Out: linears.Make(prefix + ".out_proj"),
}
var err error
if a.QKV == nil || a.Z == nil || a.B == nil || a.A == nil || a.Out == nil {
return nil, fmt.Errorf("missing linear attention projection at %s", prefix)
}
convWeight, err := requiredArray(tensors, prefix+".conv1d.weight", prefix+".conv1d")
if err != nil {
return nil, err
}
if convWeight.NumDims() == 3 && convWeight.Dim(1) == 1 {
convWeight = mlx.Reshape(convWeight, int32(convWeight.Dim(0)), int32(convWeight.Dim(2)))
}
if convWeight.NumDims() != 2 {
return nil, fmt.Errorf("%s.conv1d weight must reduce to 2D, got %dD", prefix, convWeight.NumDims())
}
a.Conv = nn.NewConv1d(mlx.ExpandDims(convWeight, 2), nil, 1, 0, 1, int32(convWeight.Dim(0)))
if a.NormWeight, err = requiredArray(tensors, prefix+".norm.weight", prefix+".norm"); err != nil {
return nil, err
}
if a.DtBias, err = requiredArray(tensors, prefix+".dt_bias", prefix+".dt_proj"); err != nil {
return nil, err
}
if a.ALog, err = requiredArray(tensors, prefix+".A_log", prefix+".a_log"); err != nil {
return nil, err
}
a.AExp = mlx.Exp(a.ALog.AsType(mlx.DTypeFloat32))
return a, nil
}
var linearAttentionOutputGate = mlx.Compile2(
"Qwen4LinearAttentionOutputGate",
func(out, gate *mlx.Array) *mlx.Array {
dtype := out.DType()
return mlx.Mul(out.AsType(mlx.DTypeFloat32), mlx.Sigmoid(gate.AsType(mlx.DTypeFloat32))).AsType(dtype)
},
mlx.Shapeless(),
)
func (a *linearAttention) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, cfg *Config) *mlx.Array {
dims := x.Dims()
B, L := int32(dims[0]), int32(dims[1])
valueDim := cfg.LinearNumValueHeads * cfg.LinearValueHeadDim
qkv := a.QKV.Forward(x)
z := mlx.Reshape(a.Z.Forward(x), B, L, cfg.LinearNumValueHeads, cfg.LinearValueHeadDim)
ba := mlx.Concatenate([]*mlx.Array{a.B.Forward(x), a.A.Forward(x)}, -1)
convTail := cfg.LinearConvKernelDim - 1
options := []nn.RecurrentOption{nn.WithConvSiLU()}
var recurrent *cache.RecurrentCache
if value, ok := c.(*cache.RecurrentCache); ok {
recurrent = value
options = append(options, nn.WithRecurrentHistory(recurrent.Get(b, x.DType())))
if splits := recurrent.SnapshotSplits(int(L)); len(splits) > 0 {
options = append(options, nn.WithSnapshotSplits(splits))
}
} else {
options = append(options, nn.WithRecurrentState(
mlx.Zeros(x.DType(), int(B), int(convTail), qkv.Dim(2)),
mlx.Zeros(mlx.DTypeFloat32, int(B), int(cfg.LinearNumValueHeads), int(cfg.LinearValueHeadDim), int(cfg.LinearKeyHeadDim)),
))
}
convOut, convState := nn.CausalConv1D(b, qkv, a.Conv, int(convTail), options...)
out, deltaState := nn.GatedDelta(b, convOut, ba, a.DtBias, a.AExp, options...)
outType := out.DType()
out = mlx.RMSNormFn(out, a.NormWeight, cfg.RMSNormEps)
// Qwen 4 uses a sigmoid Gated DeltaNet output gate rather than the SiLU
// gate used by Qwen3.5.
out = linearAttentionOutputGate(out.AsType(outType), z)
out = a.Out.Forward(mlx.Reshape(out, B, L, valueDim))
if recurrent != nil {
recurrent.Put(b, convState, deltaState)
}
return out
}
+172
View File
@@ -0,0 +1,172 @@
package qwen4_exp
import (
"fmt"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/nn"
)
type sparseMoE struct {
Gate nn.LinearLayer
GateUp *expertProjection
Down *expertProjection
SharedGate nn.LinearLayer
Shared *denseMLP
}
type denseMLP struct {
GateProj nn.LinearLayer
UpProj nn.LinearLayer
DownProj nn.LinearLayer
}
func (m *denseMLP) Forward(x *mlx.Array) *mlx.Array {
return m.DownProj.Forward(mlx.SwiGLU(m.GateProj.Forward(x), m.UpProj.Forward(x)))
}
// expertProjection keeps a packed expert bank and its quantization companions
// together. Unquantized weights are transposed once at load for GatherMM.
type expertProjection struct {
Weight *mlx.Array
Scales *mlx.Array
Biases *mlx.Array
GlobalScale *mlx.Array
GroupSize int
Bits int
Mode string
}
func (p *expertProjection) Forward(x, indices *mlx.Array, sorted bool) *mlx.Array {
if p.Scales != nil {
return mlx.GatherQMM(x, p.Weight, p.Scales, p.Biases,
nil, indices, true, p.GroupSize, p.Bits, p.Mode, p.GlobalScale, sorted)
}
return mlx.GatherMM(x, p.Weight, nil, indices, sorted)
}
func supportsGatherQMM(mode string, bits int) bool {
switch mode {
case "affine":
return bits == 4 || bits == 8
case "mxfp8":
return bits == 8
case "nvfp4", "mxfp4":
return bits == 4
default:
return false
}
}
func (m *Model) loadExpertProjection(tensors map[string]*mlx.Array, base string) (*expertProjection, error) {
p := &expertProjection{}
var key string
for _, candidate := range []string{base, base + ".weight"} {
if p.Weight = tensors[candidate]; p.Weight != nil {
key = candidate
break
}
}
if p.Weight == nil {
return nil, fmt.Errorf("missing packed expert tensor %q", base)
}
p.Scales = tensors[key+"_scale"]
if p.Scales == nil {
p.Weight = mlx.Transpose(p.Weight, 0, 2, 1)
} else {
p.Biases = tensors[key+"_qbias"]
p.GroupSize, p.Bits, p.Mode = model.ResolveLinearQuantParams(m.quantGroup, m.quantBits, m.quantMode, m.tensorQuant, key, p.Weight, p.Scales)
if !supportsGatherQMM(p.Mode, p.Bits) {
return nil, fmt.Errorf("packed expert tensor %q uses unsupported quantization mode=%q bits=%d", key, p.Mode, p.Bits)
}
}
var err error
p.GlobalScale, err = loadExpertGlobalScale(tensors, base, p.Weight.Dim(0), p.Mode)
if err != nil {
return nil, err
}
return p, nil
}
func (m *Model) loadSparseMoE(linears model.LinearFactory, tensors map[string]*mlx.Array, prefix string) (*sparseMoE, error) {
moe := &sparseMoE{}
var err error
if moe.Gate, err = requiredLinear(linears, prefix+".gate"); err != nil {
return nil, err
}
if moe.GateUp, err = m.loadExpertProjection(tensors, prefix+".experts.gate_up_proj"); err != nil {
return nil, err
}
if moe.Down, err = m.loadExpertProjection(tensors, prefix+".experts.down_proj"); err != nil {
return nil, err
}
if moe.SharedGate, err = requiredLinear(linears, prefix+".shared_expert_gate"); err != nil {
return nil, err
}
moe.Shared = &denseMLP{
GateProj: linears.Make(prefix + ".shared_expert.gate_proj"),
UpProj: linears.Make(prefix + ".shared_expert.up_proj"),
DownProj: linears.Make(prefix + ".shared_expert.down_proj"),
}
if moe.Shared.GateProj == nil || moe.Shared.UpProj == nil || moe.Shared.DownProj == nil {
return nil, fmt.Errorf("missing shared expert projection at %s", prefix)
}
return moe, nil
}
func loadExpertGlobalScale(tensors map[string]*mlx.Array, base string, experts int, mode string) (*mlx.Array, error) {
scale, _ := model.ReadGlobalScale(tensors, base, base+".weight")
if scale == nil {
return nil, nil
}
if mode != "nvfp4" {
return nil, fmt.Errorf("expert tensor %q has a global scale but uses mode=%q", base, mode)
}
if scale.Size() != 1 && scale.Size() != experts {
return nil, fmt.Errorf("expert tensor %q has %d global scales for %d experts", base, scale.Size(), experts)
}
return model.PrepareGatherQMMGlobalScale(scale, experts), nil
}
func (m *sparseMoE) Forward(x *mlx.Array, cfg *Config) *mlx.Array {
dims := x.Dims()
B, L := int32(dims[0]), int32(dims[1])
topK := cfg.NumExpertsPerTok
probs := mlx.SoftmaxAxis(m.Gate.Forward(x), -1, true)
indices := mlx.Argpartition(mlx.Neg(probs), int(topK)-1, -1)
indices = indices.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(0, int(topK)))
scores := mlx.TakeAlongAxis(probs, indices, -1)
scores = mlx.Div(scores, mlx.Sum(scores, -1, true))
xFlat := mlx.Reshape(mlx.ExpandDims(mlx.ExpandDims(x, -2), -2), B*L, 1, 1, cfg.HiddenSize)
indexFlat := mlx.Reshape(indices, B*L, topK)
doSort := B*L >= 64
var inverse *mlx.Array
if doSort {
all := mlx.Flatten(indexFlat)
order := mlx.Argsort(all, 0)
inverse = mlx.Argsort(order, 0)
xFlat = mlx.ExpandDims(mlx.Take(mlx.Squeeze(xFlat, 1), mlx.FloorDivideScalar(order, topK), 0), 1)
indexFlat = mlx.Reshape(mlx.Take(all, order, 0), B*L*topK, 1)
}
gateUp := m.GateUp.Forward(xFlat, indexFlat, doSort)
mid := gateUp.Dim(-1) / 2
gate := gateUp.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(0, mid))
up := gateUp.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(mid, mlx.End))
hidden := mlx.SwiGLU(gate, up)
down := m.Down.Forward(hidden, indexFlat, doSort)
if doSort {
down = mlx.Reshape(mlx.Take(mlx.Squeeze(mlx.Squeeze(down, 2), 1), inverse, 0), B*L, topK, cfg.HiddenSize)
} else {
down = mlx.Squeeze(down, 2)
}
differentiated := mlx.Reshape(down, B, L, topK, cfg.HiddenSize)
out := mlx.Sum(mlx.Mul(differentiated, mlx.ExpandDims(scores, -1)), 2, false)
shared := m.Shared.Forward(x)
shared = mlx.Mul(shared, mlx.Sigmoid(m.SharedGate.Forward(x)))
return mlx.Add(out, shared)
}
+94
View File
@@ -0,0 +1,94 @@
package qwen4_exp
import (
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/nn"
)
type MTPHead struct {
EmbeddingNorm *nn.RMSNorm
HiddenNorm *nn.RMSNorm
FCEmbedding nn.LinearLayer
FCHidden nn.LinearLayer
Mixer *hyperConnection
Layer *Layer
}
func (m *Model) loadMTP(linears model.LinearFactory, tensors map[string]*mlx.Array) (*MTPHead, error) {
head := &MTPHead{}
var err error
if head.EmbeddingNorm, err = loadNorm(tensors, "mtp.pre_fc_norm_embedding", m.RMSNormEps); err != nil {
return nil, err
}
if head.HiddenNorm, err = loadNorm(tensors, "mtp.pre_fc_norm_hidden", m.RMSNormEps); err != nil {
return nil, err
}
if head.FCEmbedding, err = requiredLinear(linears, "mtp.fc_embedding"); err != nil {
return nil, err
}
if head.FCHidden, err = requiredLinear(linears, "mtp.fc_hidden"); err != nil {
return nil, err
}
if head.Mixer, err = loadHyperConnection(linears, tensors, "mtp.hyper_connection_mixer", false, m.Config); err != nil {
return nil, err
}
if head.Layer, err = m.loadLayer(linears, tensors, "mtp.layers.0", m.Config.MTP.LayerTypes[0], -1); err != nil {
return nil, err
}
return head, nil
}
// mtpDraft views the checkpoint's inline predictor through DraftModel.
type mtpDraft Model
func (m *Model) SelfDraft() model.DraftModel {
if m.MTP == nil {
return nil
}
return (*mtpDraft)(m)
}
func (m *mtpDraft) NewCaches() []cache.Cache {
if m.MTP == nil {
return nil
}
return []cache.Cache{cache.NewKVCache(), cache.NewKVCache()}
}
func (m *mtpDraft) LoadWeights(map[string]*mlx.Array) error { return nil }
func (m *mtpDraft) Unembed(x *mlx.Array) *mlx.Array { return (*Model)(m).Unembed(x) }
func (m *mtpDraft) Forward(b *batch.Batch, _, draftCaches []cache.Cache) (hidden, auxHidden *mlx.Array) {
B, L := int32(b.InputIDs.Dim(0)), int32(b.InputIDs.Dim(1))
var mrope []int32
if m.Vision != nil {
mrope = m.Vision.RopePositions(b, L)
}
ropePositions := canonicalRopePositionRows(b, L, mrope)
embedding := m.EmbedTokens.Forward(b.InputIDs)
// The reference MTP is text-only: visual information reaches it through
// the target's multi-stream hidden state, while this branch embeds raw IDs.
embedding = m.MTP.FCEmbedding.Forward(m.MTP.EmbeddingNorm.Forward(embedding, m.RMSNormEps))
backbone := m.MTP.HiddenNorm.Forward(b.Hidden, m.RMSNormEps)
backbone = mlx.Reshape(backbone, B, L, m.HCCount, m.HiddenSize)
backbone = m.MTP.FCHidden.Forward(backbone)
backbone = mlx.Add(backbone, mlx.ExpandDims(embedding, -2))
backbone = mlx.Reshape(backbone, B, L, m.HCCount*m.HiddenSize)
var main, side cache.Cache
if len(draftCaches) > 0 {
main = draftCaches[0]
}
if len(draftCaches) > 1 {
side = draftCaches[1]
}
multi := m.MTP.Layer.Forward(backbone, b, main, side, ropePositions, m.Config)
sample := m.MTP.Mixer.Reduce(multi, m.Config)
return sample, multi
}
+275
View File
@@ -0,0 +1,275 @@
package qwen4_exp
import (
"encoding/binary"
"errors"
"fmt"
"io"
"log/slog"
"math"
"slices"
"sort"
"strings"
"github.com/ollama/ollama/fs/safetensors"
"github.com/ollama/ollama/manifest"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/model"
)
var errHostPLEUnsupported = errors.New("host-backed PLE requires standard NVFP4")
type hostPLEShard struct {
mapping *hostMapping
weightStart int64
scaleStart int64
rows int
weightColumns int
scaleColumns int
globalScale float32 // MLX representation; zero means no scale was stored.
}
type hostPLETable struct {
shards []*hostPLEShard
rows int
rowWidth int
hasGlobalScale bool
}
func (m *Model) SkippedTensorNames() []string {
var names []string
for prefix, table := range m.hostPLE {
for i := range table.shards {
name := fmt.Sprintf("%s.ple_embedding.ngram_embedding.shard_%d.weight", prefix, i)
names = append(names, name, name+".scale", name+".global_scale")
}
}
return names
}
func openHostPLETables(root *model.Root, cfg *Config) (map[string]*hostPLETable, error) {
headCount := (cfg.NGramSize - 1) * cfg.HeadsPerNGram
if headCount <= 0 || cfg.PLEEmbedDim%headCount != 0 {
return nil, nil
}
rowWidth := int(cfg.PLEEmbedDim / headCount)
layers := make(map[string]manifest.Layer)
for _, layer := range root.Manifest.TensorLayers() {
layers[layer.Name] = layer
}
tables := make(map[string]*hostPLETable, len(cfg.PLELayerIDs))
rowsPerShard := 0
for _, id := range cfg.PLELayerIDs {
prefix := fmt.Sprintf("model.language_model.layers.%d.ple", id-1)
table, err := openHostPLETable(layers, root.AllTensorQuant(), prefix, int(cfg.SplitNGramParts), rowWidth)
if errors.Is(err, errHostPLEUnsupported) {
closeHostPLETables(tables)
return nil, nil
}
if err != nil {
closeHostPLETables(tables)
return nil, fmt.Errorf("%s: %w", prefix, err)
}
tables[prefix] = table
rowsPerShard = table.rows
}
slog.Info("enabled host-backed Qwen PLE", "layers", len(tables), "shards_per_layer", cfg.SplitNGramParts, "rows_per_shard", rowsPerShard)
return tables, nil
}
func openHostPLETable(layers map[string]manifest.Layer, quant map[string]*model.TensorQuantInfo, prefix string, shardCount, rowWidth int) (*hostPLETable, error) {
table := &hostPLETable{
shards: make([]*hostPLEShard, shardCount),
rowWidth: rowWidth,
}
for i := range shardCount {
name := fmt.Sprintf("%s.ple_embedding.ngram_embedding.shard_%d.weight", prefix, i)
layer, ok := layers[name]
if !ok {
table.close()
return nil, fmt.Errorf("missing tensor layer %q", name)
}
path, err := manifest.BlobsPath(layer.Digest)
if err != nil {
table.close()
return nil, fmt.Errorf("resolve %s: %w", name, err)
}
shard, err := openHostPLEShard(path, name, rowWidth, quant[name])
if err != nil {
table.close()
return nil, fmt.Errorf("open %s: %w", name, err)
}
if i == 0 {
table.rows = shard.rows
} else if shard.rows != table.rows {
shard.mapping.close()
table.close()
return nil, fmt.Errorf("shard %d has %d rows, want %d", i, shard.rows, table.rows)
}
table.shards[i] = shard
table.hasGlobalScale = table.hasGlobalScale || shard.globalScale != 0
}
return table, nil
}
func openHostPLEShard(path, name string, rowWidth int, quant *model.TensorQuantInfo) (*hostPLEShard, error) {
// NVFP4 always uses groups of 16; prequantized imports may omit the field.
if quant == nil || !strings.EqualFold(quant.QuantType, "nvfp4") || (quant.GroupSize != 0 && quant.GroupSize != 16) {
return nil, errHostPLEUnsupported
}
extractor, err := safetensors.OpenForExtraction(path)
if err != nil {
return nil, err
}
defer extractor.Close()
weight, err := extractor.GetTensor(name)
if err != nil {
return nil, err
}
scale, err := extractor.GetTensor(name + ".scale")
if err != nil {
return nil, err
}
if weight.Dtype != "U32" || len(weight.Shape) != 2 || weight.Shape[0] <= 0 || int64(weight.Shape[1])*8 != int64(rowWidth) {
return nil, fmt.Errorf("weight has dtype=%s shape=%v, want U32 [rows,%d]", weight.Dtype, weight.Shape, rowWidth/8)
}
if scale.Dtype != "U8" || len(scale.Shape) != 2 || scale.Shape[0] != weight.Shape[0] || int64(scale.Shape[1])*16 != int64(rowWidth) {
return nil, fmt.Errorf("scale has dtype=%s shape=%v, want U8 [%d,%d]", scale.Dtype, scale.Shape, weight.Shape[0], rowWidth/16)
}
globalScale, err := readHostGlobalScale(extractor, name)
if err != nil {
return nil, err
}
mapping, err := openHostMapping(path)
if err != nil {
return nil, err
}
return &hostPLEShard{
mapping: mapping,
weightStart: weight.Offset(),
scaleStart: scale.Offset(),
rows: int(weight.Shape[0]),
weightColumns: int(weight.Shape[1]),
scaleColumns: int(scale.Shape[1]),
globalScale: globalScale,
}, nil
}
func readHostGlobalScale(extractor *safetensors.TensorExtractor, name string) (float32, error) {
if !slices.Contains(extractor.ListTensors(), name+".global_scale") {
return 0, nil
}
entry, err := extractor.GetTensor(name + ".global_scale")
if err != nil {
return 0, err
}
scalar := true
for _, dim := range entry.Shape {
scalar = scalar && dim == 1
}
if entry.Dtype != "F32" || !scalar || entry.Size != 4 {
return 0, fmt.Errorf("global scale has dtype=%s shape=%v, want scalar F32", entry.Dtype, entry.Shape)
}
var data [4]byte
if _, err := io.ReadFull(entry.Reader(), data[:]); err != nil {
return 0, err
}
value := math.Float32frombits(binary.LittleEndian.Uint32(data[:])) * mlx.Nvfp4MaxProduct
if !(value > 0) || math.IsInf(float64(value), 0) {
return 0, fmt.Errorf("global scale is not finite and positive")
}
return value, nil
}
func closeHostPLETables(tables map[string]*hostPLETable) {
for _, table := range tables {
table.close()
}
}
func (t *hostPLETable) close() {
for _, shard := range t.shards {
if shard != nil {
shard.mapping.close()
}
}
}
func (t *hostPLETable) lookup(globalIDs *mlx.Array) *mlx.Array {
shape := globalIDs.Dims()
ids := globalIDs.AsType(mlx.DTypeInt32).Ints()
order := make([]int, len(ids))
maxID := len(t.shards) * t.rows
for i, id := range ids {
if id < 0 || int(id) >= maxID {
panic(fmt.Sprintf("Qwen PLE row ID %d outside [0,%d)", id, maxID))
}
order[i] = i
}
sort.Slice(order, func(i, j int) bool {
return ids[order[i]] < ids[order[j]]
})
weightColumns := t.shards[0].weightColumns
scaleColumns := t.shards[0].scaleColumns
weights := make([]uint32, len(ids)*weightColumns)
scales := make([]uint8, len(ids)*scaleColumns)
previousID := int32(-1)
previousOutput := -1
for _, output := range order {
id := ids[output]
weightOutput := weights[output*weightColumns : (output+1)*weightColumns]
scaleOutput := scales[output*scaleColumns : (output+1)*scaleColumns]
if id == previousID {
copy(weightOutput, weights[previousOutput*weightColumns:(previousOutput+1)*weightColumns])
copy(scaleOutput, scales[previousOutput*scaleColumns:(previousOutput+1)*scaleColumns])
continue
}
shard := t.shards[int(id)/t.rows]
row := int64(int(id) % t.rows)
weightBytes, err := shard.mapping.bytes(
shard.weightStart+row*int64(weightColumns*4),
shard.weightStart+(row+1)*int64(weightColumns*4),
)
if err != nil {
panic(fmt.Sprintf("read Qwen PLE weight row %d: %v", id, err))
}
for i := range weightColumns {
weightOutput[i] = binary.LittleEndian.Uint32(weightBytes[i*4:])
}
scaleBytes, err := shard.mapping.bytes(
shard.scaleStart+row*int64(scaleColumns),
shard.scaleStart+(row+1)*int64(scaleColumns),
)
if err != nil {
panic(fmt.Sprintf("read Qwen PLE scale row %d: %v", id, err))
}
copy(scaleOutput, scaleBytes)
previousID = id
previousOutput = output
}
weightShape := append(append([]int(nil), shape...), weightColumns)
scaleShape := append(append([]int(nil), shape...), scaleColumns)
weight := mlx.FromValues(weights, weightShape...)
scale := mlx.FromValues(scales, scaleShape...)
var globalScale *mlx.Array
if t.hasGlobalScale {
// IDs can interleave shards, each with its own global scale. Apply the
// selected shard's scale per row, including repeated IDs.
values := make([]float32, len(ids))
for i, id := range ids {
values[i] = t.shards[int(id)/t.rows].globalScale
if values[i] == 0 {
values[i] = mlx.Nvfp4MaxProduct
}
}
globalScale = mlx.FromValues(values, shape...)
}
return mlx.Dequantize(weight, scale, nil, 16, 4, "nvfp4", globalScale)
}
+140
View File
@@ -0,0 +1,140 @@
package qwen4_exp
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"math"
"slices"
"strconv"
"testing"
"github.com/ollama/ollama/fs/safetensors"
"github.com/ollama/ollama/manifest"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/nn"
)
func TestHostPLELookupMatchesResidentEmbedding(t *testing.T) {
const (
prefix = "model.language_model.layers.1.ple"
shardCount = 2
rowsPerShard = 3
rowWidth = 16
)
weights := []uint32{
0x01234567, 0x89abcdef,
0x11111111, 0x22222222,
0x33333333, 0x44444444,
0x55555555, 0x66666666,
0x77777777, 0x88888888,
0x99999999, 0xaaaaaaaa,
}
scales := []uint8{0x38, 0x40, 0x48, 0x38, 0x40, 0x48}
for _, tc := range []struct {
name string
globals [2]float32
shape []int32
groupSize string
}{
{"unscaled", [2]float32{}, nil, "16"},
{"different shard scales", [2]float32{0.5, 2}, []int32{1, 1}, "16"},
{"mixed scaled and unscaled", [2]float32{0, 2}, []int32{1}, "16"},
{"implicit NVFP4 group size", [2]float32{0.5, 2}, nil, ""},
} {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("OLLAMA_MODELS", t.TempDir())
layers := make([]manifest.Layer, 0, shardCount)
for shard := range shardCount {
name := fmt.Sprintf("%s.ple_embedding.ngram_embedding.shard_%d.weight", prefix, shard)
start := shard * rowsPerShard
end := start + rowsPerShard
weightData := safetensors.NewTensorDataFromBytes(name, "U32", []int32{rowsPerShard, rowWidth / 8}, uint32Bytes(weights[start*2:end*2]))
scaleData := safetensors.NewTensorDataFromBytes(name+".scale", "U8", []int32{rowsPerShard, rowWidth / 16}, scales[start:end])
data := []*safetensors.TensorData{weightData, scaleData}
if tc.globals[shard] != 0 {
data = append(data, safetensors.NewTensorDataFromBytes(name+".global_scale", "F32", tc.shape, uint32Bytes([]uint32{math.Float32bits(tc.globals[shard])})))
}
metadata := map[string]string{"quant_type": "nvfp4"}
if tc.groupSize != "" {
metadata["group_size"] = tc.groupSize
}
blob, err := io.ReadAll(safetensors.BuildPackedSafetensorsReaderWithMetadata(data, metadata))
if err != nil {
t.Fatal(err)
}
layer, err := manifest.NewLayer(bytes.NewReader(blob), manifest.MediaTypeImageTensor)
if err != nil {
t.Fatal(err)
}
layer.Name = name
layers = append(layers, layer)
}
layerByName := make(map[string]manifest.Layer, len(layers))
quant := make(map[string]*model.TensorQuantInfo, len(layers))
for _, layer := range layers {
layerByName[layer.Name] = layer
group, _ := strconv.Atoi(tc.groupSize)
quant[layer.Name] = &model.TensorQuantInfo{QuantType: "nvfp4", GroupSize: group}
}
table, err := openHostPLETable(layerByName, quant, prefix, shardCount, rowWidth)
if err != nil {
t.Fatal(err)
}
t.Cleanup(table.close)
m := &Model{hostPLE: map[string]*hostPLETable{prefix: table}}
var wantNames []string
for _, layer := range layers {
wantNames = append(wantNames, layer.Name, layer.Name+".scale", layer.Name+".global_scale")
}
gotNames := m.SkippedTensorNames()
slices.Sort(gotNames)
slices.Sort(wantNames)
if !slices.Equal(gotNames, wantNames) {
t.Fatalf("skipped tensor names = %v, want %v", gotNames, wantNames)
}
mlxtest.Run(t, func(t *mlxtest.T) {
ids := mlx.FromValues([]int64{5, 0, 3, 3, 2, 4}, 2, 3)
got := table.lookup(ids).AsType(mlx.DTypeFloat32)
want := (&nn.QuantizedEmbedding{
Weight: mlx.FromValues(weights, shardCount*rowsPerShard, rowWidth/8),
Scales: mlx.FromValues(scales, shardCount*rowsPerShard, rowWidth/16),
GroupSize: 16,
Bits: 4,
Mode: "nvfp4",
}).Forward(ids).AsType(mlx.DTypeFloat32)
mlx.Eval(got, want)
wantValues := want.Floats()
for row, id := range []int{5, 0, 3, 3, 2, 4} {
if factor := tc.globals[id/rowsPerShard]; factor != 0 {
for col := range rowWidth {
wantValues[row*rowWidth+col] *= factor
}
}
}
if !slices.Equal(got.Floats(), wantValues) {
t.Fatalf("host lookup = %v, want %v", got.Floats(), wantValues)
}
})
})
}
}
func TestResidentPLEDoesNotSkipTensors(t *testing.T) {
if got := (&Model{}).SkippedTensorNames(); len(got) != 0 {
t.Fatalf("skipped tensor names = %v, want none", got)
}
}
func uint32Bytes(values []uint32) []byte {
data := make([]byte, len(values)*4)
for i, value := range values {
binary.LittleEndian.PutUint32(data[i*4:], value)
}
return data
}
@@ -0,0 +1,41 @@
//go:build !darwin && !linux
package qwen4_exp
import (
"fmt"
"os"
)
type hostMapping struct {
file *os.File
size int64
}
func openHostMapping(path string) (*hostMapping, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
info, err := f.Stat()
if err != nil {
f.Close()
return nil, err
}
return &hostMapping{file: f, size: info.Size()}, nil
}
func (m *hostMapping) bytes(start, end int64) ([]byte, error) {
if start < 0 || end < start || end > m.size {
return nil, fmt.Errorf("mapping range [%d:%d] outside %d bytes", start, end, m.size)
}
data := make([]byte, end-start)
if _, err := m.file.ReadAt(data, start); err != nil {
return nil, err
}
return data, nil
}
func (m *hostMapping) close() error {
return m.file.Close()
}
@@ -0,0 +1,27 @@
//go:build !darwin && !linux
package qwen4_exp
import (
"os"
"path/filepath"
"testing"
)
func TestHostMappingRejectsShortRead(t *testing.T) {
path := filepath.Join(t.TempDir(), "tensor")
if err := os.WriteFile(path, []byte{1, 2, 3, 4}, 0o600); err != nil {
t.Fatal(err)
}
m, err := openHostMapping(path)
if err != nil {
t.Fatal(err)
}
defer m.close()
if err := os.Truncate(path, 2); err != nil {
t.Fatal(err)
}
if _, err := m.bytes(0, 4); err == nil {
t.Fatal("accepted a short read with zero-filled tensor data")
}
}
@@ -0,0 +1,55 @@
//go:build darwin || linux
package qwen4_exp
import (
"fmt"
"os"
"golang.org/x/sys/unix"
)
type hostMapping struct {
data []byte
}
func openHostMapping(path string) (*hostMapping, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return nil, err
}
if info.Size() <= 0 || info.Size() > int64(^uint(0)>>1) {
return nil, fmt.Errorf("invalid mapping size %d", info.Size())
}
data, err := unix.Mmap(int(f.Fd()), 0, int(info.Size()), unix.PROT_READ, unix.MAP_SHARED)
if err != nil {
return nil, err
}
// PLE row IDs are hashes spread across the table. Disabling sequential
// readahead keeps untouched pages reclaimable under memory pressure.
_ = unix.Madvise(data, unix.MADV_RANDOM)
return &hostMapping{data: data}, nil
}
func (m *hostMapping) bytes(start, end int64) ([]byte, error) {
if start < 0 || end < start || end > int64(len(m.data)) {
return nil, fmt.Errorf("mapping range [%d:%d] outside %d bytes", start, end, len(m.data))
}
return m.data[start:end], nil
}
func (m *hostMapping) close() error {
if len(m.data) == 0 {
return nil
}
err := unix.Munmap(m.data)
m.data = nil
return err
}
+146 -97
View File
@@ -1,13 +1,135 @@
package qwen4_exp
import (
"fmt"
"math"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/nn"
)
type fullAttention struct {
QProj nn.LinearLayer
KProj nn.LinearLayer
VProj nn.LinearLayer
OProj nn.LinearLayer
QNorm *nn.RMSNorm
KNorm *nn.RMSNorm
Indexer *attentionIndexer
}
type attentionIndexer struct {
QKProj nn.LinearLayer
QNorm *nn.RMSNorm
KNorm *nn.RMSNorm
}
func loadFullAttention(linears model.LinearFactory, tensors map[string]*mlx.Array, prefix string, eps float32) (*fullAttention, error) {
a := &fullAttention{
QProj: linears.Make(prefix + ".q_proj"),
KProj: linears.Make(prefix + ".k_proj"),
VProj: linears.Make(prefix + ".v_proj"),
OProj: linears.Make(prefix + ".o_proj"),
}
var err error
if a.QProj == nil || a.KProj == nil || a.VProj == nil || a.OProj == nil {
return nil, fmt.Errorf("missing attention projection at %s", prefix)
}
if a.QNorm, err = loadNorm(tensors, prefix+".q_norm", eps); err != nil {
return nil, err
}
if a.KNorm, err = loadNorm(tensors, prefix+".k_norm", eps); err != nil {
return nil, err
}
idx := &attentionIndexer{}
if idx.QKProj, err = requiredLinear(linears, prefix+".indexer.index_qk_proj"); err != nil {
return nil, err
}
if idx.QNorm, err = loadNorm(tensors, prefix+".indexer.q_layernorm", eps); err != nil {
return nil, err
}
if idx.KNorm, err = loadNorm(tensors, prefix+".indexer.k_layernorm", eps); err != nil {
return nil, err
}
a.Indexer = idx
return a, nil
}
func (a *fullAttention) Forward(x *mlx.Array, b *batch.Batch, c, side cache.Cache, ropePositions *mlx.Array, cfg *Config) *mlx.Array {
dims := x.Dims()
B, L := int32(dims[0]), int32(dims[1])
qg := mlx.Reshape(a.QProj.Forward(x), B, L, cfg.NumAttentionHeads, cfg.HeadDim*2)
q := qg.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(0, int(cfg.HeadDim)))
gate := qg.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(int(cfg.HeadDim), mlx.End))
gate = mlx.Reshape(gate, B, L, cfg.NumAttentionHeads*cfg.HeadDim)
k := mlx.Reshape(a.KProj.Forward(x), B, L, cfg.NumKeyValueHeads, cfg.HeadDim)
v := mlx.Reshape(a.VProj.Forward(x), B, L, cfg.NumKeyValueHeads, cfg.HeadDim)
q = a.QNorm.Forward(q, cfg.RMSNormEps)
k = a.KNorm.Forward(k, cfg.RMSNormEps)
q = mlx.Transpose(q, 0, 2, 1, 3)
k = mlx.Transpose(k, 0, 2, 1, 3)
v = mlx.Transpose(v, 0, 2, 1, 3)
cos, sin := qsaRopeCosSin(cfg, ropePositions)
q = applyQwenRoPE(q, cos, sin, cfg.RopeDim)
k = applyQwenRoPE(k, cos, sin, cfg.RopeDim)
indexQ, rawIndexK := a.Indexer.Forward(x, cos, sin, cfg)
var mainHistory, indexHistory *nn.KVHistory
if c != nil {
mainHistory = c.(cache.Attention).Update(b, k, v)
if side == nil {
panic("QSA side cache is missing")
}
indexHistory = side.(cache.Attention).Update(b, rawIndexK, ropePositions)
}
var out *mlx.Array
keyLength := L
for _, offset := range b.SeqOffsets {
keyLength = max(keyLength, offset+L)
}
if mainHistory == nil {
out = nn.ScaledDotProductAttention(b, q, cfg.Scale,
nn.WithKV(k, v, b.SeqQueryLens), nn.WithMask(nn.CausalMask()))
} else if keyLength <= cfg.IndexerBudget {
// QSA selects the entire visible history within the indexer budget.
out = nn.ScaledDotProductAttention(b, q, cfg.Scale,
nn.WithKVHistory(mainHistory), nn.WithMask(nn.CausalMask()))
} else {
compressed := qsaCompressedKeys(indexHistory.K(), indexHistory.V(), a.Indexer, cfg)
scores := mlx.Matmul(indexQ.AsType(mlx.DTypeFloat32), mlx.Transpose(compressed.AsType(mlx.DTypeFloat32), 0, 1, 3, 2))
scores = mlx.DivScalar(mlx.Sum(mlx.ReLU(scores), 1, false), float32(math.Sqrt(float64(cfg.IndexerHeadDim))))
blocks, queryEnds := qsaLogicalBlocks(scores, b, keyLength, cfg)
out = qsaSparseAttention(q, mainHistory, blocks, queryEnds, cfg)
}
out = mlx.Reshape(mlx.Transpose(out, 0, 2, 1, 3), B, L, cfg.NumAttentionHeads*cfg.HeadDim)
out = mlx.Mul(out, mlx.Sigmoid(gate))
return a.OProj.Forward(out)
}
func (a *attentionIndexer) Forward(x, cos, sin *mlx.Array, cfg *Config) (*mlx.Array, *mlx.Array) {
B, L := int32(x.Dim(0)), int32(x.Dim(1))
projected := a.QKProj.Forward(x)
split := int(cfg.IndexerNumHeads * cfg.IndexerHeadDim)
q := projected.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(0, split))
k := projected.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(split, int((cfg.IndexerNumHeads+cfg.IndexerKVHeads)*cfg.IndexerHeadDim)))
q = mlx.Reshape(q, B, L, cfg.IndexerNumHeads, cfg.IndexerHeadDim)
q = a.QNorm.Forward(q, cfg.RMSNormEps)
q = applyQwenRoPE(mlx.Transpose(q, 0, 2, 1, 3), cos, sin, cfg.RopeDim)
// Keys must stay raw in the cache: compression averages in FP32 before
// normalization and applies RoPE at each complete block's first position.
k = mlx.Transpose(mlx.Reshape(k, B, L, cfg.IndexerKVHeads, cfg.IndexerHeadDim), 0, 2, 1, 3)
return q, k
}
// canonicalRopePositionRows returns exact [B, 1, L, 3] position rows. MRoPE
// input is the channel-major [B][3][L] layout used by the vision path.
func canonicalRopePositionRows(b *batch.Batch, L int32, mrope []int32) *mlx.Array {
@@ -57,19 +179,10 @@ func qsaRopeCosSin(cfg *Config, positions *mlx.Array) (cos, sin *mlx.Array) {
func applyQwenRoPE(x, cos, sin *mlx.Array, ropeDim int32) *mlx.Array {
headDim := int32(x.Dim(3))
rot := mlx.SliceStartStop(x,
[]int32{0, 0, 0, 0},
[]int32{int32(x.Dim(0)), int32(x.Dim(1)), int32(x.Dim(2)), ropeDim},
)
half := ropeDim / 2
left := mlx.SliceStartStop(rot,
[]int32{0, 0, 0, 0},
[]int32{int32(rot.Dim(0)), int32(rot.Dim(1)), int32(rot.Dim(2)), half},
)
right := mlx.SliceStartStop(rot,
[]int32{0, 0, 0, half},
[]int32{int32(rot.Dim(0)), int32(rot.Dim(1)), int32(rot.Dim(2)), ropeDim},
)
rot := x.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(0, int(ropeDim)))
half := int(ropeDim / 2)
left := rot.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(0, half))
right := rot.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(half, mlx.End))
rotated := mlx.Concatenate([]*mlx.Array{mlx.Neg(right), left}, -1)
out := mlx.Add(
mlx.Mul(rot, cos.AsType(x.DType())),
@@ -78,10 +191,7 @@ func applyQwenRoPE(x, cos, sin *mlx.Array, ropeDim int32) *mlx.Array {
if ropeDim == headDim {
return out
}
pass := mlx.SliceStartStop(x,
[]int32{0, 0, 0, ropeDim},
[]int32{int32(x.Dim(0)), int32(x.Dim(1)), int32(x.Dim(2)), headDim},
)
pass := x.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(int(ropeDim), mlx.End))
return mlx.Concatenate([]*mlx.Array{out, pass}, -1)
}
@@ -89,30 +199,23 @@ func qsaCompressedKeys(rawKeys, positions *mlx.Array, indexer *attentionIndexer,
ratio := cfg.IndexerCompressRatio
groups := int32(rawKeys.Dim(2)) / ratio
complete := groups * ratio
rawKeys = mlx.SliceStartStop(rawKeys,
[]int32{0, 0, 0, 0},
[]int32{int32(rawKeys.Dim(0)), int32(rawKeys.Dim(1)), complete, int32(rawKeys.Dim(3))},
)
rawKeys = rawKeys.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(0, int(complete)), mlx.Slice())
rawKeys = mlx.Reshape(rawKeys, int32(rawKeys.Dim(0)), int32(rawKeys.Dim(1)), groups, ratio, cfg.IndexerHeadDim)
pooled := mlx.Mean(rawKeys.AsType(mlx.DTypeFloat32), 3, false).AsType(rawKeys.DType())
pooled = indexer.KNorm.Forward(pooled, cfg.RMSNormEps)
positions = mlx.SliceStartStop(positions,
[]int32{0, 0, 0, 0},
[]int32{int32(positions.Dim(0)), int32(positions.Dim(1)), complete, int32(positions.Dim(3))},
)
positions = positions.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(0, int(complete)), mlx.Slice())
positions = mlx.Reshape(positions, int32(positions.Dim(0)), int32(positions.Dim(1)), groups, ratio, 3)
positions = mlx.Squeeze(mlx.SliceStartStop(positions,
[]int32{0, 0, 0, 0, 0},
[]int32{int32(positions.Dim(0)), int32(positions.Dim(1)), groups, 1, 3},
), 3)
positions = mlx.Squeeze(positions.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(0), mlx.Slice()), 3)
cos, sin := qsaRopeCosSin(cfg, positions)
return applyQwenRoPE(pooled, cos, sin, cfg.RopeDim)
}
// qsaLogicalIndices reproduces the reference's compressed-block top-k and
// incomplete-group tail. Invalid rows are kept as zero indices with a mask.
func qsaLogicalIndices(scores *mlx.Array, b *batch.Batch, keyLength int32, cfg *Config) (indices, valid *mlx.Array) {
// qsaLogicalBlocks reproduces the reference's compressed-block top-k.
// Blocks outside a query's causal history are represented by -1; queryEnds
// lets attention append the incomplete causal block without expanding the
// selected blocks into per-token indices.
func qsaLogicalBlocks(scores *mlx.Array, b *batch.Batch, keyLength int32, cfg *Config) (selected, queryEnds *mlx.Array) {
B, L := int32(scores.Dim(0)), int32(scores.Dim(1))
ratio := cfg.IndexerCompressRatio
blocks := keyLength / ratio
@@ -132,73 +235,19 @@ func qsaLogicalIndices(scores *mlx.Array, b *batch.Batch, keyLength int32, cfg *
if blocks > selectedCount {
fill := mlx.AddScalar(mlx.Zeros(scores.DType(), int(B), int(L), int(blocks)), -float32(math.MaxFloat32))
masked := mlx.Where(blockValid, scores, fill)
selected := mlx.Argpartition(mlx.Neg(masked), int(selectedCount)-1, -1)
indices = mlx.SliceStartStop(selected,
[]int32{0, 0, 0},
[]int32{B, L, selectedCount},
)
partitioned := mlx.Argpartition(mlx.Neg(masked), int(selectedCount)-1, -1)
selected = partitioned.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(0, int(selectedCount)))
} else {
indices = mlx.Tile(blockIDs, []int32{B, L, 1})
selected = mlx.Tile(blockIDs, []int32{B, L, 1})
}
blockValid = indices.Less(visibleBlocks)
blockValid = selected.Less(visibleBlocks)
invalid := mlx.AddScalar(mlx.Zeros(mlx.DTypeInt32, int(B), int(L), int(selectedCount)), -1)
selected = mlx.Where(blockValid, selected, invalid).AsType(mlx.DTypeInt32)
return selected, mlx.Reshape(visibleTokens, B, L).AsType(mlx.DTypeInt32)
}
offsets := mlx.Reshape(mlx.Arange(0, float64(ratio), 1, mlx.DTypeInt32), 1, 1, 1, ratio)
expanded := mlx.Add(mlx.MulScalar(mlx.ExpandDims(indices, -1), float32(ratio)), offsets)
expandedValid := mlx.Mul(
mlx.ExpandDims(blockValid.AsType(mlx.DTypeInt32), -1),
expanded.Less(mlx.ExpandDims(visibleTokens, -1)).AsType(mlx.DTypeInt32),
func qsaSparseAttention(q *mlx.Array, history *nn.KVHistory, blocks, queryEnds *mlx.Array, cfg *Config) *mlx.Array {
return mlx.IndexedBlockScaledDotProductAttention(
q, history.K(), history.V(), blocks, queryEnds, int(cfg.IndexerCompressRatio), cfg.Scale,
)
expanded = mlx.Reshape(expanded, B, L, selectedCount*ratio)
expandedValid = mlx.Reshape(expandedValid, B, L, selectedCount*ratio)
// The current partial compression group is always attended causally.
tailWidth := ratio - 1
tailOffsets := mlx.Reshape(mlx.Arange(0, float64(tailWidth), 1, mlx.DTypeInt32), 1, 1, tailWidth)
tailStart := mlx.MulScalar(mlx.FloorDivideScalar(visibleTokens, ratio), float32(ratio))
tail := mlx.Add(tailStart, tailOffsets)
tailCount := mlx.Sub(visibleTokens, tailStart)
tailValid := tailOffsets.Less(tailCount).AsType(mlx.DTypeInt32)
indices = mlx.Concatenate([]*mlx.Array{expanded, tail}, -1)
validInt := mlx.Concatenate([]*mlx.Array{expandedValid, tailValid}, -1)
valid = validInt.Greater(mlx.Zeros(mlx.DTypeInt32, int(B), int(L), validInt.Dim(2)))
indices = mlx.Where(valid, indices, mlx.Zeros(mlx.DTypeInt32, int(B), int(L), indices.Dim(2)))
return indices, valid
}
func qsaSparseAttention(q *mlx.Array, history *nn.KVHistory, indices, valid *mlx.Array, cfg *Config) *mlx.Array {
outputType := q.DType()
B, queryHeads, L, D := int32(q.Dim(0)), int32(q.Dim(1)), int32(q.Dim(2)), int32(q.Dim(3))
kvHeads := cfg.NumKeyValueHeads
repeats := queryHeads / kvHeads
k := qsaGatherHistory(history.K(), indices)
v := qsaGatherHistory(history.V(), indices)
qr := mlx.Reshape(q, B, kvHeads, repeats, L, 1, D)
kr := mlx.Transpose(mlx.ExpandDims(k, 2), 0, 1, 2, 3, 5, 4)
scores := mlx.Squeeze(mlx.Matmul(qr.AsType(mlx.DTypeFloat32), kr.AsType(mlx.DTypeFloat32)), 4)
scores = mlx.MulScalar(scores, cfg.Scale)
mask := mlx.ExpandDims(mlx.ExpandDims(valid, 1), 1)
fill := mlx.AddScalar(mlx.Zeros(scores.DType(), scores.Dims()...), -float32(math.MaxFloat32))
scores = mlx.Where(mask, scores, fill)
probs := mlx.SoftmaxAxis(scores, -1, true)
vr := mlx.ExpandDims(v.AsType(mlx.DTypeFloat32), 2)
out := mlx.Matmul(mlx.ExpandDims(probs, 4), vr)
out = mlx.Squeeze(out, 4)
return mlx.Reshape(out, B, queryHeads, L, D).AsType(outputType)
}
// qsaGatherHistory selects each batch row's logical token indices from a
// [B, H, K, D] cache history and returns [B, H, L, S, D].
func qsaGatherHistory(history, indices *mlx.Array) *mlx.Array {
B, H, K, D := int32(history.Dim(0)), int32(history.Dim(1)), int32(history.Dim(2)), int32(history.Dim(3))
offsets := make([]int32, B)
for i := range offsets {
offsets[i] = int32(i) * K
}
logical := mlx.Add(indices, mlx.FromValues(offsets, int(B), 1, 1))
flattened := mlx.Reshape(mlx.Transpose(history, 1, 0, 2, 3), H, B*K, D)
return mlx.Transpose(mlx.Take(flattened, logical, 1), 1, 0, 2, 3, 4)
}
+31 -39
View File
@@ -17,22 +17,19 @@ func TestQSASelectsCompressedBlocksAndCausalTail(t *testing.T) {
scores := mlx.FromValues([]float32{0.1, 4, 2, 3}, 1, 1, 4)
b := &batch.Batch{SeqOffsets: []int32{16}}
indices, valid := qsaLogicalIndices(scores, b, 16, cfg)
indices = indices.AsType(mlx.DTypeInt32)
valid = valid.AsType(mlx.DTypeInt32)
mlx.Eval(indices, valid)
values, mask := indices.Ints(), valid.Ints()
selected := make([]int32, 0, len(values))
for i, value := range values {
if mask[i] != 0 {
selected = append(selected, value)
}
blocks, queryEnds := qsaLogicalBlocks(scores, b, 16, cfg)
if blocks.DType() != mlx.DTypeInt32 {
t.Fatalf("blocks dtype = %v, want int32", blocks.DType())
}
slices.Sort(selected)
want := []int32{4, 5, 6, 7, 12, 13, 14, 15, 16}
if !slices.Equal(selected, want) {
t.Fatalf("selected indices = %v, want %v", selected, want)
mlx.Eval(blocks, queryEnds)
got := blocks.Ints()
slices.Sort(got)
if want := []int32{1, 3}; !slices.Equal(got, want) {
t.Fatalf("selected blocks = %v, want %v", got, want)
}
if got, want := queryEnds.Ints(), []int32{17}; !slices.Equal(got, want) {
t.Fatalf("query ends = %v, want %v", got, want)
}
})
}
@@ -45,34 +42,29 @@ func TestQSASelectionMasksFutureBlocks(t *testing.T) {
scores := mlx.FromValues([]float32{0.1, 100, 90, 80, 70}, 1, 1, 5)
b := &batch.Batch{SeqOffsets: []int32{4}}
indices, valid := qsaLogicalIndices(scores, b, 20, cfg)
indices = indices.AsType(mlx.DTypeInt32)
valid = valid.AsType(mlx.DTypeInt32)
mlx.Eval(indices, valid)
blocks, queryEnds := qsaLogicalBlocks(scores, b, 20, cfg)
mlx.Eval(blocks, queryEnds)
var selected []int32
for i, value := range indices.Ints() {
if valid.Ints()[i] != 0 {
selected = append(selected, value)
}
got := blocks.Ints()
if want := []int32{0, -1}; !slices.Equal(got, want) {
t.Fatalf("selected blocks = %v, want %v", got, want)
}
slices.Sort(selected)
if want := []int32{0, 1, 2, 3, 4}; !slices.Equal(selected, want) {
t.Fatalf("selected indices = %v, want %v", selected, want)
if got, want := queryEnds.Ints(), []int32{5}; !slices.Equal(got, want) {
t.Fatalf("query ends = %v, want %v", got, want)
}
})
}
func TestQSASparseAttentionMatchesReference(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
cfg := &Config{NumKeyValueHeads: 1, Scale: 1}
cfg := &Config{NumKeyValueHeads: 1, IndexerCompressRatio: 1, Scale: 1}
q := mlx.FromValues([]float32{1, 0}, 1, 1, 1, 2)
k := mlx.FromValues([]float32{1, 0, 0, 1, 2, 0}, 1, 1, 3, 2)
v := mlx.FromValues([]float32{10, 1, 20, 2, 30, 3}, 1, 1, 3, 2)
indices := mlx.FromValues([]int32{2, 0}, 1, 1, 2)
valid := mlx.FromValues([]bool{true, true}, 1, 1, 2)
blocks := mlx.FromValues([]int32{2, 0}, 1, 1, 2)
queryEnds := mlx.FromValues([]int32{3}, 1, 1)
out := qsaSparseAttention(q, nn.NewKVHistory(k, v, nil), indices, valid, cfg)
out := qsaSparseAttention(q, nn.NewKVHistory(k, v, nil), blocks, queryEnds, cfg)
out = out.AsType(mlx.DTypeFloat32)
mlx.Eval(out)
got := out.Floats()
@@ -88,15 +80,15 @@ func TestQSASparseAttentionMatchesReference(t *testing.T) {
func TestQSASparseAttentionIgnoresInvalidRows(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
cfg := &Config{NumKeyValueHeads: 1, Scale: 1}
cfg := &Config{NumKeyValueHeads: 1, IndexerCompressRatio: 1, Scale: 1}
q := mlx.FromValues([]float32{1, 0}, 1, 1, 1, 2)
// Row 0 is intentionally dominant junk. Only row 1 is logically valid.
k := mlx.FromValues([]float32{100, 0, 1, 0}, 1, 1, 2, 2)
v := mlx.FromValues([]float32{999, 999, 7, 3}, 1, 1, 2, 2)
indices := mlx.FromValues([]int32{0, 1}, 1, 1, 2)
valid := mlx.FromValues([]bool{false, true}, 1, 1, 2)
blocks := mlx.FromValues([]int32{-1, 1}, 1, 1, 2)
queryEnds := mlx.FromValues([]int32{2}, 1, 1)
out := qsaSparseAttention(q, nn.NewKVHistory(k, v, nil), indices, valid, cfg)
out := qsaSparseAttention(q, nn.NewKVHistory(k, v, nil), blocks, queryEnds, cfg)
out = out.AsType(mlx.DTypeFloat32)
mlx.Eval(out)
if got, want := out.Floats(), []float32{7, 3}; !slices.Equal(got, want) {
@@ -107,7 +99,7 @@ func TestQSASparseAttentionIgnoresInvalidRows(t *testing.T) {
func TestQSASparseAttentionKeepsBatchRowsIndependent(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
cfg := &Config{NumKeyValueHeads: 1, Scale: 1}
cfg := &Config{NumKeyValueHeads: 1, IndexerCompressRatio: 1, Scale: 1}
q := mlx.FromValues([]float32{1, 0, 1, 0}, 2, 1, 1, 2)
k := mlx.FromValues([]float32{
1, 0, 0, 1,
@@ -117,10 +109,10 @@ func TestQSASparseAttentionKeepsBatchRowsIndependent(t *testing.T) {
10, 1, 20, 2,
30, 3, 40, 4,
}, 2, 1, 2, 2)
indices := mlx.FromValues([]int32{0, 1}, 2, 1, 1)
valid := mlx.FromValues([]bool{true, true}, 2, 1, 1)
blocks := mlx.FromValues([]int32{0, 1}, 2, 1, 1)
queryEnds := mlx.FromValues([]int32{2, 2}, 2, 1)
out := qsaSparseAttention(q, nn.NewKVHistory(k, v, nil), indices, valid, cfg)
out := qsaSparseAttention(q, nn.NewKVHistory(k, v, nil), blocks, queryEnds, cfg)
out = out.AsType(mlx.DTypeFloat32)
mlx.Eval(out)
if got, want := out.Floats(), []float32{10, 1, 40, 4}; !slices.Equal(got, want) {
+144 -100
View File
@@ -18,10 +18,11 @@ func init() {
}
var (
_ model.Model = (*Model)(nil)
_ model.SelfDraft = (*Model)(nil)
_ model.DraftModel = (*mtpDraft)(nil)
_ model.MediaModel = (*Model)(nil)
_ model.Model = (*Model)(nil)
_ model.SkippedTensorsModel = (*Model)(nil)
_ model.SelfDraft = (*Model)(nil)
_ model.DraftModel = (*mtpDraft)(nil)
_ model.MediaModel = (*Model)(nil)
)
// Model carries the validated architecture and tokenizer.
@@ -40,6 +41,8 @@ type Model struct {
quantMode string
tensorQuant map[string]*model.TensorQuantInfo
configData []byte
hostPLE map[string]*hostPLETable
numCaches int
}
// NewModel validates the publisher config before constructing runtime state.
@@ -72,6 +75,10 @@ func NewModel(root *model.Root) (model.Model, error) {
if root.GroupSize() > 0 {
group = root.GroupSize()
}
hostPLE, err := openHostPLETables(root, &cfg)
if err != nil {
return nil, fmt.Errorf("open host-backed PLE: %w", err)
}
return &Model{
Config: &cfg,
Layers: make([]*Layer, cfg.NumHiddenLayers),
@@ -81,43 +88,85 @@ func NewModel(root *model.Root) (model.Model, error) {
quantMode: mode,
tensorQuant: root.AllTensorQuant(),
configData: configData,
hostPLE: hostPLE,
}, nil
}
func (m *Model) NewCaches() []cache.Cache {
fullLayers := 0
for _, layer := range m.Layers {
func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
linears := model.NewLinearFactory(tensors, m.quantGroup, m.quantBits, m.quantMode, m.tensorQuant)
var err error
m.EmbedTokens = model.MakeEmbeddingLayer(tensors, "model.language_model.embed_tokens", m.quantGroup, m.quantBits, m.quantMode, m.tensorQuant)
if m.EmbedTokens == nil {
return fmt.Errorf("missing embedding weight")
}
if m.LMHead, err = requiredLinear(linears, "lm_head"); err != nil {
return err
}
if m.OutputMixer, err = loadHyperConnection(linears, tensors, "model.language_model.hyper_connection_mixer", false, m.Config); err != nil {
return err
}
m.numCaches = len(m.Layers)
for i := range m.Layers {
prefix := fmt.Sprintf("model.language_model.layers.%d", i)
if m.Layers[i], err = m.loadLayer(linears, tensors, prefix, m.LayerTypes[i], i); err != nil {
return fmt.Errorf("load layer %d: %w", i, err)
}
layer := m.Layers[i]
if layer.Attention != nil {
fullLayers++
layer.indexerCache = m.numCaches
m.numCaches++
}
if layer.PLE != nil {
layer.pleCache = m.numCaches
m.numCaches++
}
}
caches := make([]cache.Cache, 0, len(m.Layers)+fullLayers+1)
if m.MTP, err = m.loadMTP(linears, tensors); err != nil {
return fmt.Errorf("load MTP: %w", err)
}
m.Vision, err = qwen3_5.NewVisionAdapter(m.configData, tensors, qwen3_5.VisionAdapterConfig{
HiddenSize: m.HiddenSize,
RopeDim: m.RopeDim,
RopeTheta: m.RopeParameters.RopeTheta,
MropeSection: m.RopeParameters.MRoPESection,
QuantGroup: m.quantGroup,
QuantBits: m.quantBits,
QuantMode: m.quantMode,
TensorQuant: m.tensorQuant,
})
if err != nil {
return fmt.Errorf("load vision tower: %w", err)
}
return nil
}
func (m *Model) NewCaches() []cache.Cache {
caches := make([]cache.Cache, m.numCaches)
convTail := m.LinearConvKernelDim - 1
convDim := 2*m.LinearNumKeyHeads*m.LinearKeyHeadDim + m.LinearNumValueHeads*m.LinearValueHeadDim
for i := range m.Layers {
if m.layerIsLinear(i) {
caches = append(caches, cache.NewRecurrentCache(convTail, convDim, m.LinearNumValueHeads, m.LinearValueHeadDim, m.LinearKeyHeadDim))
for i, layer := range m.Layers {
if layer.Linear != nil {
caches[i] = cache.NewRecurrentCache(convTail, convDim, m.LinearNumValueHeads, m.LinearValueHeadDim, m.LinearKeyHeadDim)
} else {
caches = append(caches, cache.NewKVCache())
caches[i] = cache.NewKVCache()
// QSA retains raw index keys and exact 3-axis positions separately
// from the attention's rotated keys and values.
caches[layer.indexerCache] = cache.NewKVCache()
}
if layer.PLE != nil {
caches[layer.pleCache] = layer.PLE.NewCache(m.Config)
}
}
for range fullLayers {
// Full-history raw QSA keys plus exact 3-axis positions. This is the
// simple semantic implementation; a compressed streaming cache can
// replace it without changing the attention contract.
caches = append(caches, cache.NewKVCache())
}
caches = append(caches, newEngramCache(
int(m.NGramSize-1),
int((m.PLEConvKernelSize-1)*m.NGramSize),
int(m.HCCount*m.HiddenSize),
m.EOSTokenID,
))
return caches
}
func (m *Model) Forward(b *batch.Batch, caches []cache.Cache) (*mlx.Array, *mlx.Array) {
positions := mlx.FromValues(b.SeqOffsets, len(b.SeqOffsets))
// The runner may append draft caches; only the target's slots belong here.
if len(caches) != 0 && len(caches) < m.numCaches {
panic(fmt.Sprintf("Qwen cache count = %d, need at least %d", len(caches), m.numCaches))
}
L := int32(b.InputIDs.Dim(1))
var mrope []int32
if m.Vision != nil {
@@ -130,38 +179,25 @@ func (m *Model) Forward(b *batch.Batch, caches []cache.Cache) (*mlx.Array, *mlx.
}
hidden := expandStreams(embedding, m.Config)
var tokens *engramCache
pleCacheIndex := len(m.Layers)
for _, layer := range m.Layers {
if layer.Attention != nil {
pleCacheIndex++
}
}
if len(caches) > pleCacheIndex {
tokens, _ = caches[pleCacheIndex].(*engramCache)
}
if tokens == nil {
tokens = newEngramCache(
int(m.NGramSize-1),
int((m.PLEConvKernelSize-1)*m.NGramSize),
int(m.HCCount*m.HiddenSize),
m.EOSTokenID,
)
}
for i, layer := range m.Layers {
if layer.PLE != nil {
var tokens *engramCache
if len(caches) > 0 {
tokens = caches[layer.pleCache].(*engramCache)
} else {
tokens = layer.PLE.NewCache(m.Config)
defer tokens.Free()
}
hidden = mlx.Add(hidden, layer.PLE.Forward(hidden, b, tokens, m.Config))
}
var c cache.Cache
if i < len(caches) {
var c, side cache.Cache
if len(caches) > 0 {
c = caches[i]
if layer.Attention != nil {
side = caches[layer.indexerCache]
}
}
var side cache.Cache
if layer.Attention != nil && layer.Attention.SideCacheIndex < len(caches) {
side = caches[layer.Attention.SideCacheIndex]
}
hidden = layer.Forward(hidden, b, c, side, positions, ropePositions, m.Config)
hidden = layer.Forward(hidden, b, c, side, ropePositions, m.Config)
}
multiHidden := hidden
hidden = m.OutputMixer.Reduce(multiHidden, m.Config)
@@ -174,6 +210,10 @@ func (m *Model) Unembed(hidden *mlx.Array) *mlx.Array {
func (m *Model) Tokenizer() *tokenizer.Tokenizer { return m.tok }
func (m *Model) MaxContextLength() int {
return int(m.MaxPositionEmbeddings)
}
func (m *Model) PrepareMedia(segments []model.Segment) (*model.PreparedRequest, error) {
if m.Vision == nil {
return nil, fmt.Errorf("this model does not support media input")
@@ -185,59 +225,63 @@ func (m *Model) EncodeMedia(item *model.PreparedItem, data *mlx.Array) *mlx.Arra
return m.Vision.EncodeMedia(item, data)
}
func (m *Model) MaxContextLength() int {
return int(m.MaxPositionEmbeddings)
type Layer struct {
AttentionConnection *hyperConnection
MLPConnection *hyperConnection
Linear *linearAttention
Attention *fullAttention
MoE *sparseMoE
PLE *PLE
// Main attention/recurrent caches occupy the first len(Layers) slots.
// These indices identify this layer's additional state in the same slice.
indexerCache int
pleCache int
}
// mtpDraft views the checkpoint's inline predictor through DraftModel.
type mtpDraft Model
func (m *Model) SelfDraft() model.DraftModel {
if m.MTP == nil {
return nil
func (m *Model) loadLayer(linears model.LinearFactory, tensors map[string]*mlx.Array, prefix, kind string, layer int) (*Layer, error) {
l := &Layer{}
var err error
if l.AttentionConnection, err = loadHyperConnection(linears, tensors, prefix+".attn_hyper_connection", true, m.Config); err != nil {
return nil, err
}
return (*mtpDraft)(m)
if l.MLPConnection, err = loadHyperConnection(linears, tensors, prefix+".mlp_hyper_connection", true, m.Config); err != nil {
return nil, err
}
if kind == "linear_attention" {
if l.Linear, err = loadLinearAttention(linears, tensors, prefix+".linear_attn"); err != nil {
return nil, err
}
} else if l.Attention, err = loadFullAttention(linears, tensors, prefix+".self_attn", m.RMSNormEps); err != nil {
return nil, err
}
if l.MoE, err = m.loadSparseMoE(linears, tensors, prefix+".mlp"); err != nil {
return nil, err
}
for _, id := range m.PLELayerIDs {
// PLE layer IDs are one-based and identify the layer receiving the
// additive n-gram features before its attention branch.
if int(id-1) == layer {
l.PLE, err = m.loadPLE(linears, tensors, prefix+".ple")
if err != nil {
return nil, err
}
}
}
return l, nil
}
func (m *mtpDraft) NewCaches() []cache.Cache {
if m.MTP == nil {
return nil
func (l *Layer) Forward(x *mlx.Array, b *batch.Batch, c, side cache.Cache, ropePositions *mlx.Array, cfg *Config) *mlx.Array {
branch, state := l.AttentionConnection.Prepare(x, cfg)
if l.Linear != nil {
branch = l.Linear.Forward(branch, b, c, cfg)
} else {
branch = l.Attention.Forward(branch, b, c, side, ropePositions, cfg)
}
return []cache.Cache{cache.NewKVCache(), cache.NewKVCache()}
}
x = l.AttentionConnection.Inject(state, branch, cfg)
func (m *mtpDraft) LoadWeights(map[string]*mlx.Array) error { return nil }
func (m *mtpDraft) Unembed(x *mlx.Array) *mlx.Array { return (*Model)(m).Unembed(x) }
func (m *mtpDraft) Forward(b *batch.Batch, _, draftCaches []cache.Cache) (hidden, auxHidden *mlx.Array) {
B, L := int32(b.InputIDs.Dim(0)), int32(b.InputIDs.Dim(1))
positions := mlx.FromValues(b.SeqOffsets, len(b.SeqOffsets))
var mrope []int32
if m.Vision != nil {
mrope = m.Vision.RopePositions(b, L)
}
ropePositions := canonicalRopePositionRows(b, L, mrope)
embedding := m.EmbedTokens.Forward(b.InputIDs)
// The reference MTP is text-only: visual information reaches it through
// the target's multi-stream hidden state, while this branch embeds raw IDs.
embedding = m.MTP.FCEmbedding.Forward(m.MTP.EmbeddingNorm.Forward(embedding, m.RMSNormEps))
backbone := m.MTP.HiddenNorm.Forward(b.Hidden, m.RMSNormEps)
backbone = mlx.Reshape(backbone, B, L, m.HCCount, m.HiddenSize)
backbone = m.MTP.FCHidden.Forward(backbone)
backbone = mlx.Add(backbone, mlx.ExpandDims(embedding, -2))
backbone = mlx.Reshape(backbone, B, L, m.HCCount*m.HiddenSize)
var main, side cache.Cache
if len(draftCaches) > 0 {
main = draftCaches[0]
}
if len(draftCaches) > 1 {
side = draftCaches[1]
}
multi := m.MTP.Layer.Forward(backbone, b, main, side, positions, ropePositions, m.Config)
sample := m.MTP.Mixer.Reduce(multi, m.Config)
return sample, multi
branch, state = l.MLPConnection.Prepare(x, cfg)
branch = l.MoE.Forward(branch, cfg)
return l.MLPConnection.Inject(state, branch, cfg)
}
-427
View File
@@ -5,145 +5,9 @@ import (
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlxrunner/model"
"github.com/ollama/ollama/mlxrunner/model/qwen3_5"
"github.com/ollama/ollama/mlxrunner/nn"
)
type hyperConnection struct {
Norm *streamRMSNorm
InputMixDown nn.LinearLayer
InputMixUp nn.LinearLayer
BlockInject nn.LinearLayer
}
type linearAttention struct {
QKV nn.LinearLayer
Z nn.LinearLayer
B nn.LinearLayer
A nn.LinearLayer
Out nn.LinearLayer
Conv *nn.Conv1d
NormWeight *mlx.Array
DtBias *mlx.Array
ALog *mlx.Array
AExp *mlx.Array
}
type attentionIndexer struct {
QKProj nn.LinearLayer
QNorm *nn.RMSNorm
KNorm *nn.RMSNorm
}
type fullAttention struct {
QProj nn.LinearLayer
KProj nn.LinearLayer
VProj nn.LinearLayer
OProj nn.LinearLayer
QNorm *nn.RMSNorm
KNorm *nn.RMSNorm
Indexer *attentionIndexer
SideCacheIndex int
}
type sparseMoE struct {
Gate nn.LinearLayer
GateUpExperts *mlx.Array
GateUpScales *mlx.Array
GateUpBiases *mlx.Array
DownExperts *mlx.Array
DownScales *mlx.Array
DownBiases *mlx.Array
GateUpGroup int
GateUpBits int
GateUpMode string
DownGroup int
DownBits int
DownMode string
SharedGate nn.LinearLayer
SharedGateProj nn.LinearLayer
SharedUpProj nn.LinearLayer
SharedDownProj nn.LinearLayer
}
func supportsGatherQMM(mode string, bits int) bool {
switch mode {
case "affine":
return bits == 4 || bits == 8
case "mxfp8":
return bits == 8
case "nvfp4", "mxfp4":
return bits == 4
default:
return false
}
}
func loadPackedExperts(tensors map[string]*mlx.Array, base string, m *Model) (weight, scales, biases *mlx.Array, group, bits int, mode string, err error) {
var key string
for _, candidate := range []string{base, base + ".weight"} {
if weight = tensors[candidate]; weight != nil {
key = candidate
break
}
}
if weight == nil {
return nil, nil, nil, 0, 0, "", fmt.Errorf("missing packed expert tensor %q", base)
}
scales = tensors[key+"_scale"]
if scales == nil {
return mlx.Transpose(weight, 0, 2, 1), nil, nil, 0, 0, "", nil
}
biases = tensors[key+"_qbias"]
group, bits, mode = model.ResolveLinearQuantParams(m.quantGroup, m.quantBits, m.quantMode, m.tensorQuant, key, weight, scales)
if !supportsGatherQMM(mode, bits) {
return nil, nil, nil, 0, 0, "", fmt.Errorf("packed expert tensor %q uses unsupported quantization mode=%q bits=%d", key, mode, bits)
}
return weight, scales, biases, group, bits, mode, nil
}
// PLE is the model's n-gram embedding block. The checkpoint stores one logical
// table in split vocabulary shards.
type PLE struct {
Conv *nn.Conv1d
KeyProj nn.LinearLayer
ValueProj nn.LinearLayer
NormConv *streamRMSNorm
NormKey *streamRMSNorm
NormQuery *streamRMSNorm
LayerMultipliers *mlx.Array
HeadOffsets *mlx.Array
HeadVocabSizes *mlx.Array
EmbeddingShards []nn.EmbeddingLayer
ShardRows int
}
type streamRMSNorm struct {
Weight *mlx.Array
}
type Layer struct {
AttentionConnection *hyperConnection
MLPConnection *hyperConnection
Linear *linearAttention
Attention *fullAttention
MoE *sparseMoE
PLE *PLE
}
type MTPHead struct {
EmbeddingNorm *nn.RMSNorm
HiddenNorm *nn.RMSNorm
FCEmbedding nn.LinearLayer
FCHidden nn.LinearLayer
Mixer *hyperConnection
Layer *Layer
}
func requiredArray(tensors map[string]*mlx.Array, names ...string) (*mlx.Array, error) {
for _, name := range names {
if value := tensors[name]; value != nil {
@@ -169,294 +33,3 @@ func loadNorm(tensors map[string]*mlx.Array, name string, eps float32) (*nn.RMSN
// Qwen 4 RMSNorm weights are stored zero-centered.
return nn.NewRMSNorm(mlx.AddScalar(weight, 1), eps), nil
}
func loadStreamNorm(tensors map[string]*mlx.Array, name string, cfg *Config) (*streamRMSNorm, error) {
weight, err := requiredArray(tensors, name+".weight", name)
if err != nil {
return nil, err
}
if weight.Size() != int(cfg.HCCount*cfg.HiddenSize) {
return nil, fmt.Errorf("%s has %d elements, want %d", name, weight.Size(), cfg.HCCount*cfg.HiddenSize)
}
weight = mlx.Reshape(mlx.AddScalar(weight, 1), cfg.HCCount, cfg.HiddenSize)
return &streamRMSNorm{Weight: weight}, nil
}
func loadHyperConnection(linears model.LinearFactory, tensors map[string]*mlx.Array, prefix string, withInjection bool, cfg *Config) (*hyperConnection, error) {
h := &hyperConnection{}
var err error
if h.Norm, err = loadStreamNorm(tensors, prefix+".hc_norm", cfg); err != nil {
return nil, err
}
if h.InputMixDown, err = requiredLinear(linears, prefix+".input_mix_weight_down"); err != nil {
return nil, err
}
if h.InputMixUp, err = requiredLinear(linears, prefix+".input_mix_weight_up"); err != nil {
return nil, err
}
if withInjection {
if h.BlockInject, err = requiredLinear(linears, prefix+".block_inject_weight"); err != nil {
return nil, err
}
}
return h, nil
}
func loadLinearAttention(linears model.LinearFactory, tensors map[string]*mlx.Array, prefix string) (*linearAttention, error) {
a := &linearAttention{}
var err error
for name, dst := range map[string]*nn.LinearLayer{
"in_proj_qkv": &a.QKV,
"in_proj_z": &a.Z,
"in_proj_b": &a.B,
"in_proj_a": &a.A,
"out_proj": &a.Out,
} {
*dst, err = requiredLinear(linears, prefix+"."+name)
if err != nil {
return nil, err
}
}
convWeight, err := requiredArray(tensors, prefix+".conv1d.weight", prefix+".conv1d")
if err != nil {
return nil, err
}
if convWeight.NumDims() == 3 && convWeight.Dim(1) == 1 {
convWeight = mlx.Reshape(convWeight, int32(convWeight.Dim(0)), int32(convWeight.Dim(2)))
}
if convWeight.NumDims() != 2 {
return nil, fmt.Errorf("%s.conv1d weight must reduce to 2D, got %dD", prefix, convWeight.NumDims())
}
a.Conv = nn.NewConv1d(mlx.ExpandDims(convWeight, 2), nil, 1, 0, 1, int32(convWeight.Dim(0)))
if a.NormWeight, err = requiredArray(tensors, prefix+".norm.weight", prefix+".norm"); err != nil {
return nil, err
}
if a.DtBias, err = requiredArray(tensors, prefix+".dt_bias", prefix+".dt_proj"); err != nil {
return nil, err
}
if a.ALog, err = requiredArray(tensors, prefix+".A_log", prefix+".a_log"); err != nil {
return nil, err
}
a.AExp = mlx.Exp(a.ALog.AsType(mlx.DTypeFloat32))
return a, nil
}
func loadFullAttention(linears model.LinearFactory, tensors map[string]*mlx.Array, prefix string, eps float32) (*fullAttention, error) {
a := &fullAttention{}
var err error
for name, dst := range map[string]*nn.LinearLayer{
"q_proj": &a.QProj,
"k_proj": &a.KProj,
"v_proj": &a.VProj,
"o_proj": &a.OProj,
} {
*dst, err = requiredLinear(linears, prefix+"."+name)
if err != nil {
return nil, err
}
}
if a.QNorm, err = loadNorm(tensors, prefix+".q_norm", eps); err != nil {
return nil, err
}
if a.KNorm, err = loadNorm(tensors, prefix+".k_norm", eps); err != nil {
return nil, err
}
idx := &attentionIndexer{}
if idx.QKProj, err = requiredLinear(linears, prefix+".indexer.index_qk_proj"); err != nil {
return nil, err
}
if idx.QNorm, err = loadNorm(tensors, prefix+".indexer.q_layernorm", eps); err != nil {
return nil, err
}
if idx.KNorm, err = loadNorm(tensors, prefix+".indexer.k_layernorm", eps); err != nil {
return nil, err
}
a.Indexer = idx
return a, nil
}
func (m *Model) loadSparseMoE(linears model.LinearFactory, tensors map[string]*mlx.Array, prefix string) (*sparseMoE, error) {
moe := &sparseMoE{}
var err error
if moe.Gate, err = requiredLinear(linears, prefix+".gate"); err != nil {
return nil, err
}
if moe.GateUpExperts, moe.GateUpScales, moe.GateUpBiases, moe.GateUpGroup, moe.GateUpBits, moe.GateUpMode, err = loadPackedExperts(tensors, prefix+".experts.gate_up_proj", m); err != nil {
return nil, err
}
if moe.DownExperts, moe.DownScales, moe.DownBiases, moe.DownGroup, moe.DownBits, moe.DownMode, err = loadPackedExperts(tensors, prefix+".experts.down_proj", m); err != nil {
return nil, err
}
for name, dst := range map[string]*nn.LinearLayer{
"shared_expert_gate": &moe.SharedGate,
"shared_expert.gate_proj": &moe.SharedGateProj,
"shared_expert.up_proj": &moe.SharedUpProj,
"shared_expert.down_proj": &moe.SharedDownProj,
} {
*dst, err = requiredLinear(linears, prefix+"."+name)
if err != nil {
return nil, err
}
}
return moe, nil
}
func (m *Model) loadPLE(linears model.LinearFactory, tensors map[string]*mlx.Array, prefix string) (*PLE, error) {
p := &PLE{}
var err error
convWeight, err := requiredArray(tensors, prefix+".conv1d.weight", prefix+".conv1d")
if err != nil {
return nil, err
}
if convWeight.NumDims() != 3 || convWeight.Dim(1) != 1 || convWeight.Dim(2) != int(m.PLEConvKernelSize) {
return nil, fmt.Errorf("%s.conv1d has shape %v, want [%d, 1, %d]", prefix, convWeight.Dims(), m.HCCount*m.HiddenSize, m.PLEConvKernelSize)
}
convWeight = mlx.Transpose(convWeight, 0, 2, 1)
p.Conv = nn.NewConv1d(convWeight, nil, 1, 0, m.NGramSize, m.HCCount*m.HiddenSize)
if p.KeyProj, err = requiredLinear(linears, prefix+".key_proj"); err != nil {
return nil, err
}
if p.ValueProj, err = requiredLinear(linears, prefix+".value_proj"); err != nil {
return nil, err
}
if p.NormConv, err = loadStreamNorm(tensors, prefix+".norm_conv", m.Config); err != nil {
return nil, err
}
if p.NormKey, err = loadStreamNorm(tensors, prefix+".norm_key", m.Config); err != nil {
return nil, err
}
if p.NormQuery, err = loadStreamNorm(tensors, prefix+".norm_query", m.Config); err != nil {
return nil, err
}
if p.LayerMultipliers, err = requiredArray(tensors, prefix+".ple_embedding.layer_multipliers"); err != nil {
return nil, err
}
if p.HeadOffsets, err = requiredArray(tensors, prefix+".ple_embedding.ngram_heads_offsets"); err != nil {
return nil, err
}
if p.HeadVocabSizes, err = requiredArray(tensors, prefix+".ple_embedding.ngram_heads_vocab_sizes"); err != nil {
return nil, err
}
p.EmbeddingShards = make([]nn.EmbeddingLayer, m.SplitNGramParts)
for i := range m.SplitNGramParts {
path := fmt.Sprintf("%s.ple_embedding.ngram_embedding.shard_%d", prefix, i)
weight, err := requiredArray(tensors, path+".weight")
if err != nil {
return nil, err
}
if i == 0 {
p.ShardRows = weight.Dim(0)
} else if weight.Dim(0) != p.ShardRows {
return nil, fmt.Errorf("%s has %d rows, want %d", path, weight.Dim(0), p.ShardRows)
}
p.EmbeddingShards[i] = model.MakeEmbeddingLayer(tensors, path, m.quantGroup, m.quantBits, m.quantMode, m.tensorQuant)
if p.EmbeddingShards[i] == nil {
return nil, fmt.Errorf("missing embedding %q", path)
}
}
return p, nil
}
func (m *Model) loadLayer(linears model.LinearFactory, tensors map[string]*mlx.Array, prefix, kind string, layer int) (*Layer, error) {
l := &Layer{}
var err error
if l.AttentionConnection, err = loadHyperConnection(linears, tensors, prefix+".attn_hyper_connection", true, m.Config); err != nil {
return nil, err
}
if l.MLPConnection, err = loadHyperConnection(linears, tensors, prefix+".mlp_hyper_connection", true, m.Config); err != nil {
return nil, err
}
if kind == "linear_attention" {
if l.Linear, err = loadLinearAttention(linears, tensors, prefix+".linear_attn"); err != nil {
return nil, err
}
} else if l.Attention, err = loadFullAttention(linears, tensors, prefix+".self_attn", m.RMSNormEps); err != nil {
return nil, err
}
if l.MoE, err = m.loadSparseMoE(linears, tensors, prefix+".mlp"); err != nil {
return nil, err
}
for _, id := range m.PLELayerIDs {
// PLE layer IDs are one-based and identify the layer receiving the
// additive n-gram features before its attention branch.
if int(id-1) == layer {
l.PLE, err = m.loadPLE(linears, tensors, prefix+".ple")
if err != nil {
return nil, err
}
}
}
return l, nil
}
func (m *Model) loadMTP(linears model.LinearFactory, tensors map[string]*mlx.Array) (*MTPHead, error) {
head := &MTPHead{}
var err error
if head.EmbeddingNorm, err = loadNorm(tensors, "mtp.pre_fc_norm_embedding", m.RMSNormEps); err != nil {
return nil, err
}
if head.HiddenNorm, err = loadNorm(tensors, "mtp.pre_fc_norm_hidden", m.RMSNormEps); err != nil {
return nil, err
}
if head.FCEmbedding, err = requiredLinear(linears, "mtp.fc_embedding"); err != nil {
return nil, err
}
if head.FCHidden, err = requiredLinear(linears, "mtp.fc_hidden"); err != nil {
return nil, err
}
if head.Mixer, err = loadHyperConnection(linears, tensors, "mtp.hyper_connection_mixer", false, m.Config); err != nil {
return nil, err
}
if head.Layer, err = m.loadLayer(linears, tensors, "mtp.layers.0", m.Config.MTP.LayerTypes[0], -1); err != nil {
return nil, err
}
return head, nil
}
func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
linears := model.NewLinearFactory(tensors, m.quantGroup, m.quantBits, m.quantMode, m.tensorQuant)
var err error
m.EmbedTokens = model.MakeEmbeddingLayer(tensors, "model.language_model.embed_tokens", m.quantGroup, m.quantBits, m.quantMode, m.tensorQuant)
if m.EmbedTokens == nil {
return fmt.Errorf("missing embedding weight")
}
if m.LMHead, err = requiredLinear(linears, "lm_head"); err != nil {
return err
}
if m.OutputMixer, err = loadHyperConnection(linears, tensors, "model.language_model.hyper_connection_mixer", false, m.Config); err != nil {
return err
}
sideCacheIndex := len(m.Layers)
for i := range m.Layers {
prefix := fmt.Sprintf("model.language_model.layers.%d", i)
if m.Layers[i], err = m.loadLayer(linears, tensors, prefix, m.LayerTypes[i], i); err != nil {
return fmt.Errorf("load layer %d: %w", i, err)
}
if m.Layers[i].Attention != nil {
m.Layers[i].Attention.SideCacheIndex = sideCacheIndex
sideCacheIndex++
}
}
if m.MTP, err = m.loadMTP(linears, tensors); err != nil {
return fmt.Errorf("load MTP: %w", err)
}
m.Vision, err = qwen3_5.NewVisionAdapter(m.configData, tensors, qwen3_5.VisionAdapterConfig{
HiddenSize: m.HiddenSize,
RopeDim: m.RopeDim,
RopeTheta: m.RopeParameters.RopeTheta,
MropeSection: m.RopeParameters.MRoPESection,
QuantGroup: m.quantGroup,
QuantBits: m.quantBits,
QuantMode: m.quantMode,
TensorQuant: m.tensorQuant,
})
if err != nil {
return fmt.Errorf("load vision tower: %w", err)
}
return nil
}
+85
View File
@@ -0,0 +1,85 @@
package qwen4_exp
import (
"math"
"testing"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/model"
)
func TestSparseMoEGlobalScales(t *testing.T) {
const experts, hidden, intermediate = 3, 64, 32
for _, tc := range []struct {
name, prefix, weightSuffix, scaleSuffix string
gate, down []float32
}{
{"unscaled", "model.language_model.layers.0.mlp", "", ".global_scale", nil, nil},
{"per expert", "model.language_model.layers.0.mlp", "", ".global_scale", []float32{0.5, 2, 4}, []float32{2, 0.25, 0.5}},
{"scalar MTP", "mtp.layers.0.mlp", ".weight", "_scale_2", []float32{0.5}, []float32{2}},
} {
t.Run(tc.name, func(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
values := func(n int, factor float32) []float32 {
v := make([]float32, n)
for i := range v {
v[i] = float32((i*37)%101-50) * factor
}
return v
}
tensors := map[string]*mlx.Array{}
for name, dims := range map[string][]int{
"gate": {experts, hidden}, "shared_expert_gate": {1, hidden},
"shared_expert.gate_proj": {intermediate, hidden},
"shared_expert.up_proj": {intermediate, hidden},
"shared_expert.down_proj": {hidden, intermediate},
} {
tensors[tc.prefix+"."+name+".weight"] = mlx.FromValues(values(dims[0]*dims[1], 0.001), dims...)
}
dense := make([]*mlx.Array, 2)
for i, p := range []struct {
name string
rows, cols int
global []float32
}{
{"gate_up_proj", 2 * intermediate, hidden, tc.gate},
{"down_proj", hidden, intermediate, tc.down},
} {
key := tc.prefix + ".experts." + p.name + tc.weightSuffix
w, s, _ := mlx.Quantize(mlx.FromValues(values(experts*p.rows*p.cols, 0.001), experts, p.rows, p.cols), 16, 4, "nvfp4")
tensors[key], tensors[key+"_scale"] = w, s
dense[i] = mlx.Dequantize(w, s, nil, 16, 4, "nvfp4", nil).AsType(mlx.DTypeFloat32)
if p.global != nil {
gs := mlx.FromValues(p.global, len(p.global))
tensors[key+tc.scaleSuffix] = gs
dense[i] = mlx.Mul(dense[i], mlx.Reshape(gs, int32(len(p.global)), 1, 1))
}
}
m := &Model{Config: &Config{HiddenSize: hidden, NumExpertsPerTok: 2}}
m.quantGroup, m.quantBits, m.quantMode = 16, 4, "nvfp4"
moe, err := m.loadSparseMoE(model.NewLinearFactory(tensors, 16, 4, "nvfp4", nil), tensors, tc.prefix)
if err != nil {
t.Fatal(err)
}
reference := *moe
reference.GateUp = &expertProjection{Weight: mlx.Transpose(dense[0], 0, 2, 1)}
reference.Down = &expertProjection{Weight: mlx.Transpose(dense[1], 0, 2, 1)}
for _, tokens := range []int{2, 64} {
x := mlx.FromValues(values(tokens*hidden, 0.02), 1, tokens, hidden)
got, want := moe.Forward(x, m.Config), reference.Forward(x, m.Config)
mlx.Eval(got, want)
gotValues, wantValues := got.Floats(), want.Floats()
var peak, errorMax float64
for j, v := range wantValues {
peak = math.Max(peak, math.Abs(float64(v)))
errorMax = math.Max(errorMax, math.Abs(float64(gotValues[j]-v)))
}
if math.IsNaN(errorMax) || errorMax > 0.005*peak {
t.Fatalf("%d tokens: max error %g, reference peak %g", tokens, errorMax, peak)
}
}
})
})
}
}
+24 -5
View File
@@ -88,8 +88,11 @@ func (r *Runner) loadModel(modelName string) (weights []*mlx.Array, err error) {
return nil
}
// Load all tensor blobs from manifest
tensors, e := loadTensorsFromManifest(root)
var skippedTensors []string
if s, ok := m.(model.SkippedTensorsModel); ok {
skippedTensors = s.SkippedTensorNames()
}
tensors, e := loadTensorsFromManifest(root, skippedTensors)
if e != nil {
err = e
return nil
@@ -236,14 +239,19 @@ func configureWiredMemory() {
"previous", mlx.PrettyBytes(previous))
}
// loadTensorsFromManifest loads all tensor blobs from the manifest into a
// flat map, deduplicating by digest and remapping safetensors key suffixes.
// loadTensorsFromManifest loads tensor blobs into a flat map, excluding specified
// tensors, deduplicating by digest and remapping key suffixes.
//
// Uses a two-phase approach: first loads all raw tensors, then remaps
// .bias → _qbias with complete knowledge of which base names have .scale
// entries. This avoids a race condition where Go map iteration order could
// cause .bias to be processed before .scale within the same blob.
func loadTensorsFromManifest(root *model.Root) (map[string]*mlx.Array, error) {
func loadTensorsFromManifest(root *model.Root, skippedTensors []string) (map[string]*mlx.Array, error) {
skip := make(map[string]bool, len(skippedTensors))
for _, name := range skippedTensors {
skip[name] = true
}
skipped, skippedBytes := 0, 0
// Phase 1: Load all tensors raw from all blobs
rawTensors := make(map[string]*mlx.Array)
seen := make(map[string]bool)
@@ -257,6 +265,14 @@ func loadTensorsFromManifest(root *model.Root) (map[string]*mlx.Array, error) {
return nil, err
}
for name, arr := range mlx.Load(blobPath) {
// Native safetensors loads are lazy. Filter excluded arrays before
// the Metal pre-pass materializes their payloads, including when a
// blob also contains tensors needed by the target or draft model.
if skip[name] {
skipped++
skippedBytes += arr.NumBytes()
continue
}
rawTensors[name] = arr
}
}
@@ -290,6 +306,9 @@ func loadTensorsFromManifest(root *model.Root) (map[string]*mlx.Array, error) {
}
slog.Info("Loaded tensors from manifest", "count", len(allTensors))
if skipped > 0 {
slog.Debug("Skipped tensors from manifest", "count", skipped, "bytes", skippedBytes)
}
return allTensors, nil
}
+45
View File
@@ -1,14 +1,59 @@
package mlxrunner
import (
"encoding/binary"
"maps"
"math"
"slices"
"testing"
"github.com/ollama/ollama/fs/safetensors"
"github.com/ollama/ollama/manifest"
"github.com/ollama/ollama/mlx"
"github.com/ollama/ollama/mlx/mlxtest"
"github.com/ollama/ollama/mlxrunner/batch"
"github.com/ollama/ollama/mlxrunner/cache"
"github.com/ollama/ollama/mlxrunner/model"
)
func TestLoadTensorsSkipsNamedTensors(t *testing.T) {
t.Setenv("OLLAMA_MODELS", t.TempDir())
var data []*safetensors.TensorData
for _, name := range []string{"skipped.weight", "skipped.weight.scale", "skipped.weight.global_scale", "target.weight", "draft.weight"} {
data = append(data, safetensors.NewTensorDataFromBytes(name, "F32", []int32{1}, binary.LittleEndian.AppendUint32(nil, math.Float32bits(2))))
}
layer, err := manifest.NewLayer(safetensors.BuildPackedSafetensorsReader(data), manifest.MediaTypeImageTensor)
if err != nil {
t.Fatal(err)
}
root := &model.Root{Manifest: &manifest.Manifest{Layers: []manifest.Layer{layer, layer}}}
for _, tc := range []struct {
name string
skip []string
want []string
}{
{"all tensors", nil, []string{"draft.weight", "skipped.weight", "skipped.weight.global_scale", "skipped.weight_scale", "target.weight"}},
{"skip named tensors", []string{"skipped.weight", "skipped.weight.scale", "skipped.weight.global_scale"}, []string{"draft.weight", "target.weight"}},
} {
t.Run(tc.name, func(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
tensors, err := loadTensorsFromManifest(root, tc.skip)
if err != nil {
t.Fatal(err)
}
if got := slices.Sorted(maps.Keys(tensors)); !slices.Equal(got, tc.want) {
t.Fatalf("loaded tensors = %v, want %v", got, tc.want)
}
for name, arr := range tensors {
if got := arr.Floats(); !slices.Equal(got, []float32{2}) {
t.Errorf("%s = %v, want [2]", name, got)
}
}
})
})
}
}
func TestRunnerCloseReleasesGenerationCache(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
activeMemory := func() int {