aprender-serve 0.75.0

Pure Rust ML inference engine built from scratch - model serving for GGUF and safetensors
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//! ALB-010: MoE Expert Dispatch for Qwen3.5-35B-A3B
//!
//! Implements the Mixture-of-Experts forward pass:
//! 1. Router: softmax → top-k → renormalize (contract: moe-router-v1)
//! 2. Expert SwiGLU: down(SiLU(gate(x)) * up(x)) per selected expert
//! 3. Weighted sum of routed outputs + shared expert (contract: moe-expert-dispatch-v1)

use super::types::MoeExpertWeights;

/// Result of MoE routing for a single token.
#[derive(Debug)]
pub struct MoeRouteResult {
    /// Selected expert indices (len == num_experts_per_tok)
    pub indices: Vec<usize>,
    /// Renormalized weights (len == num_experts_per_tok, sum == 1.0)
    pub weights: Vec<f32>,
}

/// MoE router forward pass.
///
/// Contract: moe-router-v1.yaml
/// - softmax_normalization: probs sum to 1.0
/// - topk_selection: top-k experts by probability
/// - weight_renormalization: selected weights sum to 1.0
pub fn moe_route(
    hidden_state: &[f32],
    gate_weight: &[f32],
    num_experts: usize,
    num_experts_per_tok: usize,
    hidden_dim: usize,
) -> MoeRouteResult {
    // Step 1: logits = hidden_state @ gate_weight.T, shape [num_experts]
    // gate_weight layout: [num_experts, hidden_dim] row-major
    let mut logits = vec![0.0f32; num_experts];
    for e in 0..num_experts {
        let mut sum = 0.0f32;
        let offset = e * hidden_dim;
        for j in 0..hidden_dim {
            sum += hidden_state[j] * gate_weight[offset + j];
        }
        logits[e] = sum;
    }

    // Step 2: softmax with max subtraction for numerical stability
    let probs = router_probs(&logits);

    // Step 3: top-k selection
    let mut indexed: Vec<(usize, f32)> = probs.iter().copied().enumerate().collect();
    indexed.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
    let top_k: Vec<(usize, f32)> = indexed.into_iter().take(num_experts_per_tok).collect();

    // Step 4: renormalize selected weights to sum to 1.0
    let weight_sum: f32 = top_k.iter().map(|(_, w)| w).sum();
    let indices: Vec<usize> = top_k.iter().map(|(i, _)| *i).collect();
    let weights: Vec<f32> = if weight_sum > 0.0 {
        top_k.iter().map(|(_, w)| w / weight_sum).collect()
    } else {
        // Degenerate case: equal weights
        vec![1.0 / num_experts_per_tok as f32; num_experts_per_tok]
    };

    MoeRouteResult { indices, weights }
}

/// Router softmax with max subtraction (moe-router-v1 `softmax_normalization`:
/// the returned probabilities sum to 1.0).
fn router_probs(logits: &[f32]) -> Vec<f32> {
    let max_logit = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
    let mut probs: Vec<f32> = logits.iter().map(|&l| (l - max_logit).exp()).collect();
    let exp_sum: f32 = probs.iter().sum();
    for p in &mut probs {
        *p /= exp_sum;
    }
    probs
}

/// Single expert SwiGLU forward pass.
///
/// Computes: down(SiLU(gate(x)) * up(x))
///
/// # Arguments
/// - `x`: input hidden state [hidden_dim]
/// - `gate_proj`: gate weight [intermediate, hidden_dim]
/// - `up_proj`: up weight [intermediate, hidden_dim]
/// - `down_proj`: down weight [hidden_dim, intermediate]
/// - `hidden_dim`: model hidden dimension
/// - `intermediate`: expert intermediate dimension
fn expert_swiglu(
    x: &[f32],
    gate_proj: &[f32],
    up_proj: &[f32],
    down_proj: &[f32],
    hidden_dim: usize,
    intermediate: usize,
) -> Vec<f32> {
    // gate_out = gate_proj @ x, shape [intermediate]
    let mut gate_out = vec![0.0f32; intermediate];
    for i in 0..intermediate {
        let offset = i * hidden_dim;
        let mut sum = 0.0f32;
        for j in 0..hidden_dim {
            sum += gate_proj[offset + j] * x[j];
        }
        gate_out[i] = sum;
    }

    // up_out = up_proj @ x, shape [intermediate]
    let mut up_out = vec![0.0f32; intermediate];
    for i in 0..intermediate {
        let offset = i * hidden_dim;
        let mut sum = 0.0f32;
        for j in 0..hidden_dim {
            sum += up_proj[offset + j] * x[j];
        }
        up_out[i] = sum;
    }

    // SwiGLU: SiLU(gate_out) * up_out
    for i in 0..intermediate {
        let silu = gate_out[i] / (1.0 + (-gate_out[i]).exp());
        gate_out[i] = silu * up_out[i];
    }

    // down_out = down_proj @ gate_out, shape [hidden_dim]
    let mut output = vec![0.0f32; hidden_dim];
    for i in 0..hidden_dim {
        let offset = i * intermediate;
        let mut sum = 0.0f32;
        for j in 0..intermediate {
            sum += down_proj[offset + j] * gate_out[j];
        }
        output[i] = sum;
    }

    output
}

