entrenar 0.7.9

Training & Optimization library with autograd, LoRA, quantization, and model merging
Documentation
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
#![allow(unsafe_code)]
#![allow(trivial_casts)]
#![allow(clippy::borrow_as_ptr)]
#![allow(clippy::ref_as_ptr)]

#[cfg(feature = "cuda")]
use trueno_gpu::driver::{CudaStream, GpuBuffer, LaunchConfig};
#[cfg(feature = "cuda")]
use trueno_gpu::kernels::{
    BatchedToInterleavedKernel, BatchedTransposeKernel, ElementwiseMulKernel,
    InterleavedToBatchedKernel, Kernel, ResidualAddKernel, ScaleKernel,
};

use crate::autograd::cuda_tensor::{CudaTensorError, Result};

#[cfg(feature = "cuda")]
use super::cache::FORWARD_KERNEL_CACHE;

/// Residual addition forward pass on GPU
///
/// Computes: output[i] = a[i] + b[i] for i in [0, n)
///
/// # Contract (C-RESADD-001)
///
/// - **Precondition**: a.len() == b.len() == output.len() >= n, n > 0
/// - **Postcondition**: output[i] == a[i] + b[i] for all i in [0, n)
/// - **Invariant**: Zero CPU-side data transfers (no gpu_to_vec / vec_to_gpu)
#[cfg(feature = "cuda")]
pub fn residual_add_forward(
    a: &GpuBuffer<f32>,
    b: &GpuBuffer<f32>,
    output: &mut GpuBuffer<f32>,
    n: u32,
    stream: &CudaStream,
) -> Result<()> {
    let cache = FORWARD_KERNEL_CACHE.get().ok_or(CudaTensorError::DeviceNotInitialized)?;
    let mut cache = cache.lock().map_err(|_err| {
        CudaTensorError::KernelError("Failed to acquire kernel cache lock".to_string())
    })?;

    let key = "residual_add_forward".to_string(); // PTX is n-independent (trueno#184)
    let module = match cache.get_cached(&key) {
        Some(m) => m,
        None => {
            let kernel = ResidualAddKernel::new(n);
            let ptx = kernel.emit_ptx_for_target(cache.sm_target());
            cache.get_or_compile(&key, &ptx)?
        }
    };

    let config = LaunchConfig { grid: (n.div_ceil(256), 1, 1), block: (256, 1, 1), shared_mem: 0 };

    let a_ptr = a.as_ptr();
    let b_ptr = b.as_ptr();
    let output_ptr = output.as_ptr();

    let mut args: [*mut std::ffi::c_void; 4] = [
        &a_ptr as *const _ as *mut _,
        &b_ptr as *const _ as *mut _,
        &output_ptr as *const _ as *mut _,
        &n as *const _ as *mut _,
    ];

    // SAFETY: Kernel launch requires FFI. All buffers are valid GPU allocations with
    // matching sizes, and the kernel parameters match the expected PTX signature.
    unsafe {
        stream.launch_kernel(module, "residual_add", &config, &mut args).map_err(|e| {
            CudaTensorError::KernelError(format!("Residual add forward launch failed: {e:?}"))
        })?;
    }

    Ok(())
}

