realizar 0.8.6

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
impl GpuModelQ4 {
    /// Execute forward pass using Q4_0 kernels
    ///
    /// # Arguments
    ///
    /// * `executor` - CUDA executor with cached weights
    /// * `token_ids` - Input token IDs
    ///
    /// # Returns
    ///
    /// Logits for next token prediction
    #[cfg(feature = "cuda")]
    pub fn forward(&self, executor: &mut CudaExecutor, token_ids: &[usize]) -> Result<Vec<f32>> {
        let hidden_dim = self.config.hidden_dim;
        let vocab_size = self.config.vocab_size;

        // 1. Embed tokens (CPU - fast lookup)
        let seq_len = token_ids.len();
        let mut hidden = Vec::with_capacity(seq_len * hidden_dim);
        for &token_id in token_ids {
            let start = token_id * hidden_dim;
            let end = start + hidden_dim;
            if end <= self.token_embedding.len() {
                hidden.extend_from_slice(&self.token_embedding[start..end]);
            } else {
                // Out of vocab, use zeros
                hidden.extend(std::iter::repeat_n(0.0, hidden_dim));
            }
        }

        // 2. Upload hidden state to GPU
        let mut hidden_gpu = GpuBuffer::from_host(executor.context(), &hidden).map_err(|e| {
            RealizarError::GpuError {
                reason: format!("Failed to upload hidden: {e}"),
            }
        })?;

        // 3. Pass through transformer layers
        for layer_idx in 0..self.num_layers {
            hidden_gpu = self.forward_layer(executor, &hidden_gpu, layer_idx, seq_len)?;
        }

        // 4. Final layer norm (GPU)
        // PAR-023: Use cached gamma pointer to avoid CPU roundtrip
        let (output_gamma_ptr, output_gamma_len) = executor
            .get_rmsnorm_gamma_ptr("apr.output_norm")
            .ok_or_else(|| RealizarError::GpuError {
                reason: "apr.output_norm not cached on GPU".to_string(),
            })?;

        let normed_gpu = executor
            .rmsnorm_gpu_ptr(
                &hidden_gpu,
                output_gamma_ptr,
                output_gamma_len,
                hidden_dim as u32,
                self.config.eps,
            )
            .map_err(|e| RealizarError::GpuError {
                reason: format!("Output RMSNorm failed: {e}"),
            })?;

        // 5. LM head projection (GPU, Q4_0)

        let logits_gpu = GpuBuffer::new(executor.context(), vocab_size).map_err(|e| {
            RealizarError::GpuError {
                reason: format!("Failed to allocate logits: {e}"),
            }
        })?;

        let lm_head_ptr =
            executor
                .get_quantized_weight_ptr("lm_head")
                .map_err(|e| RealizarError::GpuError {
                    reason: format!("lm_head not cached: {e}"),
                })?;

        executor
            .q4_0_gemv_into(
                lm_head_ptr,
                &normed_gpu,
                &logits_gpu,
                vocab_size as u32,
                hidden_dim as u32,
            )
            .map_err(|e| RealizarError::GpuError {
                reason: format!("LM head GEMV failed: {e}"),
            })?;

        // 6. Sync and return
        executor
            .synchronize()
            .map_err(|e| RealizarError::GpuError {
                reason: format!("Sync failed: {e}"),
            })?;

        gpu_to_host(&logits_gpu)
    }