/// MoE forward pass for a single token.
///
/// Contract: moe-expert-dispatch-v1.yaml
/// - Routes to top-k experts via softmax router
/// - Runs SwiGLU on each selected expert
/// - Combines with weighted sum + shared expert
///
/// # Arguments
/// - `hidden_state`: input [hidden_dim]
/// - `moe`: expert weights
/// - `hidden_dim`: model hidden dimension
///
/// # Returns
/// MoE output [hidden_dim] = routed_sum + shared_expert(x)
pub fn moe_forward_token(
    hidden_state: &[f32],
    moe: &MoeExpertWeights,
    hidden_dim: usize,
) -> Vec<f32> {
    let intermediate = moe.expert_intermediate;
    let num_experts = moe.num_experts;
    let k = moe.num_experts_per_tok;

    // Step 1: Route
    let route = moe_route(hidden_state, &moe.gate_weight, num_experts, k, hidden_dim);

    // Step 2: Run selected experts and accumulate weighted sum
    let mut routed_out = vec![0.0f32; hidden_dim];

    for (idx, &expert_id) in route.indices.iter().enumerate() {
        // Unfuse gate_up: expert_gate_up layout [num_experts, 2*intermediate, hidden_dim]
        let expert_offset = expert_id * 2 * intermediate * hidden_dim;
        let gate_proj =
            &moe.expert_gate_up[expert_offset..expert_offset + intermediate * hidden_dim];
        let up_proj = &moe.expert_gate_up[expert_offset + intermediate * hidden_dim
            ..expert_offset + 2 * intermediate * hidden_dim];

        // expert_down layout [num_experts, hidden_dim, intermediate]
        let down_offset = expert_id * hidden_dim * intermediate;
        let down_proj = &moe.expert_down[down_offset..down_offset + hidden_dim * intermediate];

        let expert_out = expert_swiglu(
            hidden_state,
            gate_proj,
            up_proj,
            down_proj,
            hidden_dim,
            intermediate,
        );

        let w = route.weights[idx];
        for i in 0..hidden_dim {
            routed_out[i] += w * expert_out[i];
        }
    }

    // Step 3: Shared expert (always active, not gated by router)
    let shared_out = expert_swiglu(
        hidden_state,
        &moe.shared_gate,
        &moe.shared_up,
        &moe.shared_down,
        hidden_dim,
        intermediate,
    );

    // Step 4: moe_out = routed_out + gated_shared_out
    // Qwen3.5: shared_expert_gate is a [1, hidden_dim] linear → sigmoid scalar gate
    if !moe.shared_expert_gate_weight.is_empty() {
        let mut gate_logit = 0.0f32;
        for j in 0..hidden_dim {
            gate_logit += moe.shared_expert_gate_weight[j] * hidden_state[j];
        }
        let gate_scale = 1.0 / (1.0 + (-gate_logit).exp()); // sigmoid
        for i in 0..hidden_dim {
            routed_out[i] += gate_scale * shared_out[i];
        }
    } else {
        // No shared expert gate — add directly (dense model or ungated shared expert)
        for i in 0..hidden_dim {
            routed_out[i] += shared_out[i];
        }
    }

    routed_out
}

#[cfg(test)]
mod tests {
    use super::*;