/// In-place GPU buffer addition: dst[i] += src[i]
///
/// # Contract (C-IPADD-001)
///
/// - **Precondition**: dst.len() >= n, src.len() >= n, n > 0
/// - **Postcondition**: dst[i] == old_dst[i] + src[i] for all i in [0, n)
/// - **Invariant**: Zero CPU-side data transfers, zero stream synchronization
#[cfg(feature = "cuda")]
pub fn inplace_add_gpu(
    dst: &mut GpuBuffer<f32>,
    src: &GpuBuffer<f32>,
    n: u32,
    stream: &CudaStream,
) -> Result<()> {
    let cache = FORWARD_KERNEL_CACHE.get().ok_or(CudaTensorError::DeviceNotInitialized)?;
    let mut cache = cache.lock().map_err(|_err| {
        CudaTensorError::KernelError("Failed to acquire kernel cache lock".to_string())
    })?;

    let key = "inplace_add".to_string(); // PTX is n-independent (trueno#184)
    let module = match cache.get_cached(&key) {
        Some(m) => m,
        None => {
            let kernel = ResidualAddKernel::new(n);
            let ptx = kernel.emit_ptx_for_target(cache.sm_target());
            cache.get_or_compile(&key, &ptx)?
        }
    };

    let config = LaunchConfig { grid: (n.div_ceil(256), 1, 1), block: (256, 1, 1), shared_mem: 0 };

    // Use dst pointer for both input `a` and `output` — in-place accumulation.
    // SAFETY: ResidualAddKernel computes output[i] = a[i] + b[i] per thread.
    // With a == output (aliased), each thread reads dst[i], adds src[i], writes dst[i].
    // No inter-thread data dependency — safe for in-place operation.
    let dst_ptr = dst.as_ptr();
    let src_ptr = src.as_ptr();

    let mut args: [*mut std::ffi::c_void; 4] = [
        &dst_ptr as *const _ as *mut _,
        &src_ptr as *const _ as *mut _,
        &dst_ptr as *const _ as *mut _,
        &n as *const _ as *mut _,
    ];

    // SAFETY: kernel launch with pre-validated device pointers and grid config;
    // both src and dst are valid CudaTensor buffers with length >= n elements.
    unsafe {
        stream.launch_kernel(module, "residual_add", &config, &mut args).map_err(|e| {
            CudaTensorError::KernelError(format!("In-place add launch failed: {e:?}"))
        })?;
    }

    Ok(())
}

/// Element-wise multiplication forward pass on GPU
///
/// Computes: output[i] = a[i] * b[i] for i in [0, n)
///
/// # Contract (C-ELMUL-001)
///
/// - **Precondition**: a.len() == b.len() == output.len() >= n, n > 0
/// - **Postcondition**: output[i] == a[i] * b[i] for all i in [0, n)
/// - **Invariant**: Zero CPU-side data transfers
#[cfg(feature = "cuda")]
pub fn elementwise_mul_forward(
    a: &GpuBuffer<f32>,
    b: &GpuBuffer<f32>,
    output: &mut GpuBuffer<f32>,
    n: u32,
    stream: &CudaStream,
) -> Result<()> {
    let cache = FORWARD_KERNEL_CACHE.get().ok_or(CudaTensorError::DeviceNotInitialized)?;
    let mut cache = cache.lock().map_err(|_err| {
        CudaTensorError::KernelError("Failed to acquire kernel cache lock".to_string())
    })?;

    let key = "elementwise_mul_forward".to_string(); // PTX is n-independent (trueno#184)
    let module = match cache.get_cached(&key) {
        Some(m) => m,
        None => {
            let kernel = ElementwiseMulKernel::new(n);
            let ptx = kernel.emit_ptx_for_target(cache.sm_target());
            cache.get_or_compile(&key, &ptx)?
        }
    };

    let config = LaunchConfig { grid: (n.div_ceil(256), 1, 1), block: (256, 1, 1), shared_mem: 0 };

    let a_ptr = a.as_ptr();
    let b_ptr = b.as_ptr();
    let output_ptr = output.as_ptr();

    let mut args: [*mut std::ffi::c_void; 4] = [
        &a_ptr as *const _ as *mut _,
        &b_ptr as *const _ as *mut _,
        &output_ptr as *const _ as *mut _,
        &n as *const _ as *mut _,
    ];

    // SAFETY: Kernel launch requires FFI. All buffers are valid GPU allocations with
    // matching sizes, and the kernel parameters match the expected PTX signature.
    unsafe {
        stream.launch_kernel(module, "elementwise_mul", &config, &mut args).map_err(|e| {
            CudaTensorError::KernelError(format!("Elementwise mul forward launch failed: {e:?}"))
        })?;
    }

    Ok(())
}