    /// Execute single transformer layer
    #[cfg(feature = "cuda")]
    fn forward_layer(
        &self,
        executor: &mut CudaExecutor,
        input: &GpuBuffer<f32>,
        layer_idx: usize,
        seq_len: usize,
    ) -> Result<GpuBuffer<f32>> {
        let hidden_dim = self.config.hidden_dim;
        let num_heads = self.config.num_heads;
        let num_kv_heads = self.config.num_kv_heads;
        // GH-479: Use explicit_head_dim if set (Qwen3 head_dim != hidden/heads)
        let head_dim = self.config.explicit_head_dim.unwrap_or(hidden_dim / num_heads);
        let kv_dim = num_kv_heads * head_dim;
        let qkv_dim = hidden_dim + 2 * kv_dim;

        // 1. Pre-attention RMSNorm (GPU)
        // PAR-023: Use cached gamma pointer to avoid CPU roundtrip
        let attn_norm_name = format!("apr.layer_{layer_idx}.attn_norm");
        let (attn_gamma_ptr, attn_gamma_len) = executor
            .get_rmsnorm_gamma_ptr(&attn_norm_name)
            .ok_or_else(|| RealizarError::GpuError {
                reason: format!("{attn_norm_name} not cached on GPU"),
            })?;

        let normed_gpu = executor
            .rmsnorm_gpu_ptr(
                input,
                attn_gamma_ptr,
                attn_gamma_len,
                hidden_dim as u32,
                self.config.eps,
            )
            .map_err(|e| RealizarError::GpuError {
                reason: format!("Attention RMSNorm failed: {e}"),
            })?;

        // 3. QKV projection (Q4_0)
        let qkv_gpu =
            GpuBuffer::new(executor.context(), qkv_dim).map_err(|e| RealizarError::GpuError {
                reason: format!("Failed to allocate QKV: {e}"),
            })?;

        let qkv_name = format!("layer_{layer_idx}.attn.qkv");
        let qkv_ptr =
            executor
                .get_quantized_weight_ptr(&qkv_name)
                .map_err(|e| RealizarError::GpuError {
                    reason: format!("{qkv_name} not cached: {e}"),
                })?;

        executor
            .q4_0_gemv_into(
                qkv_ptr,
                &normed_gpu,
                &qkv_gpu,
                qkv_dim as u32,
                hidden_dim as u32,
            )
            .map_err(|e| RealizarError::GpuError {
                reason: format!("QKV GEMV failed: {e}"),
            })?;

        // 4. Attention (CPU for single-token - GPU launch overhead exceeds benefit)
        let qkv = gpu_to_host(&qkv_gpu)?;

        // Apply RoPE to Q and K before attention
        // For seq_len tokens at layer 0, positions are [0, 1, 2, ... seq_len-1]
        let mut qkv_with_rope = qkv.clone();
        self.apply_rope_to_qkv(
            &mut qkv_with_rope,
            seq_len,
            hidden_dim,
            num_heads,
            num_kv_heads,
        );

        let attn_out =
            self.attention_cpu(&qkv_with_rope, seq_len, hidden_dim, num_heads, num_kv_heads);

        // 5. Output projection (Q4_0)
        let attn_out_gpu = GpuBuffer::from_host(executor.context(), &attn_out).map_err(|e| {
            RealizarError::GpuError {
                reason: format!("Failed to upload attn_out: {e}"),
            }
        })?;

        let out_gpu = GpuBuffer::new(executor.context(), hidden_dim).map_err(|e| {
            RealizarError::GpuError {
                reason: format!("Failed to allocate out: {e}"),
            }
        })?;

        let out_name = format!("layer_{layer_idx}.attn.out");
        let out_ptr =
            executor
                .get_quantized_weight_ptr(&out_name)
                .map_err(|e| RealizarError::GpuError {
                    reason: format!("{out_name} not cached: {e}"),
                })?;

        executor
            .q4_0_gemv_into(
                out_ptr,
                &attn_out_gpu,
                &out_gpu,
                hidden_dim as u32,
                hidden_dim as u32,
            )
            .map_err(|e| RealizarError::GpuError {
                reason: format!("Out GEMV failed: {e}"),
            })?;

        // 6. Residual connection (GPU)
        // PAR-023: Keep data on GPU to avoid roundtrip
        let residual1 = executor
            .residual_add_gpu(input, &out_gpu, hidden_dim as u32)
            .map_err(|e| RealizarError::GpuError {
                reason: format!("Residual add failed: {e}"),
            })?;

        // 7. FFN norm (GPU)
        let ffn_norm_name = format!("apr.layer_{layer_idx}.ffn_norm");
        let (ffn_gamma_ptr, ffn_gamma_len) = executor
            .get_rmsnorm_gamma_ptr(&ffn_norm_name)
            .ok_or_else(|| RealizarError::GpuError {
                reason: format!("{ffn_norm_name} not cached on GPU"),
            })?;

        let ffn_input_gpu = executor
            .rmsnorm_gpu_ptr(
                &residual1,
                ffn_gamma_ptr,
                ffn_gamma_len,
                hidden_dim as u32,
                self.config.eps,
            )
            .map_err(|e| RealizarError::GpuError {
                reason: format!("FFN RMSNorm failed: {e}"),
            })?;

        // 8. FFN (GPU, Q4_0)

        let ffn_out = if self.has_gate {
            // SwiGLU: gate * up * silu
            self.ffn_swiglu_gpu(executor, &ffn_input_gpu, layer_idx)?
        } else {
            // Standard FFN: up -> activation -> down
            self.ffn_standard_gpu(executor, &ffn_input_gpu, layer_idx)?
        };

        // 9. Final residual (GPU)
        // PAR-023: Keep data on GPU - residual1 + ffn_out
        executor
            .residual_add_gpu(&residual1, &ffn_out, hidden_dim as u32)
            .map_err(|e| RealizarError::GpuError {
                reason: format!("Final residual add failed: {e}"),
            })
    }

