Skip to content

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

nn/recurrent: return per-boundary states from the gated-delta kernels

Jesse Gross177aefb8a9fb
diff --git a/x/mlxrunner/cache/recurrent.go b/x/mlxrunner/cache/recurrent.go
index d920e8807..2424f546d 100644
--- a/x/mlxrunner/cache/recurrent.go
+++ b/x/mlxrunner/cache/recurrent.go
@@ -82,14 +82,20 @@ func (c *RecurrentCache) Get(b *batch.Batch, dtype mlx.DType) *nn.RecurrentHisto
return nn.NewRecurrentHistory(c.convState, c.deltaState)
}
-// Put stores the post-computation conv/delta states for the SSM
-// layer's write phase and advances the cache offset by the current
-// forward's real token count.
+// Put stores the conv/delta states produced by the SSM layer's write phase.
+// convStates/deltaStates are the per-boundary recurrent states, one per
+// boundary ending with the forward-end state. The final entry becomes the
+// committed live state, advancing the cache offset by the forward's real
+// token count.
+//
+// In the common (unsegmented) case both slices have length 1 — just the
+// forward-end state.
//
// Assumes B = 1; heterogeneous batches are not supported.
-func (c *RecurrentCache) Put(b *batch.Batch, newConv, newDelta *mlx.Array) {
- c.convState = c.setState(c.convState, newConv, true)
- c.deltaState = c.setState(c.deltaState, newDelta, false)
+func (c *RecurrentCache) Put(b *batch.Batch, convStates, deltaStates []*mlx.Array) {
+ last := len(convStates) - 1
+ c.convState = c.setState(c.convState, convStates[last], true)
+ c.deltaState = c.setState(c.deltaState, deltaStates[last], false)
c.offset += int(b.SeqQueryLens[0])
}
diff --git a/x/mlxrunner/cache/recurrent_test.go b/x/mlxrunner/cache/recurrent_test.go
index cf98b6378..035bde6e0 100644
--- a/x/mlxrunner/cache/recurrent_test.go
+++ b/x/mlxrunner/cache/recurrent_test.go
@@ -18,13 +18,20 @@ func TestRecurrentCacheRestoreExactOffset(t *testing.T) {
b1 := &batch.Batch{InputIDs: mlx.Zeros(mlx.DTypeInt32, 1, 1)}
c.Get(b1, mlx.DTypeFloat16) // lazy-init
+ keep := func() ([]*mlx.Array, []*mlx.Array) {
+ s := c.State()
+ return []*mlx.Array{s[0]}, []*mlx.Array{s[1]}
+ }
+
b10 := &batch.Batch{InputIDs: mlx.Zeros(mlx.DTypeInt32, 1, 10), SeqQueryLens: []int32{10}}
- c.Put(b10, nil, nil) // advance to 10
+ cs, ds := keep()
+ c.Put(b10, cs, ds) // advance to 10
snap := c.Snapshot(0) // snap.offset == 10
b5 := &batch.Batch{InputIDs: mlx.Zeros(mlx.DTypeInt32, 1, 5), SeqQueryLens: []int32{5}}
- c.Put(b5, nil, nil) // cache now at 15
+ cs, ds = keep()
+ c.Put(b5, cs, ds) // cache now at 15
// target < snap.offset: fails (can't rewind past snapshot)
if c.Restore(snap, 5) {
@@ -157,7 +164,7 @@ func TestRecurrentCachePaddedRoundTrip(t *testing.T) {
}
history := c.Get(b, mlx.DTypeFloat32)
- _, nextConv := nn.CausalConv1D(b, convInput, nil, weight, convTail,
+ _, convStates := nn.CausalConv1D(b, convInput, nil, weight, convTail,
nn.WithRecurrentHistory(history))
var q, k, v, g, beta *mlx.Array
@@ -168,11 +175,11 @@ func TestRecurrentCachePaddedRoundTrip(t *testing.T) {
q, k, v = makeQKV(0.3, T)
g, beta = makeGB(0.1, T)
}
- _, newDelta := nn.GatedDelta(b, q, k, v, g, beta,
+ _, deltaStates := nn.GatedDelta(b, q, k, v, g, beta,
nn.WithRecurrentHistory(history))
- c.Put(b, nextConv, newDelta)
- return nextConv, newDelta
+ c.Put(b, convStates, deltaStates)
+ return convStates[len(convStates)-1], deltaStates[len(deltaStates)-1]
}
// Padded forward.
@@ -230,7 +237,7 @@ func TestRecurrentCachePutAdvances(t *testing.T) {
b := &batch.Batch{InputIDs: mlx.Zeros(mlx.DTypeInt32, 1, 2), SeqQueryLens: []int32{2}}
newConv := mlx.Zeros(mlx.DTypeFloat16, 1, 3, 4)
newDelta := mlx.Zeros(mlx.DTypeFloat16, 1, 2, 4, 4)
- c.Put(b, newConv, newDelta)
+ c.Put(b, []*mlx.Array{newConv}, []*mlx.Array{newDelta})
if c.Offset() != 2 {
t.Fatalf("cache offset not advanced: %d", c.Offset())
}
diff --git a/x/models/nn/recurrent.go b/x/models/nn/recurrent.go
index 6f0f7474f..255d49f54 100644
--- a/x/models/nn/recurrent.go
+++ b/x/models/nn/recurrent.go
@@ -15,6 +15,7 @@ type recurrentConfig struct {
history *RecurrentHistory
convState *mlx.Array
deltaState *mlx.Array
+ splits []int
}
// WithRecurrentHistory supplies a cache's per-layer view of conv and
@@ -34,6 +35,66 @@ func WithRecurrentState(convState, deltaState *mlx.Array) RecurrentOption {
}
}
+// WithSnapshotSplits requests that the scan run in segments cut at the given
+// offsets within this forward (0 < offset < L), capturing the recurrent state
+// at each boundary. The wrapper returns those per-boundary states to the
+// caller. Offsets must be sorted ascending and strictly interior; out-of-range
+// or duplicate offsets are ignored.
+func WithSnapshotSplits(offsets []int) RecurrentOption {
+ return func(c *recurrentConfig) { c.splits = offsets }
+}
+
+// seg is a half-open token range [start, end) within a forward.
+type seg struct{ start, end int32 }
+
+func (s seg) len() int32 { return s.end - s.start }
+
+// segmentRanges expands the interior cut offsets into consecutive [a,c) ranges
+// covering [0, L). Cuts are assumed sorted, deduped, and strictly interior; an
+// empty slice yields a single {0, L} segment.
+func segmentRanges(splits []int, L int32) []seg {
+ segs := make([]seg, 0, len(splits)+1)
+ start := int32(0)
+ for _, c := range splits {
+ segs = append(segs, seg{start, int32(c)})
+ start = int32(c)
+ }
+ return append(segs, seg{start, L})
+}
+
+// segmentLens returns each row's real query length within segment
+// [s.start, s.end): the portion of the row's full real length that falls
+// inside the segment, clamped to the segment width. Rows that already ended
+// before the segment contribute 0; rows extending past it are full.
+func segmentLens(b *batch.Batch, s seg) []int32 {
+ lens := make([]int32, len(b.SeqQueryLens))
+ for i := range lens {
+ lens[i] = min(max(b.SeqQueryLens[i]-s.start, 0), s.len())
+ }
+ return lens
+}
+
+// sliceSeg slices x to the segment's window [s.start, s.end) along the L axis
+// (axis 1), keeping all other axes whole. Works for any rank — [B, L],
+// [B, L, H], [B, L, H, D] — so the padding mask, conv/gate/beta, and q/k/v all
+// slice the same L range and stay aligned. Returns nil when x is nil (the
+// no-padding-mask fast path). Slicing the full-forward mask this way yields
+// the segment's own mask, so masks are built once per forward and reused
+// across segments and layers.
+func sliceSeg(x *mlx.Array, s seg) *mlx.Array {
+ if x == nil {
+ return nil
+ }
+ rank := x.NumDims()
+ start := make([]int32, rank)
+ stop := make([]int32, rank)
+ for d := range rank {
+ start[d], stop[d] = 0, int32(x.Dim(d))
+ }
+ start[1], stop[1] = s.start, s.end
+ return mlx.SliceStartStop(x, start, stop)
+}
+
// resolve applies opts and panics if WithRecurrentHistory and
// WithRecurrentState were combined or neither was supplied.
func resolveRecurrentConfig(opts []RecurrentOption) recurrentConfig {
@@ -55,10 +116,8 @@ func resolveRecurrentConfig(opts []RecurrentOption) recurrentConfig {
}
// CausalConv1D runs a depthwise causal 1D convolution with recurrent
-// state management. Prepends the prior conv state along axis 1, runs
-// the conv, and returns (output, nextConv). nextConv is the trailing
-// convTail positions of the concat — write it back to the cache via
-// Put alongside the scan's new delta state.
+// state management. Prepends the prior conv state along axis 1 and runs
+// the conv.
//
// Conv selection: when conv is non-nil (a full nn.Conv1d layer), it
// runs through conv.Forward. Otherwise weight is treated as the bare
@@ -70,7 +129,13 @@ func resolveRecurrentConfig(opts []RecurrentOption) recurrentConfig {
//
// Prior state comes from exactly one of WithRecurrentHistory (cache
// path) or WithRecurrentState (no-cache path).
-func CausalConv1D(b *batch.Batch, input *mlx.Array, conv *Conv1d, weight *mlx.Array, convTail int, opts ...RecurrentOption) (out, nextConv *mlx.Array) {
+//
+// Returns the output and the conv states at each boundary, ending with the
+// forward-end conv tail. Without WithSnapshotSplits there is one boundary (the
+// end), so states has length 1. With splits, the conv runs in segments and
+// states holds the conv tail at each interior split and at the end; out is
+// identical to the unsegmented conv.
+func CausalConv1D(b *batch.Batch, input *mlx.Array, conv *Conv1d, weight *mlx.Array, convTail int, opts ...RecurrentOption) (out *mlx.Array, states []*mlx.Array) {
cfg := resolveRecurrentConfig(opts)
var prior *mlx.Array
if cfg.history != nil {
@@ -79,7 +144,33 @@ func CausalConv1D(b *batch.Batch, input *mlx.Array, conv *Conv1d, weight *mlx.Ar
prior = cfg.convState
}
- mask := paddingMask(b, int32(input.Dim(1)))
+ L := int32(input.Dim(1))
+ mask := paddingMask(b, L) // built once per forward, sliced per segment
+ segs := segmentRanges(cfg.splits, L)
+ if len(segs) <= 1 {
+ out, end := causalConv1DSegment(input, prior, mask, b.SeqQueryLens, conv, weight, convTail)
+ return out, []*mlx.Array{end}
+ }
+
+ // Segmented conv: each piece prepends the prior piece's conv tail,
+ // recording the conv tail at every boundary (interior splits + end).
+ outs := make([]*mlx.Array, 0, len(segs))
+ states = make([]*mlx.Array, 0, len(segs))
+ state := prior
+ for _, s := range segs {
+ segOut, segNext := causalConv1DSegment(sliceSeg(input, s), state, sliceSeg(mask, s), segmentLens(b, s), conv, weight, convTail)
+ outs = append(outs, segOut)
+ state = segNext
+ states = append(states, segNext)
+ }
+ return mlx.Concatenate(outs, 1), states
+}
+
+// causalConv1DSegment convolves one segment: prepend prior, convolve, return
+// (output, conv tail). mask is the [B, L] padding mask for input (nil if no
+// row is padded); queryLens is each row's real query length (used to gather
+// the per-row conv tail when masking is in play).
+func causalConv1DSegment(input, prior *mlx.Array, mask *mlx.Array, queryLens []int32, conv *Conv1d, weight *mlx.Array, convTail int) (out, nextConv *mlx.Array) {
if mask != nil {
zero := mlx.FromValue(float32(0)).AsType(input.DType())
input = mlx.Where(mlx.ExpandDims(mask, 2), input, zero)
@@ -101,7 +192,7 @@ func CausalConv1D(b *batch.Batch, input *mlx.Array, conv *Conv1d, weight *mlx.Ar
offsets := make([]int32, int(B)*convTail)
for i := range int(B) {
- end := b.SeqQueryLens[i]
+ end := queryLens[i]
for k := range convTail {
offsets[i*convTail+k] = end + int32(k)
@@ -151,9 +242,10 @@ func depthwiseCausalConv1d(x, w *mlx.Array, outLen int32) *mlx.Array {
}
// GatedDelta wraps mlx.FastGatedDelta with recurrent state management.
-// Reads prior delta state from the supplied option and returns
-// (output, newDelta). Write newDelta back via the cache's Put
-// alongside the conv wrapper's nextConv.
+// Reads prior delta state from the supplied option and returns the output
+// and the delta states at each boundary. The boundary states end with the
+// forward-end state. Without WithSnapshotSplits there is one boundary (the
+// end), so states has length 1.
//
// Shape conventions:
//
@@ -164,16 +256,44 @@ func depthwiseCausalConv1d(x, w *mlx.Array, outLen int32) *mlx.Array {
//
// Prior state comes from exactly one of WithRecurrentHistory (cache
// path) or WithRecurrentState (no-cache path).
-func GatedDelta(b *batch.Batch, q, k, v, gDecay, beta *mlx.Array, opts ...RecurrentOption) (out, newDelta *mlx.Array) {
+//
+// When WithSnapshotSplits supplies interior offsets, the scan runs in
+// segments cut at those offsets, threading delta state between them; states
+// holds the delta state at each interior split and at the end. out is
+// identical to the unsegmented scan.
+func GatedDelta(b *batch.Batch, q, k, v, gDecay, beta *mlx.Array, opts ...RecurrentOption) (out *mlx.Array, states []*mlx.Array) {
cfg := resolveRecurrentConfig(opts)
- var state *mlx.Array
+ var prior *mlx.Array
if cfg.history != nil {
- state = cfg.history.DeltaState()
+ prior = cfg.history.DeltaState()
} else {
- state = cfg.deltaState
+ prior = cfg.deltaState
}
- return mlx.FastGatedDelta(q, k, v, gDecay, beta, state, paddingMask(b, int32(q.Dim(1))))
+ L := int32(q.Dim(1))
+ mask := paddingMask(b, L) // built once per forward, sliced per segment
+ segs := segmentRanges(cfg.splits, L)
+ if len(segs) <= 1 {
+ out, end := mlx.FastGatedDelta(q, k, v, gDecay, beta, prior, mask)
+ return out, []*mlx.Array{end}
+ }
+
+ // Segmented scan: run each [a,c) piece with the prior segment's state,
+ // recording the delta state at every boundary (interior splits + end).
+ outs := make([]*mlx.Array, 0, len(segs))
+ states = make([]*mlx.Array, 0, len(segs))
+ state := prior
+ for _, seg := range segs {
+ segOut, segState := mlx.FastGatedDelta(
+ sliceSeg(q, seg), sliceSeg(k, seg), sliceSeg(v, seg),
+ sliceSeg(gDecay, seg), sliceSeg(beta, seg),
+ state, sliceSeg(mask, seg),
+ )
+ outs = append(outs, segOut)
+ state = segState
+ states = append(states, segState)
+ }
+ return mlx.Concatenate(outs, 1), states
}
// RecurrentHistory is an opaque per-forward view a recurrent cache
diff --git a/x/models/nn/recurrent_test.go b/x/models/nn/recurrent_test.go
index d6e0d3538..7e8eb6f86 100644
--- a/x/models/nn/recurrent_test.go
+++ b/x/models/nn/recurrent_test.go
@@ -12,6 +12,10 @@ func ones(dtype mlx.DType, shape ...int) *mlx.Array {
return mlx.AddScalar(mlx.Zeros(dtype, shape...), 1)
}
+// lastState returns the forward-end state — the last boundary the recurrent
+// wrappers return.
+func lastState(states []*mlx.Array) *mlx.Array { return states[len(states)-1] }
+
// fromValues builds a tensor with sequentially-numbered float32
// values so element-by-element parity actually exercises the kernel.
func fromValues(seed float32, shape ...int) *mlx.Array {
@@ -67,7 +71,8 @@ func TestCausalConv1DParity(t *testing.T) {
prior := fromValues(-0.3, B, convTail, D)
weight := fromValues(0.2, D, K)
- out, nextConv := CausalConv1D(&batch.Batch{}, input, nil, weight, convTail, WithRecurrentState(prior, nil))
+ out, convStates := CausalConv1D(&batch.Batch{}, input, nil, weight, convTail, WithRecurrentState(prior, nil))
+ nextConv := lastState(convStates)
mlx.Eval(out, nextConv)
concat := mlx.Concatenate([]*mlx.Array{prior, input}, 1)
@@ -143,19 +148,22 @@ func TestCausalConv1DPaddedRowParity(t *testing.T) {
SeqQueryLens: []int32{int32(L), int32(qLenShort)},
}
- out, nextConv := CausalConv1D(b, input, nil, weight, convTail, WithRecurrentState(priorFull, nil))
+ out, convStates := CausalConv1D(b, input, nil, weight, convTail, WithRecurrentState(priorFull, nil))
+ nextConv := lastState(convStates)
mlx.Eval(out, nextConv)
// Reference for row 0: B=1 unpadded length-L call.
- refOut0, refNextConv0 := CausalConv1D(&batch.Batch{},
+ refOut0, refConvStates0 := CausalConv1D(&batch.Batch{},
inputFull, nil, weight, convTail,
WithRecurrentState(mlx.SliceStartStop(priorFull,
[]int32{0, 0, 0},
[]int32{1, int32(convTail), int32(D)}), nil))
+ refNextConv0 := lastState(refConvStates0)
// Reference for row 1: B=1 unpadded length-qLenShort call.
- refOut1, refNextConv1 := CausalConv1D(&batch.Batch{},
+ refOut1, refConvStates1 := CausalConv1D(&batch.Batch{},
inputShortReal, nil, weight, convTail,
WithRecurrentState(priorShort, nil))
+ refNextConv1 := lastState(refConvStates1)
mlx.Eval(refOut0, refNextConv0, refOut1, refNextConv1)
gotOut := out.Floats()
@@ -206,7 +214,11 @@ func TestCausalConv1DPaddedRowParity(t *testing.T) {
}
}
-func TestGatedDeltaZeroFallback(t *testing.T) {
+// TestGatedDeltaDelegatesToKernel checks the wrapper produces the same output
+// and final state as a direct mlx.FastGatedDelta call, for both a zero prior
+// state and a non-zero one (so the wrapper is shown to thread the prior through,
+// not just handle the zero path).
+func TestGatedDeltaDelegatesToKernel(t *testing.T) {
skipIfNoMLX(t)
B, L, nK, nV, dK, dV := 1, 2, 1, 1, 4, 4
q := ones(mlx.DTypeFloat32, B, L, nK, dK)
@@ -215,45 +227,33 @@ func TestGatedDeltaZeroFallback(t *testing.T) {
gDecay := ones(mlx.DTypeFloat32, B, L, nV)
beta := ones(mlx.DTypeFloat32, B, L, nV)
- zero := mlx.Zeros(mlx.DTypeFloat32, B, nV, dV, dK)
- outA, stateA := GatedDelta(&batch.Batch{}, q, k, v, gDecay, beta, WithRecurrentState(nil, zero))
- outB, stateB := mlx.FastGatedDelta(q, k, v, gDecay, beta, zero, nil)
- mlx.Eval(outA, stateA, outB, stateB)
-
- gotOut, wantOut := outA.Floats(), outB.Floats()
- for i := range wantOut {
- if gotOut[i] != wantOut[i] {
- t.Fatalf("output[%d]: wrapper=%v direct=%v", i, gotOut[i], wantOut[i])
- }
- }
- gotState, wantState := stateA.Floats(), stateB.Floats()
- for i := range wantState {
- if gotState[i] != wantState[i] {
- t.Fatalf("state[%d]: wrapper=%v direct=%v", i, gotState[i], wantState[i])
- }
+ cases := []struct {
+ name string
+ prior *mlx.Array
+ }{
+ {"zero", mlx.Zeros(mlx.DTypeFloat32, B, nV, dV, dK)},
+ {"non-zero", mlx.MulScalar(ones(mlx.DTypeFloat32, B, nV, dV, dK), 3)},
}
-}
-
-func TestGatedDeltaUsesPriorState(t *testing.T) {
- skipIfNoMLX(t)
- B, L, nK, nV, dK, dV := 1, 2, 1, 1, 4, 4
- q := ones(mlx.DTypeFloat32, B, L, nK, dK)
- k := ones(mlx.DTypeFloat32, B, L, nK, dK)
- v := ones(mlx.DTypeFloat32, B, L, nV, dV)
- gDecay := ones(mlx.DTypeFloat32, B, L, nV)
- beta := ones(mlx.DTypeFloat32, B, L, nV)
-
- priorState := mlx.MulScalar(ones(mlx.DTypeFloat32, B, nV, dV, dK), 3)
-
- outA, _ := GatedDelta(&batch.Batch{}, q, k, v, gDecay, beta, WithRecurrentState(nil, priorState))
- outB, _ := mlx.FastGatedDelta(q, k, v, gDecay, beta, priorState, nil)
- mlx.Eval(outA, outB)
-
- gotOut, wantOut := outA.Floats(), outB.Floats()
- for i := range wantOut {
- if gotOut[i] != wantOut[i] {
- t.Fatalf("output[%d]: wrapper=%v direct=%v", i, gotOut[i], wantOut[i])
- }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ outA, statesA := GatedDelta(&batch.Batch{}, q, k, v, gDecay, beta, WithRecurrentState(nil, tc.prior))
+ stateA := lastState(statesA)
+ outB, stateB := mlx.FastGatedDelta(q, k, v, gDecay, beta, tc.prior, nil)
+ mlx.Eval(outA, stateA, outB, stateB)
+
+ gotOut, wantOut := outA.Floats(), outB.Floats()
+ for i := range wantOut {
+ if gotOut[i] != wantOut[i] {
+ t.Fatalf("output[%d]: wrapper=%v direct=%v", i, gotOut[i], wantOut[i])
+ }
+ }
+ gotState, wantState := stateA.Floats(), stateB.Floats()
+ for i := range wantState {
+ if gotState[i] != wantState[i] {
+ t.Fatalf("state[%d]: wrapper=%v direct=%v", i, gotState[i], wantState[i])
+ }
+ }
+ })
}
}
@@ -298,7 +298,8 @@ func TestGatedDeltaPaddedRowParity(t *testing.T) {
SeqOffsets: []int32{0, 0},
SeqQueryLens: []int32{int32(L), int32(qLenShort)},
}
- _, state := GatedDelta(b, q, k, v, gDecay, beta, WithRecurrentState(nil, priorState))
+ _, states := GatedDelta(b, q, k, v, gDecay, beta, WithRecurrentState(nil, priorState))
+ state := lastState(states)
mlx.Eval(state)
// Reference for row 1: B=1 length-qLenShort call against the
@@ -338,3 +339,205 @@ func TestGatedDeltaPaddedRowParity(t *testing.T) {
}
}
}
+
+// floatsClose compares two flat float slices within tolerance.
+func floatsClose(t *testing.T, label string, got, want []float32, tol float64) {
+ t.Helper()
+ if len(got) != len(want) {
+ t.Fatalf("%s: len %d, want %d", label, len(got), len(want))
+ }
+ for i := range want {
+ if math.Abs(float64(got[i]-want[i])) > tol {
+ t.Fatalf("%s[%d]: got %v, want %v", label, i, got[i], want[i])
+ }
+ }
+}
+
+// TestGatedDeltaSegmentEquivalence checks that running the scan in segments
+// cut at WithSnapshotSplits offsets yields identical output and final state to
+// the single-shot scan, and that each boundary state equals the single-shot
+// state over the corresponding prefix.
+func TestGatedDeltaSegmentEquivalence(t *testing.T) {
+ skipIfNoMLX(t)
+ B, T, Hk, Dk, Hv, Dv := 1, 4, 1, 32, 1, 32
+
+ q := fromValues(0.1, B, T, Hk, Dk)
+ k := fromValues(-0.2, B, T, Hk, Dk)
+ v := fromValues(0.3, B, T, Hv, Dv)
+ gDecay := mlx.MulScalar(ones(mlx.DTypeFloat32, B, T, Hv), 0.9)
+ beta := mlx.MulScalar(ones(mlx.DTypeFloat32, B, T, Hv), 0.5)
+ prior := mlx.Zeros(mlx.DTypeFloat32, B, Hv, Dv, Dk)
+
+ full := &batch.Batch{SeqOffsets: []int32{0}, SeqQueryLens: []int32{int32(T)}}
+
+ refOut, refStates := GatedDelta(full, q, k, v, gDecay, beta, WithRecurrentState(nil, prior))
+ if len(refStates) != 1 {
+ t.Fatalf("unsegmented call returned %d states, want 1", len(refStates))
+ }
+
+ segOut, segStates := GatedDelta(full, q, k, v, gDecay, beta,
+ WithRecurrentState(nil, prior), WithSnapshotSplits([]int{1, 2, 3}))
+ mlx.Eval(refOut, segOut)
+
+ floatsClose(t, "out", segOut.Floats(), refOut.Floats(), 1e-4)
+ // 3 splits + end = 4 boundary states.
+ if len(segStates) != 4 {
+ t.Fatalf("got %d boundary states, want 4", len(segStates))
+ }
+ mlx.Eval(lastState(segStates), lastState(refStates))
+ floatsClose(t, "final state", lastState(segStates).Floats(), lastState(refStates).Floats(), 1e-4)
+
+ // boundary i (offset i+1) must equal a single-shot scan over prefix [0, i+1).
+ for i := range segStates {
+ n := int32(i + 1)
+ pb := &batch.Batch{SeqOffsets: []int32{0}, SeqQueryLens: []int32{n}}
+ _, want := GatedDelta(pb,
+ mlx.SliceStartStop(q, []int32{0, 0, 0, 0}, []int32{int32(B), n, int32(Hk), int32(Dk)}),
+ mlx.SliceStartStop(k, []int32{0, 0, 0, 0}, []int32{int32(B), n, int32(Hk), int32(Dk)}),
+ mlx.SliceStartStop(v, []int32{0, 0, 0, 0}, []int32{int32(B), n, int32(Hv), int32(Dv)}),
+ mlx.SliceStartStop(gDecay, []int32{0, 0, 0}, []int32{int32(B), n, int32(Hv)}),
+ mlx.SliceStartStop(beta, []int32{0, 0, 0}, []int32{int32(B), n, int32(Hv)}),
+ WithRecurrentState(nil, prior))
+ mlx.Eval(segStates[i], lastState(want))
+ floatsClose(t, "boundary delta", segStates[i].Floats(), lastState(want).Floats(), 1e-4)
+ }
+}
+
+// TestCausalConv1DSegmentEquivalence checks the conv segmented path matches the
+// single-shot conv for output, final conv tail, and each boundary conv state.
+func TestCausalConv1DSegmentEquivalence(t *testing.T) {
+ skipIfNoMLX(t)
+ B, L, D, convTail := 1, 4, 3, 2
+ K := convTail + 1
+
+ input := fromValues(0.5, B, L, D)
+ prior := fromValues(-0.3, B, convTail, D)
+ weight := fromValues(0.2, D, K)
+
+ full := &batch.Batch{SeqOffsets: []int32{0}, SeqQueryLens: []int32{int32(L)}}
+
+ refOut, refStates := CausalConv1D(full, input, nil, weight, convTail, WithRecurrentState(prior, nil))
+ if len(refStates) != 1 {
+ t.Fatalf("unsegmented call returned %d states, want 1", len(refStates))
+ }
+
+ segOut, segStates := CausalConv1D(full, input, nil, weight, convTail,
+ WithRecurrentState(prior, nil), WithSnapshotSplits([]int{1, 2, 3}))
+ mlx.Eval(refOut, segOut)
+
+ floatsClose(t, "conv out", segOut.Floats(), refOut.Floats(), 1e-4)
+ if len(segStates) != 4 {
+ t.Fatalf("got %d boundary conv states, want 4", len(segStates))
+ }
+ mlx.Eval(lastState(segStates), lastState(refStates))
+ floatsClose(t, "conv final", lastState(segStates).Floats(), lastState(refStates).Floats(), 1e-4)
+
+ for i := range segStates {
+ n := int32(i + 1)
+ pb := &batch.Batch{SeqOffsets: []int32{0}, SeqQueryLens: []int32{n}}
+ _, want := CausalConv1D(pb,
+ mlx.SliceStartStop(input, []int32{0, 0, 0}, []int32{int32(B), n, int32(D)}),
+ nil, weight, convTail, WithRecurrentState(prior, nil))
+ mlx.Eval(segStates[i], lastState(want))
+ floatsClose(t, "boundary conv", segStates[i].Floats(), lastState(want).Floats(), 1e-4)
+ }
+}
+
+// TestGatedDeltaSegmentEquivalenceBatched checks the segmented scan matches the
+// single-shot scan for B>1, including a ragged batch where rows have different
+// real lengths — segmentLens must clamp each row's per-segment query length.
+func TestGatedDeltaSegmentEquivalenceBatched(t *testing.T) {
+ skipIfNoMLX(t)
+ B, T, Hk, Dk, Hv, Dv := 2, 4, 1, 32, 1, 32
+
+ q := fromValues(0.1, B, T, Hk, Dk)
+ k := fromValues(-0.2, B, T, Hk, Dk)
+ v := fromValues(0.3, B, T, Hv, Dv)
+ gDecay := mlx.MulScalar(ones(mlx.DTypeFloat32, B, T, Hv), 0.9)
+ beta := mlx.MulScalar(ones(mlx.DTypeFloat32, B, T, Hv), 0.5)
+ prior := mlx.Zeros(mlx.DTypeFloat32, B, Hv, Dv, Dk)
+
+ // Row 0 full length T; row 1 ends at 3 (so segment [3,4) is all padding
+ // for row 1).
+ full := &batch.Batch{SeqOffsets: []int32{0, 0}, SeqQueryLens: []int32{int32(T), 3}}
+
+ refOut, refStates := GatedDelta(full, q, k, v, gDecay, beta, WithRecurrentState(nil, prior))
+ segOut, segStates := GatedDelta(full, q, k, v, gDecay, beta,
+ WithRecurrentState(nil, prior), WithSnapshotSplits([]int{1, 2, 3}))
+ mlx.Eval(refOut, segOut, lastState(refStates), lastState(segStates))
+
+ floatsClose(t, "batched out", segOut.Floats(), refOut.Floats(), 1e-4)
+ floatsClose(t, "batched final state", lastState(segStates).Floats(), lastState(refStates).Floats(), 1e-4)
+ if len(segStates) != 4 {
+ t.Fatalf("got %d boundary states, want 4", len(segStates))
+ }
+
+ // Each row's boundary i (offset i+1) must equal a B=1 single-shot scan over
+ // that row's real prefix: row 0 advances the full length, row 1 freezes once
+ // it reaches its real length 3. Per-row B=1 references avoid the ambiguity of
+ // re-declaring a ragged length over a uniform input slice.
+ rowReal := []int32{int32(T), 3}
+ for i := range segStates {
+ for r := range B {
+ n := min(int32(i+1), rowReal[r])
+ lo, hi := int32(r), int32(r)+1
+ rowPrior := mlx.SliceStartStop(prior, []int32{lo, 0, 0, 0}, []int32{hi, int32(Hv), int32(Dv), int32(Dk)})
+ _, want := GatedDelta(&batch.Batch{},
+ mlx.SliceStartStop(q, []int32{lo, 0, 0, 0}, []int32{hi, n, int32(Hk), int32(Dk)}),
+ mlx.SliceStartStop(k, []int32{lo, 0, 0, 0}, []int32{hi, n, int32(Hk), int32(Dk)}),
+ mlx.SliceStartStop(v, []int32{lo, 0, 0, 0}, []int32{hi, n, int32(Hv), int32(Dv)}),
+ mlx.SliceStartStop(gDecay, []int32{lo, 0, 0}, []int32{hi, n, int32(Hv)}),
+ mlx.SliceStartStop(beta, []int32{lo, 0, 0}, []int32{hi, n, int32(Hv)}),
+ WithRecurrentState(nil, rowPrior))
+ gotRow := mlx.SliceStartStop(segStates[i], []int32{lo, 0, 0, 0}, []int32{hi, int32(Hv), int32(Dv), int32(Dk)})
+ mlx.Eval(gotRow, lastState(want))
+ floatsClose(t, "batched boundary delta", gotRow.Floats(), lastState(want).Floats(), 1e-4)
+ }
+ }
+}
+
+// TestCausalConv1DSegmentEquivalenceBatched is the conv analog: segmented vs
+// single-shot for a ragged B>1 batch.
+func TestCausalConv1DSegmentEquivalenceBatched(t *testing.T) {
+ skipIfNoMLX(t)
+ B, L, D, convTail := 2, 4, 3, 2
+ K := convTail + 1
+
+ input := fromValues(0.5, B, L, D)
+ prior := fromValues(-0.3, B, convTail, D)
+ weight := fromValues(0.2, D, K)
+
+ full := &batch.Batch{SeqOffsets: []int32{0, 0}, SeqQueryLens: []int32{int32(L), 3}}
+
+ refOut, refStates := CausalConv1D(full, input, nil, weight, convTail, WithRecurrentState(prior, nil))
+ segOut, segStates := CausalConv1D(full, input, nil, weight, convTail,
+ WithRecurrentState(prior, nil), WithSnapshotSplits([]int{1, 2, 3}))
+ mlx.Eval(refOut, segOut, lastState(refStates), lastState(segStates))
+
+ floatsClose(t, "batched conv out", segOut.Floats(), refOut.Floats(), 1e-4)
+ floatsClose(t, "batched conv final", lastState(segStates).Floats(), lastState(refStates).Floats(), 1e-4)
+ if len(segStates) != 4 {
+ t.Fatalf("got %d boundary conv states, want 4", len(segStates))
+ }
+
+ // Each row's boundary i (offset i+1) must equal a B=1 single-shot conv over
+ // that row's real prefix: row 0 advances the full length, row 1 freezes once
+ // it reaches its real length 3. Per-row B=1 references avoid the ambiguity of
+ // re-declaring a ragged length over a uniform input slice.
+ rowReal := []int32{int32(L), 3}
+ for i := range segStates {
+ for r := range B {
+ n := min(int32(i+1), rowReal[r])
+ rowPrior := mlx.SliceStartStop(prior,
+ []int32{int32(r), 0, 0}, []int32{int32(r) + 1, int32(convTail), int32(D)})
+ rowInput := mlx.SliceStartStop(input,
+ []int32{int32(r), 0, 0}, []int32{int32(r) + 1, n, int32(D)})
+ _, want := CausalConv1D(&batch.Batch{}, rowInput, nil, weight, convTail,
+ WithRecurrentState(rowPrior, nil))
+ gotRow := mlx.SliceStartStop(segStates[i],
+ []int32{int32(r), 0, 0}, []int32{int32(r) + 1, int32(convTail), int32(D)})
+ mlx.Eval(gotRow, lastState(want))
+ floatsClose(t, "batched boundary conv", gotRow.Floats(), lastState(want).Floats(), 1e-4)
+ }
+ }
+}
diff --git a/x/models/qwen3_5/qwen3_5.go b/x/models/qwen3_5/qwen3_5.go
index 0598eadd7..17f479193 100644
--- a/x/models/qwen3_5/qwen3_5.go
+++ b/x/models/qwen3_5/qwen3_5.go
@@ -1176,7 +1176,7 @@ func (g *GatedDeltaNet) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, B,
)
}
- convOut, nextConv := nn.CausalConv1D(b, qkv, g.Conv1D, g.ConvWeight, int(convTail), rec)
+ convOut, convStates := nn.CausalConv1D(b, qkv, g.Conv1D, g.ConvWeight, int(convTail), rec)
convOut = mlx.SiLU(convOut)
keyDim := cfg.LinearNumKeyHeads * cfg.LinearKeyHeadDim
@@ -1198,14 +1198,14 @@ func (g *GatedDeltaNet) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, B,
betaGate := mlx.Sigmoid(beta)
- out, state := nn.GatedDelta(b, q, k, v, gDecay, betaGate, rec)
+ out, deltaStates := nn.GatedDelta(b, q, k, v, gDecay, betaGate, rec)
outDType := out.DType()
out = mlx.RMSNormFn(out, g.NormWeight, cfg.RMSNormEps)
out = mlx.Mul(out.AsType(mlx.DTypeFloat32), mlx.SiLU(z.AsType(mlx.DTypeFloat32))).AsType(outDType)
out = mlx.Reshape(out, B, L, valueDim)
out = g.OutProj.Forward(out)
if rc != nil {
- rc.Put(b, nextConv, state)
+ rc.Put(b, convStates, deltaStates)
}
return out
}