    // FALSIFY-MOE-ROUTER-004 (FALSIFY-MOE_ROUTER_V1_001/002/003): router probs sum to 1, exactly k
    // distinct experts are selected, and their renormalized weights sum to 1.
    #[test]
    fn falsify_moe_router_v1_sums_and_topk() {
        const TOL: f32 = 1e-5;
        let logit_sets: [&[f32]; 5] = [
            &[0.0, 0.0, 0.0, 0.0],
            &[1.0, -2.0, 3.5, 0.25, -7.0, 2.0],
            &[80.0, 79.0, -80.0, 0.0, 12.0, 3.0, -1.0, 5.0],
            &[-3.0, -3.0, -1e-3, -50.0],
            &[0.5; 16],
        ];
        for logits in logit_sets {
            let sum: f32 = router_probs(logits).iter().sum();
            assert!(
                (sum - 1.0).abs() < TOL,
                "V1_001: probs sum {sum} for {logits:?}"
            );
        }
        let hidden_dim = 3;
        for (num_experts, k) in [(4, 1), (6, 2), (8, 3), (16, 16)] {
            let hidden: Vec<f32> = (0..hidden_dim).map(|j| 0.3 * j as f32 - 0.2).collect();
            let gate: Vec<f32> = (0..num_experts * hidden_dim)
                .map(|i| ((i * 7 % 11) as f32 - 5.0) * 0.4)
                .collect();
            let r = moe_route(&hidden, &gate, num_experts, k, hidden_dim);
            let mut distinct = r.indices.clone();
            distinct.sort_unstable();
            distinct.dedup();
            assert_eq!(
                (r.indices.len(), distinct.len()),
                (k, k),
                "V1_002: k={k} of {num_experts}"
            );
            let wsum: f32 = r.weights.iter().sum();
            assert!(
                (wsum - 1.0).abs() < TOL,
                "V1_003: weights sum {wsum} (k={k})"
            );
        }
    }

    // FALSIFY-MOE-ROUTER-001: Softmax stability with large logits
    #[test]
    fn test_softmax_stability_large_logits() {
        let hidden_dim = 4;
        let num_experts = 8;
        let hidden_state = vec![1.0f32; hidden_dim];
        // gate_weight: expert 0 has very large projection, expert 1 slightly less
        let mut gate_weight = vec![0.0f32; num_experts * hidden_dim];
        // Expert 0: weight = [250, 250, 250, 250] → dot = 1000
        for j in 0..hidden_dim {
            gate_weight[0 * hidden_dim + j] = 250.0;
        }
        // Expert 1: weight = [249.75, 249.75, ...] → dot = 999
        for j in 0..hidden_dim {
            gate_weight[1 * hidden_dim + j] = 249.75;
        }

        let result = moe_route(&hidden_state, &gate_weight, num_experts, 2, hidden_dim);

        // No NaN, no Inf
        for &w in &result.weights {
            assert!(w.is_finite(), "weight is not finite: {w}");
        }
        // Expert 0 selected first (highest logit)
        assert_eq!(result.indices[0], 0);
        // Expert 1 selected second
        assert_eq!(result.indices[1], 1);
        // Weights sum to 1
        let sum: f32 = result.weights.iter().sum();
        assert!((sum - 1.0).abs() < 1e-6, "weights sum = {sum}");
    }

    // FALSIFY-MOE-ROUTER-002: Zero gate weight → uniform routing
    #[test]
    fn test_zero_gate_uniform_routing() {
        let hidden_dim = 4;
        let num_experts = 8;
        let k = 4;
        let hidden_state = vec![1.0f32; hidden_dim];
        let gate_weight = vec![0.0f32; num_experts * hidden_dim];

        let result = moe_route(&hidden_state, &gate_weight, num_experts, k, hidden_dim);

        assert_eq!(result.indices.len(), k);
        // All weights should be equal (uniform)
        for &w in &result.weights {
            assert!((w - 0.25).abs() < 1e-6, "expected 0.25, got {w}");
        }
    }