/// Scale forward pass on GPU
///
/// Computes: output[i] = input[i] * scale for i in [0, n)
///
/// # Contract (C-SCALE-001)
///
/// - **Precondition**: input.len() == output.len() >= n, n > 0
/// - **Postcondition**: output[i] == input[i] * scale for all i in [0, n)
/// - **Invariant**: Zero CPU-side data transfers; in-place aliasing allowed (output may == input)
#[cfg(feature = "cuda")]
pub fn scale_forward(
    input: &GpuBuffer<f32>,
    output: &mut GpuBuffer<f32>,
    scale: f32,
    n: u32,
    stream: &CudaStream,
) -> Result<()> {
    let cache = FORWARD_KERNEL_CACHE.get().ok_or(CudaTensorError::DeviceNotInitialized)?;
    let mut cache = cache.lock().map_err(|_err| {
        CudaTensorError::KernelError("Failed to acquire kernel cache lock".to_string())
    })?;

    let key = "scale_forward".to_string(); // PTX is n-independent (trueno#184)
    let module = match cache.get_cached(&key) {
        Some(m) => m,
        None => {
            let kernel = ScaleKernel::new(n);
            let ptx = kernel.emit_ptx_for_target(cache.sm_target());
            cache.get_or_compile(&key, &ptx)?
        }
    };

    let config = LaunchConfig { grid: (n.div_ceil(256), 1, 1), block: (256, 1, 1), shared_mem: 0 };

    let input_ptr = input.as_ptr();
    let output_ptr = output.as_ptr();

    let mut args: [*mut std::ffi::c_void; 4] = [
        &input_ptr as *const _ as *mut _,
        &output_ptr as *const _ as *mut _,
        &scale as *const _ as *mut _,
        &n as *const _ as *mut _,
    ];

    // SAFETY: Kernel launch requires FFI. All buffers are valid GPU allocations with
    // matching sizes, and the kernel parameters match the expected PTX signature.
    unsafe {
        stream.launch_kernel(module, "scale", &config, &mut args).map_err(|e| {
            CudaTensorError::KernelError(format!("Scale forward launch failed: {e:?}"))
        })?;
    }

    Ok(())
}

/// Convert interleaved to batched layout on GPU
///
/// Transforms: [seq_len, n_heads * head_dim] → [n_heads, seq_len, head_dim]
///
/// Used to prepare Q/K/V for batched multi-head attention GEMM.
///
/// # Contract (C-I2B-001)
///
/// - **Precondition**: input.len() >= seq_len * n_heads * head_dim, output.len() >= same
/// - **Postcondition**: output[h, s, d] = input[s, h * head_dim + d]
/// - **Invariant**: Zero CPU-side data transfers; total element count preserved
#[cfg(feature = "cuda")]
pub fn interleaved_to_batched_forward(
    input: &GpuBuffer<f32>,
    output: &mut GpuBuffer<f32>,
    seq_len: u32,
    n_heads: u32,
    head_dim: u32,
    stream: &CudaStream,
) -> Result<()> {
    let cache = FORWARD_KERNEL_CACHE.get().ok_or(CudaTensorError::DeviceNotInitialized)?;
    let mut cache = cache.lock().map_err(|_err| {
        CudaTensorError::KernelError("Failed to acquire kernel cache lock".to_string())
    })?;

    let total = seq_len * n_heads * head_dim;
    // Contract: dimension-independent-kernels-v1.yaml (FALSIFY-DIM-004)
    // Use generic cache key — PTX is dimension-independent, one module handles all dims.
    let key = "interleaved_to_batched";
    let module = match cache.get_cached(key) {
        Some(m) => m,
        None => {
            // Constructor args don't matter — PTX is identical for any dimensions
            let kernel = InterleavedToBatchedKernel::new(seq_len, n_heads, head_dim);
            let ptx = kernel.emit_ptx_for_target(cache.sm_target());
            cache.get_or_compile(key, &ptx)?
        }
    };

    let config =
        LaunchConfig { grid: (total.div_ceil(256), 1, 1), block: (256, 1, 1), shared_mem: 0 };

    let input_ptr = input.as_ptr();
    let output_ptr = output.as_ptr();

    // Dimension-independent kernel: pass dims as runtime params
    let mut args: [*mut std::ffi::c_void; 6] = [
        &input_ptr as *const _ as *mut _,
        &output_ptr as *const _ as *mut _,
        &seq_len as *const _ as *mut _,
        &n_heads as *const _ as *mut _,
        &head_dim as *const _ as *mut _,
        &total as *const _ as *mut _,
    ];

    // SAFETY: Kernel launch requires FFI. All buffers are valid GPU allocations.
    unsafe {
        stream.launch_kernel(module, "interleaved_to_batched", &config, &mut args).map_err(
            |e| {
                CudaTensorError::KernelError(format!("Interleaved-to-batched launch failed: {e:?}"))
            },
        )?;
    }

    Ok(())
}