    /// SwiGLU FFN using Q4_0 kernels
    #[cfg(feature = "cuda")]
    fn ffn_swiglu_gpu(
        &self,
        executor: &mut CudaExecutor,
        input: &GpuBuffer<f32>,
        layer_idx: usize,
    ) -> Result<GpuBuffer<f32>> {
        let hidden_dim = self.config.hidden_dim;
        let intermediate_dim = self.config.intermediate_dim;

        // Gate projection
        let gate_gpu = GpuBuffer::new(executor.context(), intermediate_dim).map_err(|e| {
            RealizarError::GpuError {
                reason: format!("Failed to allocate gate: {e}"),
            }
        })?;

        let gate_name = format!("layer_{layer_idx}.ffn.gate");
        let gate_ptr =
            executor
                .get_quantized_weight_ptr(&gate_name)
                .map_err(|e| RealizarError::GpuError {
                    reason: format!("{gate_name} not cached: {e}"),
                })?;

        executor
            .q4_0_gemv_into(
                gate_ptr,
                input,
                &gate_gpu,
                intermediate_dim as u32,
                hidden_dim as u32,
            )
            .map_err(|e| RealizarError::GpuError {
                reason: format!("Gate GEMV failed: {e}"),
            })?;

        // Up projection
        let up_gpu = GpuBuffer::new(executor.context(), intermediate_dim).map_err(|e| {
            RealizarError::GpuError {
                reason: format!("Failed to allocate up: {e}"),
            }
        })?;

        let up_name = format!("layer_{layer_idx}.ffn.up");
        let up_ptr =
            executor
                .get_quantized_weight_ptr(&up_name)
                .map_err(|e| RealizarError::GpuError {
                    reason: format!("{up_name} not cached: {e}"),
                })?;

        executor
            .q4_0_gemv_into(
                up_ptr,
                input,
                &up_gpu,
                intermediate_dim as u32,
                hidden_dim as u32,
            )
            .map_err(|e| RealizarError::GpuError {
                reason: format!("Up GEMV failed: {e}"),
            })?;

        // SwiGLU activation (GPU - fused kernel PAR-023)
        // Eliminates 2x GPU→CPU transfers + CPU compute + 1x CPU→GPU transfer
        let activated_gpu = executor
            .fused_swiglu_gpu(&gate_gpu, &up_gpu, intermediate_dim as u32)
            .map_err(|e| RealizarError::GpuError {
                reason: format!("Fused SwiGLU failed: {e}"),
            })?;

        let down_gpu = GpuBuffer::new(executor.context(), hidden_dim).map_err(|e| {
            RealizarError::GpuError {
                reason: format!("Failed to allocate down: {e}"),
            }
        })?;

        let down_name = format!("layer_{layer_idx}.ffn.down");
        let down_ptr =
            executor
                .get_quantized_weight_ptr(&down_name)
                .map_err(|e| RealizarError::GpuError {
                    reason: format!("{down_name} not cached: {e}"),
                })?;

        executor
            .q4_0_gemv_into(
                down_ptr,
                &activated_gpu,
                &down_gpu,
                hidden_dim as u32,
                intermediate_dim as u32,
            )
            .map_err(|e| RealizarError::GpuError {
                reason: format!("Down GEMV failed: {e}"),
            })?;

        Ok(down_gpu)
    }