    // FALSIFY-MOE-DISPATCH-002: Uniform routing = average of experts
    #[test]
    fn test_uniform_routing_averages_experts() {
        let hidden_dim = 4;
        let intermediate = 2;
        let num_experts = 4;
        let k = 4;

        // Create MoE weights where each expert is different
        let mut expert_gate_up = vec![0.1f32; num_experts * 2 * intermediate * hidden_dim];
        let expert_down = vec![0.1f32; num_experts * hidden_dim * intermediate];

        // Make expert 0 produce different output by scaling gate_up
        for i in 0..(2 * intermediate * hidden_dim) {
            expert_gate_up[0 * 2 * intermediate * hidden_dim + i] = 0.2;
        }

        let moe = MoeExpertWeights {
            gate_weight: vec![0.0f32; num_experts * hidden_dim], // uniform routing
            expert_gate_up,
            expert_down,
            shared_gate: vec![0.0f32; intermediate * hidden_dim], // zero shared
            shared_up: vec![0.0f32; intermediate * hidden_dim],
            shared_down: vec![0.0f32; hidden_dim * intermediate],
            shared_expert_gate_weight: vec![],
            num_experts,
            num_experts_per_tok: k,
            expert_intermediate: intermediate,
        };

        let x = vec![1.0f32; hidden_dim];
        let output = moe_forward_token(&x, &moe, hidden_dim);

        // Output should be finite
        for &v in &output {
            assert!(v.is_finite(), "output not finite: {v}");
        }
    }

    // FALSIFY-MOE-DISPATCH-004: Shared expert runs even with zero routing
    #[test]
    fn test_shared_expert_always_active() {
        let hidden_dim = 4;
        let intermediate = 2;
        let num_experts = 4;
        let k = 2;

        // All expert weights zero, shared expert non-zero
        let moe = MoeExpertWeights {
            gate_weight: vec![0.0f32; num_experts * hidden_dim],
            expert_gate_up: vec![0.0f32; num_experts * 2 * intermediate * hidden_dim],
            expert_down: vec![0.0f32; num_experts * hidden_dim * intermediate],
            shared_gate: vec![0.1f32; intermediate * hidden_dim],
            shared_up: vec![0.1f32; intermediate * hidden_dim],
            shared_down: vec![0.1f32; hidden_dim * intermediate],
            shared_expert_gate_weight: vec![],
            num_experts,
            num_experts_per_tok: k,
            expert_intermediate: intermediate,
        };

        let x = vec![1.0f32; hidden_dim];
        let output = moe_forward_token(&x, &moe, hidden_dim);

        // Output should be non-zero (from shared expert)
        let norm: f32 = output.iter().map(|v| v * v).sum();
        assert!(norm > 0.0, "shared expert output should be non-zero");
    }

    // FALSIFY-MOE-ROUTER-003: Renormalization preserves relative order
    #[test]
    fn test_renorm_preserves_order() {
        let hidden_dim = 4;
        let num_experts = 8;
        let k = 4;

        // Set up gate weights so experts have known ordering
        let mut gate_weight = vec![0.0f32; num_experts * hidden_dim];
        for e in 0..num_experts {
            for j in 0..hidden_dim {
                gate_weight[e * hidden_dim + j] = (num_experts - e) as f32;
            }
        }

        let hidden_state = vec![1.0f32; hidden_dim];
        let result = moe_route(&hidden_state, &gate_weight, num_experts, k, hidden_dim);

        // Weights should be in descending order
        for i in 1..k {
            assert!(
                result.weights[i - 1] >= result.weights[i],
                "weights not ordered: {} < {}",
                result.weights[i - 1],
                result.weights[i]
            );
        }
    }

    // FALSIFY-MOE-DISPATCH-005: Shared expert gate scales output via sigmoid
    #[test]
    fn test_shared_expert_gate_scales_output() {
        let hidden_dim = 4;
        let intermediate = 2;
        let num_experts = 4;
        let k = 2;

        // All routed expert weights zero, shared expert non-zero
        let base_moe = MoeExpertWeights {
            gate_weight: vec![0.0f32; num_experts * hidden_dim],
            expert_gate_up: vec![0.0f32; num_experts * 2 * intermediate * hidden_dim],
            expert_down: vec![0.0f32; num_experts * hidden_dim * intermediate],
            shared_gate: vec![0.1f32; intermediate * hidden_dim],
            shared_up: vec![0.1f32; intermediate * hidden_dim],
            shared_down: vec![0.1f32; hidden_dim * intermediate],
            shared_expert_gate_weight: vec![], // no gate
            num_experts,
            num_experts_per_tok: k,
            expert_intermediate: intermediate,
        };

        let x = vec![1.0f32; hidden_dim];
        let ungated = moe_forward_token(&x, &base_moe, hidden_dim);

        // Now with a large negative gate → sigmoid ≈ 0 → shared expert nearly suppressed
        let mut gated_moe = base_moe.clone();
        gated_moe.shared_expert_gate_weight = vec![-10.0f32; hidden_dim];
        let gated = moe_forward_token(&x, &gated_moe, hidden_dim);

        // Gated output should have much smaller shared component
        let ungated_norm: f32 = ungated.iter().map(|v| v * v).sum::<f32>().sqrt();
        let gated_norm: f32 = gated.iter().map(|v| v * v).sum::<f32>().sqrt();
        assert!(
            gated_norm < ungated_norm * 0.1,
            "shared expert gate should suppress output: ungated={ungated_norm}, gated={gated_norm}"
        );
    }