/// Batched transpose on GPU
///
/// Transforms: [batch, rows, cols] → [batch, cols, rows]
///
/// Used for K^T in attention: [n_heads, seq_len, head_dim] → [n_heads, head_dim, seq_len]
///
/// # Contract (C-BTRANS-001)
///
/// - **Precondition**: input.len() >= batch * rows * cols, output.len() >= same
/// - **Postcondition**: output[b, j, i] = input[b, i, j]
/// - **Invariant**: Zero CPU-side data transfers; total element count preserved
#[cfg(feature = "cuda")]
pub fn batched_transpose_forward(
    input: &GpuBuffer<f32>,
    output: &mut GpuBuffer<f32>,
    batch: u32,
    rows: u32,
    cols: u32,
    stream: &CudaStream,
) -> Result<()> {
    let cache = FORWARD_KERNEL_CACHE.get().ok_or(CudaTensorError::DeviceNotInitialized)?;
    let mut cache = cache.lock().map_err(|_err| {
        CudaTensorError::KernelError("Failed to acquire kernel cache lock".to_string())
    })?;

    let total_per_batch = rows * cols;
    // Contract: dimension-independent-kernels-v1.yaml (FALSIFY-DIM-004)
    let key = "batched_transpose";
    let module = match cache.get_cached(key) {
        Some(m) => m,
        None => {
            let kernel = BatchedTransposeKernel::new(batch, rows, cols);
            let ptx = kernel.emit_ptx_for_target(cache.sm_target());
            cache.get_or_compile(key, &ptx)?
        }
    };

    // Grid: (ceil(total_per_batch/256), 1, batch)
    let config = LaunchConfig {
        grid: (total_per_batch.div_ceil(256), 1, batch),
        block: (256, 1, 1),
        shared_mem: 0,
    };

    let input_ptr = input.as_ptr();
    let output_ptr = output.as_ptr();

    // Dimension-independent kernel: pass dims as runtime params
    let mut args: [*mut std::ffi::c_void; 6] = [
        &input_ptr as *const _ as *mut _,
        &output_ptr as *const _ as *mut _,
        &batch as *const _ as *mut _,
        &rows as *const _ as *mut _,
        &cols as *const _ as *mut _,
        &total_per_batch as *const _ as *mut _,
    ];

    // SAFETY: Kernel launch requires FFI. All buffers are valid GPU allocations.
    unsafe {
        stream.launch_kernel(module, "batched_transpose", &config, &mut args).map_err(|e| {
            CudaTensorError::KernelError(format!("Batched transpose launch failed: {e:?}"))
        })?;
    }

    Ok(())
}

