Skip to content

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

qwen3_5: pack GDN input projections into one layout at load

Jesse Grossbd3f22e2f788
diff --git a/x/models/nn/nn.go b/x/models/nn/nn.go
index 371af64c3..9a69f55ab 100644
--- a/x/models/nn/nn.go
+++ b/x/models/nn/nn.go
@@ -85,7 +85,7 @@ type QuantizedLinear struct {
Scales *mlx.Array // Scale factors for dequantization
QBiases *mlx.Array // Quantization biases (nil for nvfp4)
Bias *mlx.Array // Layer bias [output_dims] or nil
- GlobalScale *mlx.Array // Per-tensor global scale for double-scale nvfp4 (nil for standard)
+ GlobalScale *mlx.Array // Per-tensor or per-row global scale for double-scale nvfp4 (nil for standard)
GroupSize int
Bits int
Mode string
@@ -116,8 +116,8 @@ func (ql *QuantizedLinear) Forward(x *mlx.Array) *mlx.Array {
out := mlx.QuantizedMatmul(x, ql.Weight, ql.Scales, ql.QBiases, true, ql.GroupSize, ql.Bits, ql.Mode)
if ql.GlobalScale != nil {
// Double-scale nvfp4 (e.g., NVIDIA ModelOpt): standard quantized_matmul
- // followed by global_scale multiply. The global_scale is a per-tensor
- // F32 scalar (weight_scale_2 in NVIDIA's format).
+ // followed by global_scale multiply. The global_scale is F32, per-tensor
+ // (weight_scale_2 in NVIDIA's format) or per-row.
// TODO: switch to a fused double-scale matmul once MLX has kernel
// coverage for this path.
outDType := out.DType()
diff --git a/x/models/qwen3_5/gdn_projections.go b/x/models/qwen3_5/gdn_projections.go
new file mode 100644
index 000000000..69d48b87d
--- /dev/null
+++ b/x/models/qwen3_5/gdn_projections.go
@@ -0,0 +1,205 @@
+package qwen3_5
+
+import (
+ "fmt"
+ "log/slog"
+
+ "github.com/ollama/ollama/x/mlxrunner/mlx"
+ "github.com/ollama/ollama/x/models/nn"
+)
+
+// The runtime keeps one layout for the linear-attention input projections:
+// InProjQKVZ rows form [q | k | v | z] blocks and InProjBA rows form
+// [beta | alpha], so the causal conv consumes a contiguous qkv slice and
+// beta/alpha sit at fixed offsets. Split checkpoints concatenate into that
+// layout; native combined checkpoints ship rows interleaved per key head and
+// are permuted into it once at load.
+
+func packGatedDeltaProjections(qkv, z, b, a, qkvz, ba nn.LinearLayer, cfg *Config) (packedQKVZ, packedBA nn.LinearLayer, err error) {
+ switch {
+ case (qkvz != nil || ba != nil) && (qkv != nil || z != nil || b != nil || a != nil):
+ return nil, nil, fmt.Errorf("both combined and split linear attention projections present")
+ case qkvz != nil && ba != nil:
+ packedQKVZ, err = permuteProjectionRows(qkvz, nativeQKVZPerm(cfg))
+ if err != nil {
+ return nil, nil, err
+ }
+ packedBA, err = permuteProjectionRows(ba, nativeBAPerm(cfg))
+ return packedQKVZ, packedBA, err
+ case qkv != nil && z != nil && b != nil && a != nil:
+ packedQKVZ, err = concatProjectionPair(qkv, z)
+ if err != nil {
+ return nil, nil, err
+ }
+ packedBA, err = concatProjectionPair(b, a)
+ return packedQKVZ, packedBA, err
+ }
+ return nil, nil, fmt.Errorf("missing linear attention projections")
+}
+
+// nativeQKVZPerm maps packed row -> native row. Native in_proj_qkvz rows are
+// grouped per key head as [q(dk) | k(dk) | v(vPerK*dv) | z(vPerK*dv)].
+func nativeQKVZPerm(cfg *Config) []int32 {
+ nk, nv := int(cfg.LinearNumKeyHeads), int(cfg.LinearNumValueHeads)
+ dk, dv := int(cfg.LinearKeyHeadDim), int(cfg.LinearValueHeadDim)
+ vPerK := nv / nk
+ group := 2*dk + 2*vPerK*dv
+ keyDim, valueDim := nk*dk, nv*dv
+
+ perm := make([]int32, 2*keyDim+2*valueDim)
+ for kh := range nk {
+ base := kh * group
+ for i := range dk {
+ perm[kh*dk+i] = int32(base + i)
+ perm[keyDim+kh*dk+i] = int32(base + dk + i)
+ }
+ for j := range vPerK * dv {
+ perm[2*keyDim+kh*vPerK*dv+j] = int32(base + 2*dk + j)
+ perm[2*keyDim+valueDim+kh*vPerK*dv+j] = int32(base + 2*dk + vPerK*dv + j)
+ }
+ }
+ return perm
+}
+
+// nativeBAPerm maps packed row -> native row. Native in_proj_ba rows are
+// grouped per key head as [beta(vPerK) | alpha(vPerK)].
+func nativeBAPerm(cfg *Config) []int32 {
+ nk, nv := int(cfg.LinearNumKeyHeads), int(cfg.LinearNumValueHeads)
+ vPerK := nv / nk
+
+ perm := make([]int32, 2*nv)
+ for kh := range nk {
+ for j := range vPerK {
+ perm[kh*vPerK+j] = int32(kh*2*vPerK + j)
+ perm[nv+kh*vPerK+j] = int32(kh*2*vPerK + vPerK + j)
+ }
+ }
+ return perm
+}
+
+func permuteProjectionRows(layer nn.LinearLayer, perm []int32) (nn.LinearLayer, error) {
+ indices := mlx.NewArrayInt32(perm, []int32{int32(len(perm))})
+ takeRows := func(a *mlx.Array) *mlx.Array {
+ if a == nil {
+ return nil
+ }
+ return mlx.Take(a, indices, 0)
+ }
+
+ switch l := layer.(type) {
+ case *nn.Linear:
+ if l.Weight.Dim(0) != len(perm) {
+ return nil, fmt.Errorf("projection has %d rows, want %d", l.Weight.Dim(0), len(perm))
+ }
+ return nn.NewLinear(takeRows(l.Weight), takeRows(l.Bias)), nil
+ case *nn.QuantizedLinear:
+ if l.Weight.Dim(0) != len(perm) {
+ return nil, fmt.Errorf("projection has %d rows, want %d", l.Weight.Dim(0), len(perm))
+ }
+ globalScale := l.GlobalScale
+ if globalScale != nil && globalScale.Size() > 1 {
+ globalScale = takeRows(globalScale)
+ }
+ return &nn.QuantizedLinear{
+ Weight: takeRows(l.Weight),
+ Scales: takeRows(l.Scales),
+ QBiases: takeRows(l.QBiases),
+ Bias: takeRows(l.Bias),
+ GlobalScale: globalScale,
+ GroupSize: l.GroupSize,
+ Bits: l.Bits,
+ Mode: l.Mode,
+ }, nil
+ }
+ return nil, fmt.Errorf("unsupported projection type %T", layer)
+}
+
+func concatProjectionPair(hi, lo nn.LinearLayer) (nn.LinearLayer, error) {
+ hiQ, hiQuant := hi.(*nn.QuantizedLinear)
+ loQ, loQuant := lo.(*nn.QuantizedLinear)
+ if hiQuant && loQuant &&
+ hiQ.GroupSize == loQ.GroupSize && hiQ.Bits == loQ.Bits && hiQ.Mode == loQ.Mode {
+ return concatQuantizedPair(hiQ, loQ)
+ }
+ if hiQuant || loQuant {
+ slog.Warn("dequantizing linear attention projections: pair quantization differs")
+ }
+
+ hiD, err := denseProjection(hi)
+ if err != nil {
+ return nil, err
+ }
+ loD, err := denseProjection(lo)
+ if err != nil {
+ return nil, err
+ }
+ weight := mlx.Concatenate([]*mlx.Array{hiD.Weight, loD.Weight.AsType(hiD.Weight.DType())}, 0)
+ return nn.NewLinear(weight, concatOptionalRows(hiD.Bias, loD.Bias, hiD.Weight, loD.Weight)), nil
+}
+
+func concatQuantizedPair(hi, lo *nn.QuantizedLinear) (nn.LinearLayer, error) {
+ var qbiases *mlx.Array
+ if hi.QBiases != nil || lo.QBiases != nil {
+ if hi.QBiases == nil || lo.QBiases == nil {
+ return nil, fmt.Errorf("quantized projections disagree on qbiases")
+ }
+ qbiases = mlx.Concatenate([]*mlx.Array{hi.QBiases, lo.QBiases}, 0)
+ }
+ return &nn.QuantizedLinear{
+ Weight: mlx.Concatenate([]*mlx.Array{hi.Weight, lo.Weight}, 0),
+ Scales: mlx.Concatenate([]*mlx.Array{hi.Scales, lo.Scales}, 0),
+ QBiases: qbiases,
+ Bias: concatOptionalRows(hi.Bias, lo.Bias, hi.Scales, lo.Scales),
+ GlobalScale: concatGlobalScales(hi.GlobalScale, lo.GlobalScale, hi.Weight, lo.Weight),
+ GroupSize: hi.GroupSize,
+ Bits: hi.Bits,
+ Mode: hi.Mode,
+ }, nil
+}
+
+func denseProjection(layer nn.LinearLayer) (*nn.Linear, error) {
+ switch l := layer.(type) {
+ case *nn.Linear:
+ return l, nil
+ case *nn.QuantizedLinear:
+ weight := mlx.Dequantize(l.Weight, l.Scales, l.QBiases, l.GroupSize, l.Bits, l.Mode, l.GlobalScale)
+ return nn.NewLinear(weight, l.Bias), nil
+ }
+ return nil, fmt.Errorf("unsupported projection type %T", layer)
+}
+
+// concatOptionalRows concatenates two per-row vectors where nil means zero,
+// sized by the paired weights' row counts.
+func concatOptionalRows(hi, lo, hiRows, loRows *mlx.Array) *mlx.Array {
+ switch {
+ case hi == nil && lo == nil:
+ return nil
+ case hi == nil:
+ hi = mlx.Zeros(lo.DType(), hiRows.Dim(0))
+ case lo == nil:
+ lo = mlx.Zeros(hi.DType(), loRows.Dim(0))
+ }
+ return mlx.Concatenate([]*mlx.Array{hi, lo.AsType(hi.DType())}, 0)
+}
+
+// concatGlobalScales concatenates per-tensor or per-row global scales into a
+// per-row vector, where nil means one.
+func concatGlobalScales(hi, lo, hiRows, loRows *mlx.Array) *mlx.Array {
+ if hi == nil && lo == nil {
+ return nil
+ }
+ expand := func(scale *mlx.Array, rows int32) *mlx.Array {
+ switch {
+ case scale == nil:
+ return mlx.Tile(mlx.FromValues([]float32{1}, 1), []int32{rows})
+ case scale.Size() == 1:
+ return mlx.Tile(mlx.Reshape(scale.AsType(mlx.DTypeFloat32), 1), []int32{rows})
+ default:
+ return scale.AsType(mlx.DTypeFloat32)
+ }
+ }
+ return mlx.Concatenate([]*mlx.Array{
+ expand(hi, int32(hiRows.Dim(0))),
+ expand(lo, int32(loRows.Dim(0))),
+ }, 0)
+}
diff --git a/x/models/qwen3_5/gdn_projections_test.go b/x/models/qwen3_5/gdn_projections_test.go
new file mode 100644
index 000000000..73e09dfb1
--- /dev/null
+++ b/x/models/qwen3_5/gdn_projections_test.go
@@ -0,0 +1,138 @@
+package qwen3_5
+
+import (
+ "math"
+ "testing"
+
+ "github.com/ollama/ollama/x/mlxrunner/mlx"
+ "github.com/ollama/ollama/x/models/nn"
+)
+
+func gdnTestConfig() *Config {
+ return &Config{
+ LinearNumKeyHeads: 2,
+ LinearNumValueHeads: 4,
+ LinearKeyHeadDim: 4,
+ LinearValueHeadDim: 4,
+ }
+}
+
+func patternArray(rows, cols int) *mlx.Array {
+ values := make([]float32, rows*cols)
+ for i := range values {
+ values[i] = float32((i*37)%113-56) * 0.03
+ }
+ return mlx.FromValues(values, rows, cols).AsType(mlx.DTypeBFloat16)
+}
+
+func assertBitEqual(t *testing.T, label string, got, want *mlx.Array) {
+ t.Helper()
+ if got == nil || want == nil {
+ if got != want {
+ t.Fatalf("%s: got %v, want %v", label, got, want)
+ }
+ return
+ }
+ got32, want32 := got.AsType(mlx.DTypeFloat32), want.AsType(mlx.DTypeFloat32)
+ mlx.Eval(got32, want32)
+ gotValues, wantValues := got32.Floats(), want32.Floats()
+ if len(gotValues) != len(wantValues) {
+ t.Fatalf("%s: length %d, want %d", label, len(gotValues), len(wantValues))
+ }
+ for i := range wantValues {
+ if math.Float32bits(gotValues[i]) != math.Float32bits(wantValues[i]) {
+ t.Fatalf("%s[%d] = %v, want %v", label, i, gotValues[i], wantValues[i])
+ }
+ }
+}
+
+// scatterRows builds the native interleaved tensor from a packed tensor and
+// the packed->native row map, inverting what the loader's permutation does.
+func scatterRows(packed *mlx.Array, perm []int32) *mlx.Array {
+ inverse := make([]int32, len(perm))
+ for dst, src := range perm {
+ inverse[src] = int32(dst)
+ }
+ return mlx.Take(packed, mlx.NewArrayInt32(inverse, []int32{int32(len(inverse))}), 0)
+}
+
+func TestPackGatedDeltaProjectionsNativeMatchesSplit(t *testing.T) {
+ skipIfNoMLX(t)
+ cfg := gdnTestConfig()
+ keyDim := int(cfg.LinearNumKeyHeads * cfg.LinearKeyHeadDim)
+ valueDim := int(cfg.LinearNumValueHeads * cfg.LinearValueHeadDim)
+ in := 8
+
+ qkvW := patternArray(2*keyDim+valueDim, in)
+ zW := patternArray(valueDim, in)
+ bW := patternArray(int(cfg.LinearNumValueHeads), in)
+ aW := patternArray(int(cfg.LinearNumValueHeads), in)
+
+ fromSplitQKVZ, fromSplitBA, err := packGatedDeltaProjections(
+ nn.NewLinear(qkvW, nil), nn.NewLinear(zW, nil),
+ nn.NewLinear(bW, nil), nn.NewLinear(aW, nil),
+ nil, nil, cfg,
+ )
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ packedQKVZ := mlx.Concatenate([]*mlx.Array{qkvW, zW}, 0)
+ packedBA := mlx.Concatenate([]*mlx.Array{bW, aW}, 0)
+ nativeQKVZ := scatterRows(packedQKVZ, nativeQKVZPerm(cfg))
+ nativeBA := scatterRows(packedBA, nativeBAPerm(cfg))
+
+ fromNativeQKVZ, fromNativeBA, err := packGatedDeltaProjections(
+ nil, nil, nil, nil,
+ nn.NewLinear(nativeQKVZ, nil), nn.NewLinear(nativeBA, nil),
+ cfg,
+ )
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ assertBitEqual(t, "qkvz", fromNativeQKVZ.(*nn.Linear).Weight, fromSplitQKVZ.(*nn.Linear).Weight)
+ assertBitEqual(t, "ba", fromNativeBA.(*nn.Linear).Weight, fromSplitBA.(*nn.Linear).Weight)
+}
+
+func TestConcatProjectionPairQuantized(t *testing.T) {
+ skipIfNoMLX(t)
+ in := 64
+ hi := nn.NewQuantizedLinear(patternArray(16, in).AsType(mlx.DTypeFloat32), nil, 32, 4, "affine")
+ lo := nn.NewQuantizedLinear(patternArray(8, in).AsType(mlx.DTypeFloat32), nil, 32, 4, "affine")
+
+ packed, err := concatProjectionPair(hi, lo)
+ if err != nil {
+ t.Fatal(err)
+ }
+ q, ok := packed.(*nn.QuantizedLinear)
+ if !ok {
+ t.Fatalf("packed projection is %T, want *nn.QuantizedLinear", packed)
+ }
+ assertBitEqual(t, "weight", q.Weight, mlx.Concatenate([]*mlx.Array{hi.Weight, lo.Weight}, 0))
+ assertBitEqual(t, "scales", q.Scales, mlx.Concatenate([]*mlx.Array{hi.Scales, lo.Scales}, 0))
+}
+
+func TestConcatProjectionPairMixedFallsBackToDense(t *testing.T) {
+ skipIfNoMLX(t)
+ in := 64
+ hi := nn.NewQuantizedLinear(patternArray(16, in).AsType(mlx.DTypeFloat32), nil, 32, 4, "affine")
+ loW := patternArray(8, in)
+
+ packed, err := concatProjectionPair(hi, nn.NewLinear(loW, nil))
+ if err != nil {
+ t.Fatal(err)
+ }
+ dense, ok := packed.(*nn.Linear)
+ if !ok {
+ t.Fatalf("packed projection is %T, want *nn.Linear", packed)
+ }
+ want := mlx.Concatenate([]*mlx.Array{
+ mlx.Dequantize(hi.Weight, hi.Scales, hi.QBiases, hi.GroupSize, hi.Bits, hi.Mode, nil),
+ loW.AsType(mlx.DTypeFloat16),
+ }, 0)
+ if dense.Weight.Dim(0) != 24 {
+ t.Fatalf("packed rows = %d, want 24", dense.Weight.Dim(0))
+ }
+ assertBitEqual(t, "weight", dense.Weight, want.AsType(dense.Weight.DType()))
+}
diff --git a/x/models/qwen3_5/qwen3_5.go b/x/models/qwen3_5/qwen3_5.go
index e7a411528..9100585d0 100644
--- a/x/models/qwen3_5/qwen3_5.go
+++ b/x/models/qwen3_5/qwen3_5.go
@@ -118,10 +118,6 @@ type FullAttention struct {
// GatedDeltaNet is the recurrent linear-attention branch.
type GatedDeltaNet struct {
- InProjQKV nn.LinearLayer
- InProjZ nn.LinearLayer
- InProjB nn.LinearLayer
- InProjA nn.LinearLayer
InProjQKVZ nn.LinearLayer
InProjBA nn.LinearLayer
OutProj nn.LinearLayer
@@ -872,12 +868,19 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
if layer.IsLinear {
lin := &GatedDeltaNet{}
- lin.InProjQKV = linears.Make(layerPrefix + ".linear_attn.in_proj_qkv")
- lin.InProjZ = linears.Make(layerPrefix + ".linear_attn.in_proj_z")
- lin.InProjB = linears.Make(layerPrefix + ".linear_attn.in_proj_b")
- lin.InProjA = linears.Make(layerPrefix + ".linear_attn.in_proj_a")
- lin.InProjQKVZ = linears.Make(layerPrefix + ".linear_attn.in_proj_qkvz")
- lin.InProjBA = linears.Make(layerPrefix + ".linear_attn.in_proj_ba")
+ var err error
+ lin.InProjQKVZ, lin.InProjBA, err = packGatedDeltaProjections(
+ linears.Make(layerPrefix+".linear_attn.in_proj_qkv"),
+ linears.Make(layerPrefix+".linear_attn.in_proj_z"),
+ linears.Make(layerPrefix+".linear_attn.in_proj_b"),
+ linears.Make(layerPrefix+".linear_attn.in_proj_a"),
+ linears.Make(layerPrefix+".linear_attn.in_proj_qkvz"),
+ linears.Make(layerPrefix+".linear_attn.in_proj_ba"),
+ cfg,
+ )
+ if err != nil {
+ return fmt.Errorf("layer %d: %w", i, err)
+ }
lin.OutProj = linears.Make(layerPrefix + ".linear_attn.out_proj")
convWeight := sanitizeConvWeight(tensors[layerPrefix+".linear_attn.conv1d.weight"])
@@ -900,9 +903,7 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
lin.AExp = mlx.Exp(lin.ALog.AsType(mlx.DTypeFloat32))
}
- hasSplit := lin.InProjQKV != nil && lin.InProjZ != nil && lin.InProjB != nil && lin.InProjA != nil
- hasCombined := lin.InProjQKVZ != nil && lin.InProjBA != nil
- if (!hasSplit && !hasCombined) || lin.OutProj == nil {
+ if lin.OutProj == nil {
return fmt.Errorf("layer %d: missing linear attention projections", i)
}
if convWeight == nil || lin.NormWeight == nil || lin.DtBias == nil || lin.ALog == nil || lin.AExp == nil {
@@ -987,31 +988,6 @@ func softplus(x *mlx.Array) *mlx.Array {
return mlx.Logaddexp(x, mlx.Zeros(x.DType(), x.Dims()...))
}
-func splitQKVZBA(mixedQKVZ, mixedBA *mlx.Array, cfg *Config, B, L int32) (q, k, v, z, beta, alpha *mlx.Array) {
- nk := cfg.LinearNumKeyHeads
- nv := cfg.LinearNumValueHeads
- dk := cfg.LinearKeyHeadDim
- dv := cfg.LinearValueHeadDim
- vPerK := nv / nk
-
- mixedQKVZ = mlx.Reshape(mixedQKVZ, B, L, nk, 2*dk+2*vPerK*dv)
- q = mlx.SliceStartStop(mixedQKVZ, []int32{0, 0, 0, 0}, []int32{B, L, nk, dk})
- k = mlx.SliceStartStop(mixedQKVZ, []int32{0, 0, 0, dk}, []int32{B, L, nk, 2 * dk})
- v = mlx.SliceStartStop(mixedQKVZ, []int32{0, 0, 0, 2 * dk}, []int32{B, L, nk, 2*dk + vPerK*dv})
- z = mlx.SliceStartStop(mixedQKVZ, []int32{0, 0, 0, 2*dk + vPerK*dv}, []int32{B, L, nk, 2*dk + 2*vPerK*dv})
-
- v = mlx.Reshape(v, B, L, nv, dv)
- z = mlx.Reshape(z, B, L, nv, dv)
-
- mixedBA = mlx.Reshape(mixedBA, B, L, nk, 2*vPerK)
- beta = mlx.SliceStartStop(mixedBA, []int32{0, 0, 0, 0}, []int32{B, L, nk, vPerK})
- alpha = mlx.SliceStartStop(mixedBA, []int32{0, 0, 0, vPerK}, []int32{B, L, nk, 2 * vPerK})
- beta = mlx.Reshape(beta, B, L, nv)
- alpha = mlx.Reshape(alpha, B, L, nv)
-
- return q, k, v, z, beta, alpha
-}
-
func (a *FullAttention) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, positions *mlx.Array, B, L int32, cfg *Config) *mlx.Array {
qg := a.QProj.Forward(x)
qg = mlx.Reshape(qg, B, L, cfg.NumAttentionHeads, cfg.HeadDim*2)
@@ -1050,25 +1026,17 @@ func (a *FullAttention) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, pos
}
func (g *GatedDeltaNet) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, B, L int32, cfg *Config) *mlx.Array {
- var qkv, z, beta, alpha *mlx.Array
- useSplitProj := g.InProjQKV != nil && g.InProjZ != nil && g.InProjB != nil && g.InProjA != nil
- if useSplitProj {
- qkv = g.InProjQKV.Forward(x)
- z = g.InProjZ.Forward(x)
- z = mlx.Reshape(z, B, L, cfg.LinearNumValueHeads, cfg.LinearValueHeadDim)
- beta = g.InProjB.Forward(x)
- alpha = g.InProjA.Forward(x)
- } else {
- mixedQKVZ := g.InProjQKVZ.Forward(x)
- mixedBA := g.InProjBA.Forward(x)
- var q, k, v *mlx.Array
- q, k, v, z, beta, alpha = splitQKVZBA(mixedQKVZ, mixedBA, cfg, B, L)
- qkv = mlx.Concatenate([]*mlx.Array{
- mlx.Reshape(q, B, L, cfg.LinearNumKeyHeads*cfg.LinearKeyHeadDim),
- mlx.Reshape(k, B, L, cfg.LinearNumKeyHeads*cfg.LinearKeyHeadDim),
- mlx.Reshape(v, B, L, cfg.LinearNumValueHeads*cfg.LinearValueHeadDim),
- }, -1)
- }
+ keyDim := cfg.LinearNumKeyHeads * cfg.LinearKeyHeadDim
+ valueDim := cfg.LinearNumValueHeads * cfg.LinearValueHeadDim
+ qkvDim := 2*keyDim + valueDim
+
+ mixedQKVZ := g.InProjQKVZ.Forward(x)
+ mixedBA := g.InProjBA.Forward(x)
+ qkv := mlx.SliceStartStop(mixedQKVZ, []int32{0, 0, 0}, []int32{B, L, qkvDim})
+ z := mlx.SliceStartStop(mixedQKVZ, []int32{0, 0, qkvDim}, []int32{B, L, qkvDim + valueDim})
+ z = mlx.Reshape(z, B, L, cfg.LinearNumValueHeads, cfg.LinearValueHeadDim)
+ beta := mlx.SliceStartStop(mixedBA, []int32{0, 0, 0}, []int32{B, L, cfg.LinearNumValueHeads})
+ alpha := mlx.SliceStartStop(mixedBA, []int32{0, 0, cfg.LinearNumValueHeads}, []int32{B, L, 2 * cfg.LinearNumValueHeads})
convTail := cfg.LinearConvKernelDim - 1
var rc *cache.RecurrentCache
opts := make([]nn.RecurrentOption, 0, 2)
@@ -1091,8 +1059,6 @@ func (g *GatedDeltaNet) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, B,
convOut, convStates := nn.CausalConv1D(b, qkv, g.Conv1D, int(convTail), opts...)
convOut = mlx.SiLU(convOut)
- keyDim := cfg.LinearNumKeyHeads * cfg.LinearKeyHeadDim
- valueDim := cfg.LinearNumValueHeads * cfg.LinearValueHeadDim
q := mlx.SliceStartStop(convOut, []int32{0, 0, 0}, []int32{B, L, keyDim})
k := mlx.SliceStartStop(convOut, []int32{0, 0, keyDim}, []int32{B, L, 2 * keyDim})
v := mlx.SliceStartStop(convOut, []int32{0, 0, 2 * keyDim}, []int32{B, L, 2*keyDim + valueDim})