    // FALSIFY-MOE_EXPERT_DISPATCH_V1_001/002: output = sum_e weight[e] * expert_e(x)
    // over the routed experts only; weights of unrouted experts cannot change it.
    #[test]
    fn falsify_moe_expert_dispatch_isolation_and_weighted_sum() {
        let (hidden_dim, intermediate, num_experts, k) = (4usize, 2usize, 4usize, 2usize);
        let gu_len = 2 * intermediate * hidden_dim;
        let dn_len = hidden_dim * intermediate;
        let mut expert_gate_up = vec![0.0f32; num_experts * gu_len];
        let mut expert_down = vec![0.0f32; num_experts * dn_len];
        for e in 0..num_experts {
            for i in 0..gu_len {
                expert_gate_up[e * gu_len + i] = 0.05 * (e as f32 + 1.0) + 0.01 * i as f32;
            }
            for i in 0..dn_len {
                expert_down[e * dn_len + i] = 0.03 * (e as f32 + 1.0) - 0.01 * i as f32;
            }
        }
        // Experts 0 and 1 win the router (strictly higher logits than 2 and 3).
        let mut gate_weight = vec![0.0f32; num_experts * hidden_dim];
        for e in 0..num_experts {
            let logit = [2.0f32, 1.0, -1.0, -2.0][e];
            for j in 0..hidden_dim {
                gate_weight[e * hidden_dim + j] = logit;
            }
        }
        let moe = MoeExpertWeights {
            gate_weight: gate_weight.clone(),
            expert_gate_up: expert_gate_up.clone(),
            expert_down: expert_down.clone(),
            shared_gate: vec![0.0f32; intermediate * hidden_dim],
            shared_up: vec![0.0f32; intermediate * hidden_dim],
            shared_down: vec![0.0f32; hidden_dim * intermediate],
            shared_expert_gate_weight: vec![],
            num_experts,
            num_experts_per_tok: k,
            expert_intermediate: intermediate,
        };
        let x = vec![1.0f32, 0.5, -0.5, 2.0];
        let route = moe_route(&x, &gate_weight, num_experts, k, hidden_dim);
        let mut routed: Vec<usize> = route.indices.clone();
        routed.sort_unstable();
        assert_eq!(routed, vec![0, 1], "router must pick the two top experts");

        // Reference: the weighted sum over routed experts, computed independently.
        let mut expected = vec![0.0f32; hidden_dim];
        for (idx, &e) in route.indices.iter().enumerate() {
            let gu = &expert_gate_up[e * gu_len..(e + 1) * gu_len];
            let out = expert_swiglu(
                &x,
                &gu[..intermediate * hidden_dim],
                &gu[intermediate * hidden_dim..],
                &expert_down[e * dn_len..(e + 1) * dn_len],
                hidden_dim,
                intermediate,
            );
            for i in 0..hidden_dim {
                expected[i] += route.weights[idx] * out[i];
            }
        }
        let got = moe_forward_token(&x, &moe, hidden_dim);
        assert!(
            expected.iter().any(|v| v.abs() > 1e-6),
            "reference is non-trivial"
        );
        for i in 0..hidden_dim {
            assert!(
                (got[i] - expected[i]).abs() < 1e-6,
                "aggregate[{i}]: {} vs {}",
                got[i],
                expected[i]
            );
        }

        // Isolation: scrambling the unrouted experts leaves the output unchanged.
        let mut scrambled = moe.clone();
        for e in 2..num_experts {
            for v in &mut scrambled.expert_gate_up[e * gu_len..(e + 1) * gu_len] {
                *v = 100.0;
            }
            for v in &mut scrambled.expert_down[e * dn_len..(e + 1) * dn_len] {
                *v = -100.0;
            }
        }
        let after = moe_forward_token(&x, &scrambled, hidden_dim);
        assert_eq!(got, after, "unrouted experts must not affect the output");
    }
}