/// Convert batched to interleaved layout on GPU
///
/// Transforms: [n_heads, seq_len, head_dim] → [seq_len, n_heads * head_dim]
///
/// Used to convert attention output back to interleaved layout for output projection.
///
/// # Contract (C-B2I-001)
///
/// - **Precondition**: input.len() >= n_heads * seq_len * head_dim, output.len() >= same
/// - **Postcondition**: output[s, h * head_dim + d] = input[h, s, d]
/// - **Invariant**: Zero CPU-side data transfers; total element count preserved
#[cfg(feature = "cuda")]
pub fn batched_to_interleaved_forward(
    input: &GpuBuffer<f32>,
    output: &mut GpuBuffer<f32>,
    seq_len: u32,
    n_heads: u32,
    head_dim: u32,
    stream: &CudaStream,
) -> Result<()> {
    let cache = FORWARD_KERNEL_CACHE.get().ok_or(CudaTensorError::DeviceNotInitialized)?;
    let mut cache = cache.lock().map_err(|_err| {
        CudaTensorError::KernelError("Failed to acquire kernel cache lock".to_string())
    })?;

    let total = seq_len * n_heads * head_dim;
    // Contract: dimension-independent-kernels-v1.yaml (FALSIFY-DIM-004)
    let key = "batched_to_interleaved";
    let module = match cache.get_cached(key) {
        Some(m) => m,
        None => {
            let kernel = BatchedToInterleavedKernel::new(seq_len, n_heads, head_dim);
            let ptx = kernel.emit_ptx_for_target(cache.sm_target());
            cache.get_or_compile(key, &ptx)?
        }
    };

    let config =
        LaunchConfig { grid: (total.div_ceil(256), 1, 1), block: (256, 1, 1), shared_mem: 0 };

    let input_ptr = input.as_ptr();
    let output_ptr = output.as_ptr();

    // Dimension-independent kernel: pass dims as runtime params
    let mut args: [*mut std::ffi::c_void; 6] = [
        &input_ptr as *const _ as *mut _,
        &output_ptr as *const _ as *mut _,
        &seq_len as *const _ as *mut _,
        &n_heads as *const _ as *mut _,
        &head_dim as *const _ as *mut _,
        &total as *const _ as *mut _,
    ];

    // SAFETY: Kernel launch requires FFI. All buffers are valid GPU allocations.
    unsafe {
        stream.launch_kernel(module, "batched_to_interleaved", &config, &mut args).map_err(
            |e| {
                CudaTensorError::KernelError(format!("Batched-to-interleaved launch failed: {e:?}"))
            },
        )?;
    }

    Ok(())
}

/// Expand KV heads for grouped-query attention (GQA) on GPU
///
/// Replicates each KV head `heads_per_kv` times using D2D copies.
/// Transforms: [num_kv_heads, seq_len, head_dim] → [num_heads, seq_len, head_dim]
///
/// # Contract (C-GQAEXP-001)
///
/// - **Precondition**: src has at least num_kv_heads * elems_per_head elements,
///   dst has at least num_kv_heads * heads_per_kv * elems_per_head elements
/// - **Postcondition**: dst[h, :, :] = src[h / heads_per_kv, :, :] for all h in [0, num_heads)
/// - **Invariant**: Zero CPU-side data transfers (D2D only)
#[cfg(feature = "cuda")]
pub fn expand_kv_heads(
    src: &GpuBuffer<f32>,
    dst: &mut GpuBuffer<f32>,
    num_kv_heads: usize,
    heads_per_kv: usize,
    elems_per_head: usize,
    stream: &CudaStream,
) -> Result<()> {
    for kv_h in 0..num_kv_heads {
        let src_offset = kv_h * elems_per_head;
        for rep in 0..heads_per_kv {
            let dst_offset = (kv_h * heads_per_kv + rep) * elems_per_head;
            // SAFETY: Both buffers are valid GPU allocations with sufficient size.
            // The async D2D copy is ordered on the stream with prior kernel launches.
            unsafe {
                dst.copy_from_buffer_at_async(src, dst_offset, src_offset, elems_per_head, stream)
                    .map_err(|e| {
                        CudaTensorError::TransferFailed(format!(
                            "GQA head expansion D2D copy failed: {e}"
                        ))
                    })?;
            }
        }
    }
    Ok(())
}