    /// Standard FFN (GELU) using Q4_0 kernels
    #[cfg(feature = "cuda")]
    fn ffn_standard_gpu(
        &self,
        executor: &mut CudaExecutor,
        input: &GpuBuffer<f32>,
        layer_idx: usize,
    ) -> Result<GpuBuffer<f32>> {
        let hidden_dim = self.config.hidden_dim;
        let intermediate_dim = self.config.intermediate_dim;

        // Up projection
        let up_gpu = GpuBuffer::new(executor.context(), intermediate_dim).map_err(|e| {
            RealizarError::GpuError {
                reason: format!("Failed to allocate up: {e}"),
            }
        })?;

        let up_name = format!("layer_{layer_idx}.ffn.up");
        let up_ptr =
            executor
                .get_quantized_weight_ptr(&up_name)
                .map_err(|e| RealizarError::GpuError {
                    reason: format!("{up_name} not cached: {e}"),
                })?;

        executor
            .q4_0_gemv_into(
                up_ptr,
                input,
                &up_gpu,
                intermediate_dim as u32,
                hidden_dim as u32,
            )
            .map_err(|e| RealizarError::GpuError {
                reason: format!("Up GEMV failed: {e}"),
            })?;

        // GELU activation (GPU - in place)
        // Eliminates 2x PCIe transfers (GPU→CPU download + CPU→GPU upload)
        executor
            .gelu_gpu(&up_gpu, intermediate_dim as u32)
            .map_err(|e| RealizarError::GpuError {
                reason: format!("GELU GPU failed: {e}"),
            })?;

        let down_gpu = GpuBuffer::new(executor.context(), hidden_dim).map_err(|e| {
            RealizarError::GpuError {
                reason: format!("Failed to allocate down: {e}"),
            }
        })?;

        let down_name = format!("layer_{layer_idx}.ffn.down");
        let down_ptr =
            executor
                .get_quantized_weight_ptr(&down_name)
                .map_err(|e| RealizarError::GpuError {
                    reason: format!("{down_name} not cached: {e}"),
                })?;

        executor
            .q4_0_gemv_into(
                down_ptr,
                &up_gpu, // up_gpu now contains GELU-activated values (in-place)
                &down_gpu,
                hidden_dim as u32,
                intermediate_dim as u32,
            )
            .map_err(|e| RealizarError::GpuError {
                reason: format!("Down GEMV failed: {e}"),
            })?;

        Ok(down_gpu)
    }

    /// RMSNorm in place
    pub(crate) fn rms_norm_inplace(&self, x: &mut [f32], weight: &[f32]) {
        let eps = self.config.eps;
        let n = x.len();

        // Calculate RMS
        let sum_sq: f32 = x.iter().map(|&v| v * v).sum();
        let rms = (sum_sq / n as f32 + eps).sqrt();
        let scale = 1.0 / rms;

        // Normalize and apply weight
        for (i, v) in x.iter_mut().enumerate() {
            *v = *v * scale * weight.get(i).copied().unwrap_or(1.0);
        }
    }
}