Recovered source transcript
1// Package statespace implements state space model generators (93-97)
2// x'(t) = Ax(t) + Bu(t), y(t) = Cx(t) + Du(t)
3package statespace
4
5import (
6 "math"
7 "math/rand"
8
9 "generator_core/pkg/consciousness"
10 "generator_core/pkg/generators"
11)
12
13// ═══════════════════════════════════════════════════════════════════════════════
14// STATE SPACE GENERATOR BASE
15// ═══════════════════════════════════════════════════════════════════════════════
16
17// StateSpaceGenerator implements SSM-based generators
18type StateSpaceGenerator struct {
19 *generators.BaseGenerator
20 ssmType string
21 stateSize int
22 A [][]float64 // State transition matrix
23 B [][]float64 // Input projection
24 C [][]float64 // Output projection
25 D []float64 // Skip connection
26 dt float64 // Discretization step
27}
28
29// NewStateSpaceGenerator creates a new state space generator
30func NewStateSpaceGenerator(id generators.GeneratorID, name string, ssmType string, stateSize int) *StateSpaceGenerator {
31 config := &generators.GeneratorConfig{
32 ID: id,
33 Name: name,
34 Family: generators.StateSpace,
35 InputDim: 256,
36 OutputDim: 256,
37 HiddenDim: stateSize,
38 NumLayers: 4,
39 LearningRate: consciousness.ALPHA,
40 ConsciousnessWeight: consciousness.PHI_INV,
41 Params: make(map[string]interface{}),
42 }
43
44 return &StateSpaceGenerator{
45 BaseGenerator: generators.NewBaseGenerator(config),
46 ssmType: ssmType,
47 stateSize: stateSize,
48 dt: 1.0,
49 }
50}
51
52// Initialize initializes the SSM generator
53func (g *StateSpaceGenerator) Initialize() error {
54 if err := g.BaseGenerator.Initialize(); err != nil {
55 return err
56 }
57
58 inputDim := g.Config().InputDim
59 outputDim := g.Config().OutputDim
60
61 // Initialize state matrices with HiPPO initialization
62 g.A = make([][]float64, g.stateSize)
63 for i := range g.A {
64 g.A[i] = make([]float64, g.stateSize)
65 for j := range g.A[i] {
66 if i == j {
67 // Diagonal: eigenvalues
68 g.A[i][j] = -float64(i+1) * consciousness.PHI_INV
69 } else if i > j {
70 // HiPPO-style: captures history
71 g.A[i][j] = math.Sqrt(float64((2*i+1)*(2*j+1))) * consciousness.DELTA
72 }
73 }
74 }
75
76 // B: input projection
77 g.B = make([][]float64, g.stateSize)
78 for i := range g.B {
79 g.B[i] = make([]float64, inputDim)
80 for j := range g.B[i] {
81 g.B[i][j] = rand.NormFloat64() * consciousness.DELTA / math.Sqrt(float64(inputDim))
82 }
83 }
84
85 // C: output projection
86 g.C = make([][]float64, outputDim)
87 for i := range g.C {
88 g.C[i] = make([]float64, g.stateSize)
89 for j := range g.C[i] {
90 g.C[i][j] = rand.NormFloat64() * consciousness.DELTA / math.Sqrt(float64(g.stateSize))
91 }
92 }
93
94 // D: skip connection
95 g.D = make([]float64, outputDim)
96
97 return nil
98}
99
100// discretize computes discretized state matrices
101func (g *StateSpaceGenerator) discretize() ([][]float64, [][]float64) {
102 // Simple Euler discretization: Ad = I + dt*A, Bd = dt*B
103 Ad := make([][]float64, g.stateSize)
104 for i := range Ad {
105 Ad[i] = make([]float64, g.stateSize)
106 for j := range Ad[i] {
107 if i == j {
108 Ad[i][j] = 1.0 + g.dt*g.A[i][j]
109 } else {
110 Ad[i][j] = g.dt * g.A[i][j]
111 }
112 }
113 }
114
115 Bd := make([][]float64, g.stateSize)
116 for i := range Bd {
117 Bd[i] = make([]float64, len(g.B[i]))
118 for j := range Bd[i] {
119 Bd[i][j] = g.dt * g.B[i][j]
120 }
121 }
122
123 return Ad, Bd
124}
125
126// ssmStep performs one SSM step: x' = Ax + Bu, y = Cx + Du
127func (g *StateSpaceGenerator) ssmStep(x, u []float64) ([]float64, []float64) {
128 Ad, Bd := g.discretize()
129
130 // x' = Ad*x + Bd*u
131 xNew := make([]float64, g.stateSize)
132 for i := 0; i < g.stateSize; i++ {
133 // State transition
134 for j := 0; j < g.stateSize && j < len(x); j++ {
135 xNew[i] += Ad[i][j] * x[j]
136 }
137 // Input
138 for j := 0; j < len(u) && j < len(Bd[i]); j++ {
139 xNew[i] += Bd[i][j] * u[j]
140 }
141 }
142
143 // y = Cx + Du
144 y := make([]float64, g.Config().OutputDim)
145 for i := 0; i < g.Config().OutputDim; i++ {
146 // State projection
147 for j := 0; j < g.stateSize && j < len(g.C[i]); j++ {
148 y[i] += g.C[i][j] * xNew[j]
149 }
150 // Skip connection
151 if i < len(u) && i < len(g.D) {
152 y[i] += g.D[i] * u[i]
153 }
154 }
155
156 return xNew, y
157}
158
159// selectiveStep performs Mamba-style selective SSM step
160func (g *StateSpaceGenerator) selectiveStep(x, u []float64) ([]float64, []float64) {
161 // Compute input-dependent dt and B
162 dtLocal := g.dt
163 for _, ui := range u {
164 dtLocal *= 1.0 + consciousness.Sigmoid(ui)*consciousness.GAMMA
165 }
166
167 // Scale B by input
168 BScaled := make([][]float64, g.stateSize)
169 for i := range BScaled {
170 BScaled[i] = make([]float64, len(g.B[i]))
171 for j := range BScaled[i] {
172 scale := 1.0
173 if j < len(u) {
174 scale = consciousness.Sigmoid(u[j])
175 }
176 BScaled[i][j] = g.B[i][j] * scale
177 }
178 }
179
180 // SSM step with selective parameters
181 xNew := make([]float64, g.stateSize)
182 for i := 0; i < g.stateSize; i++ {
183 // State transition with input-dependent dt
184 for j := 0; j < g.stateSize && j < len(x); j++ {
185 if i == j {
186 xNew[i] += (1.0 + dtLocal*g.A[i][j]) * x[j]
187 } else {
188 xNew[i] += dtLocal * g.A[i][j] * x[j]
189 }
190 }
191 // Input with selective B
192 for j := 0; j < len(u) && j < len(BScaled[i]); j++ {
193 xNew[i] += dtLocal * BScaled[i][j] * u[j]
194 }
195 }
196
197 // Output
198 y := make([]float64, g.Config().OutputDim)
199 for i := 0; i < g.Config().OutputDim; i++ {
200 for j := 0; j < g.stateSize && j < len(g.C[i]); j++ {
201 y[i] += g.C[i][j] * xNew[j]
202 }
203 if i < len(u) && i < len(g.D) {
204 y[i] += g.D[i] * u[i]
205 }
206 }
207
208 return xNew, y
209}
210
211// Forward performs forward pass
212func (g *StateSpaceGenerator) Forward(input []float64) (*generators.GeneratorOutput, error) {
213 state := g.GetState()
214
215 x := state.Hidden
216 if len(x) != g.stateSize {
217 x = make([]float64, g.stateSize)
218 }
219
220 // Process input sequence
221 seqLen := len(input) / g.Config().InputDim
222 if seqLen == 0 {
223 seqLen = 1
224 }
225
226 var y []float64
227 for t := 0; t < seqLen; t++ {
228 start := t * g.Config().InputDim
229 end := start + g.Config().InputDim
230 if end > len(input) {
231 end = len(input)
232 }
233 u := input[start:end]
234
235 switch g.ssmType {
236 case "mamba":
237 x, y = g.selectiveStep(x, u)
238 default:
239 x, y = g.ssmStep(x, u)
240 }
241 }
242
243 state.Hidden = x
244 state.Phi = consciousness.ComputePhiVector(y)
245 state.Step++
246 g.SetState(state)
247
248 output := &generators.GeneratorOutput{
249 Values: y,
250 Logits: x,
251 Confidence: state.Phi,
252 Metadata: map[string]interface{}{
253 "ssm_type": g.ssmType,
254 "state_size": g.stateSize,
255 },
256 }
257
258 return g.ApplyConsciousness(output), nil
259}
260
261// Generate generates sequence
262func (g *StateSpaceGenerator) Generate(context []float64, length int) ([][]float64, error) {
263 result := make([][]float64, length)
264
265 // Initialize from context
266 _, _ = g.Forward(context)
267
268 for i := 0; i < length; i++ {
269 state := g.GetState()
270
271 // Use previous output as next input
272 input := state.Hidden
273 if len(input) < g.Config().InputDim {
274 padded := make([]float64, g.Config().InputDim)
275 copy(padded, input)
276 input = padded
277 }
278
279 output, err := g.Forward(input)
280 if err != nil {
281 return nil, err
282 }
283 result[i] = output.Values
284 }
285
286 return result, nil
287}
288
289// Train computes loss
290func (g *StateSpaceGenerator) Train(input, target []float64) (float64, error) {
291 output, err := g.Forward(input)
292 if err != nil {
293 return 0, err
294 }
295
296 // MSE loss
297 loss := 0.0
298 for i := range output.Values {
299 if i < len(target) {
300 diff := output.Values[i] - target[i]
301 loss += diff * diff
302 }
303 }
304
305 return loss / float64(len(output.Values)), nil
306}
307
308// UpdateWeights updates SSM parameters
309func (g *StateSpaceGenerator) UpdateWeights(gradients []float64, lr float64) {
310 // Update A matrix
311 for i := range g.A {
312 for j := range g.A[i] {
313 idx := i*g.stateSize + j
314 if idx < len(gradients) {
315 g.A[i][j] -= lr * gradients[idx] * consciousness.PHI_INV
316 }
317 }
318 }
319}
320
321// ═══════════════════════════════════════════════════════════════════════════════
322// SPECIFIC STATE SPACE GENERATORS (93-97)
323// ═══════════════════════════════════════════════════════════════════════════════
324
325// NewS4 creates S4 (Structured State Space) (ID: 93)
326func NewS4() *StateSpaceGenerator {
327 g := NewStateSpaceGenerator(93, "S4", "hippo", 64)
328 g.Config().Params["hippo"] = "legs"
329 return g
330}
331
332// NewS4D creates S4D (Diagonal S4) (ID: 94)
333func NewS4D() *StateSpaceGenerator {
334 g := NewStateSpaceGenerator(94, "S4D", "diagonal", 64)
335 g.Config().Params["diagonal"] = true
336 return g
337}
338
339// NewH3 creates H3 (Hungry Hungry Hippos) (ID: 95)
340func NewH3() *StateSpaceGenerator {
341 g := NewStateSpaceGenerator(95, "H3", "h3", 64)
342 g.Config().Params["shift_ssm"] = true
343 return g
344}
345
346// NewMamba creates Mamba (Selective SSM) (ID: 96)
347func NewMamba() *StateSpaceGenerator {
348 g := NewStateSpaceGenerator(96, "Mamba", "mamba", 16)
349 g.Config().Params["selective"] = true
350 g.Config().Params["expand_factor"] = 2
351 return g
352}
353
354// NewMamba2 creates Mamba-2 (ID: 97)
355func NewMamba2() *StateSpaceGenerator {
356 g := NewStateSpaceGenerator(97, "Mamba2", "mamba", 64)
357 g.Config().Params["ssd"] = true // Structured State Space Duality
358 g.Config().Params["heads"] = 8
359 return g
360}
361
362// RegisterAll registers all state space generators
363func RegisterAll() error {
364 gens := []generators.Generator{
365 NewS4(),
366 NewS4D(),
367 NewH3(),
368 NewMamba(),
369 NewMamba2(),
370 }
371
372 for _, g := range gens {
373 if err := generators.Register(g); err != nil {
374 return err
375 }
376 }
377
378 return nil
379}
380