lumen-core 0.6.1

A tiny ML framework
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
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
use std::sync::{Arc, RwLock};
use rand::rng;
use rand_distr::{Distribution, Uniform};
use crate::{Error, IntDType, Result};
use crate::{DType, FloatDType, Layout, NumDType, Shape, WithDType};

#[derive(Clone)]
pub struct Storage<T>(Vec<T>);

impl<T: WithDType> Storage<T> {
    pub fn zeros(shape: &Shape) -> Self {
        Self(vec![T::ZERO; shape.element_count()])
    }

    pub fn ones(shape: &Shape) -> Self {
        Self(vec![T::ONE; shape.element_count()])
    }

    pub fn full(value: T, shape: &Shape) -> Self {
        Self(vec![value; shape.element_count()])
    }

    pub fn new<D: Into<Vec<T>>>(data: D) -> Self {
        Self(data.into())
    }

    #[inline]
    pub fn data(&self) -> &[T] {
        &self.0
    }

    #[inline]
    pub fn data_mut(&mut self) -> &mut [T] {
        &mut self.0
    }

    #[inline]
    pub fn dtype(&self) -> DType {
        T::DTYPE
    }

    #[inline]
    pub fn copy_data(&self) -> Vec<T> {
        self.0.clone()
    }

    #[inline]
    pub fn get(&self, index: usize) -> Option<T> {
        self.0.get(index).copied()
    }

    #[inline]
    pub fn get_unchecked(&self, index: usize) -> T {
        self.0[index]
    }

    #[inline]
    pub fn set(&mut self, index: usize, value: T) -> Option<()> {
        if index >= self.len() {
            None
        } else {
            self.0[index] = value;
            Some(())
        }
    }

    #[inline]
    pub fn set_unchecked(&mut self, index: usize, value: T) {
        self.0[index] = value;
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn copy(&self, layout: &Layout) -> Self {
        let output: Vec<_> = layout.storage_indices()
            .map(|i| self.0[i])
            .collect();
        Self(output)
    }

    pub fn copy_map<F, U>(&self, layout: &Layout, f: F) -> Storage<U> 
    where 
        U: WithDType,
        F: Fn(T) -> U
    {
        let output: Vec<_> = layout.storage_indices()
            .map(|i| f(self.0[i]))
            .collect();
        Storage(output)
    }
}

impl<T: NumDType> Storage<T> {
    pub fn rand_uniform(shape: &Shape, min: T, max: T) -> Result<Self> {
        let elem_count = shape.element_count();
        let mut rng = rng();
        let uniform = Uniform::new(min, max).map_err(|e| Error::Rand(e.to_string()))?;
        let v: Vec<T> = (0..elem_count)
            .map(|_| uniform.sample(&mut rng))
            .collect();

        Ok(Self(v))
    }
}

impl<F: FloatDType> Storage<F> {
    pub fn rand_normal(shape: &Shape, mean: F, std: F) -> Result<Self> 
    {
        let elem_count = shape.element_count();
        let v = F::random_normal_vec(elem_count, mean, std)?;
        Ok(Self(v))
    }
}

impl<T: WithDType> Storage<T> {
    pub(crate) fn index_select<I: IntDType>(
        &self,
        self_layout: &Layout,
        ids: &Storage<I>,
        ids_layout: &Layout,
        dim: usize,
    ) -> Result<Self> {
        let vec = Self::do_index_select(ids.data(), ids_layout, dim, self.data(), self_layout)?;
        Ok(Storage::new(vec))
    }

    fn do_index_select<I: IntDType>(ids: &[I], ids_l: &Layout, dim: usize, src: &[T], layout: &Layout) -> Result<Vec<T>> {
        if !layout.is_contiguous() {
            Err(Error::RequiresContiguous { op: "index-select" })?
        } 
        let src = &src[layout.start_offset..layout.start_offset+layout.shape.element_count()];
        let n_ids = ids_l.dims();
        assert!(n_ids.len() == 1);
        let n_ids = n_ids[0];
        let stride_ids = ids_l.stride()[0];
        let mut dst_dims = layout.dims().to_vec();
        let src_dim = dst_dims[dim];
        dst_dims[dim] = n_ids;
        let dst_len: usize = dst_dims.iter().product();
        let left_len: usize = dst_dims[..dim].iter().product();
        let right_len: usize = dst_dims[dim + 1..].iter().product();
        let mut dst = vec![T::ZERO; dst_len];
        for left_i in 0..left_len {
            let start_src_idx = left_i * right_len * src_dim;
            let start_dst_idx = left_i * right_len * n_ids;
            for i in 0..n_ids {
                let start_dst_idx = start_dst_idx + i * right_len;
                let index = ids[ids_l.start_offset() + stride_ids * i];
                if index == I::max_value() {
                    dst[start_dst_idx..start_dst_idx + right_len].fill(T::ZERO);
                } else {
                    let index = index.to_usize();
                    if index >= src_dim {
                        Err(Error::InvalidIndex {
                            index,
                            size: src_dim,
                            op: "index-select",
                        })?
                    }
                    let start_src_idx = start_src_idx + index * right_len;
                    dst[start_dst_idx..start_dst_idx + right_len]
                        .copy_from_slice(&src[start_src_idx..start_src_idx + right_len])
                }
            }
        }
        Ok(dst)
    }
}

impl<T: NumDType> Storage<T> {
    pub(crate) fn index_add<I: IntDType>(
        &self,
        self_layout: &Layout,
        ids: &Storage<I>,
        ids_layout: &Layout,
        source: &Storage<T>,
        source_layout: &Layout,
        dim: usize,
    ) -> Result<Self> {
        if !self_layout.is_contiguous() || !source_layout.is_contiguous() {
            return Err(Error::RequiresContiguous { op: "index-add" }.into());
        }

        let new_data = Self::do_index_add(
            self.data(),
            self_layout,
            ids.data(),
            ids_layout,
            source.data(),
            dim
        )?;
        
        Ok(Storage::new(new_data))
    }

    fn do_index_add<I: IntDType>(
        dst_data: &[T],      
        dst_layout: &Layout,
        ids: &[I],           
        ids_layout: &Layout, 
        src_data: &[T],     
        dim: usize,
    ) -> Result<Vec<T>> {
        // 1. 复制一份 dst_data 作为结果,因为我们要修改它 (或者说是累加到一个新 buffer 上)
        // 注意:在大张量场景下,这里可能会有性能开销。
        // 如果你的系统支持 inplace 修改且确信引用计数为1,可以直接修改。
        // 这里为了安全采用 clone。
        let mut result = dst_data.to_vec();

        let n_ids = ids_layout.dims()[0];
        let stride_ids = ids_layout.stride()[0];

        let dst_dims = dst_layout.dims();
        let src_dim_size = dst_dims[dim]; // 原始张量在该维度的长度

        let left_len: usize = dst_dims[..dim].iter().product();
        let right_len: usize = dst_dims[dim + 1..].iter().product();
        
        // src (grad) 的结构是 [left, n_ids, right]
        // dst (self) 的结构是 [left, src_dim_size, right]

        for left_i in 0..left_len {
            let start_src_block = left_i * n_ids * right_len;
            let start_dst_block = left_i * src_dim_size * right_len;

            for i in 0..n_ids {
                // 获取索引值
                let index_val = ids[ids_layout.start_offset() + stride_ids * i];
                
                // 处理 mask (如果有 padding index)
                if index_val == I::max_value() {
                    continue; 
                }

                let idx = index_val.to_usize();
                if idx >= src_dim_size {
                    return Err(Error::InvalidIndex {
                        index: idx,
                        size: src_dim_size,
                        op: "index-add",
                    }.into());
                }

                // 计算偏移量
                let src_offset = start_src_block + i * right_len;
                let dst_offset = start_dst_block + idx * right_len;

                // 执行加法: dst[idx] += src[i]
                for k in 0..right_len {
                    let s_val = src_data[src_offset + k];
                    let d_val = result[dst_offset + k];
                    result[dst_offset + k] = d_val + s_val;
                }
            }
        }

        Ok(result)
    }
}

impl<T: WithDType> Storage<T> {
    pub(crate) fn gather<I: IntDType>(
        &self,
        self_layout: &Layout,
        ids: &Storage<I>,
        ids_layout: &Layout,
        dim: usize,
    ) -> Result<Self> {
        let new_data = Self::do_gather(self.data(), self_layout, ids.data(), ids_layout, dim)?;
        Ok(Storage::new(new_data))
    }

    fn do_gather<I: IntDType>(
        src: &[T],
        src_layout: &Layout,
        ids: &[I],
        ids_layout: &Layout,
        dim: usize,
    ) -> Result<Vec<T>> {
        // 1. 检查连续性:为了简化多维索引的偏移量计算,强制要求 src 和 ids 均连续。
        // 如果需要支持非连续,需要根据 stride 手动计算物理偏移量,会显著增加复杂性。
        if !src_layout.is_contiguous() || !ids_layout.is_contiguous() {
            return Err(Error::RequiresContiguous { op: "gather" }.into());
        }

        let src_dims = src_layout.dims();
        let ids_dims = ids_layout.dims();

        // 2. 检查维度一致性 (Rank check)
        if src_dims.len() != ids_dims.len() {
             return Err(Error::ShapeMismatchBinaryOp { 
                lhs: src_layout.shape().clone(), 
                rhs: ids_layout.shape().clone(),
                op: "gather" 
             }.into());
        }

        // 3. 准备结果 Buffer
        let dst_len = ids_layout.shape.element_count();
        // 类似于 index_select,预填充默认值 (如 0 或 false),方便处理 Padding Mask
        let mut dst = vec![T::ZERO; dst_len];

        // 4. 计算三段式维度的长度:[Left, Dim, Right]
        // Left: dim 左边所有维度的乘积
        let left_len: usize = src_dims[..dim].iter().product();
        // Right: dim 右边所有维度的乘积
        let right_len: usize = src_dims[dim + 1..].iter().product();
        
        let src_dim_size = src_dims[dim];
        let ids_dim_size = ids_dims[dim];

        // 5. 执行 Gather 操作
        // 逻辑视角:src 是 [left, src_dim, right], ids 是 [left, ids_dim, right]
        // 我们遍历 ids (即遍历 dst) 的所有位置
        
        for i in 0..left_len {
            // 计算 src 在当前 Left 块的起始偏移
            let src_block_start = i * src_dim_size * right_len;
            let dst_block_start = i * ids_dim_size * right_len;

            for j in 0..ids_dim_size {
                for k in 0..right_len {
                    // 计算 ids 和 dst 的线性索引 (因为是连续内存)
                    // dst_idx = (i * ids_dim * right) + (j * right) + k
                    let dst_idx = dst_block_start + j * right_len + k;
                    
                    let index_val = ids[dst_idx];

                    // 处理 Mask (Padding Index)
                    if index_val == I::max_value() {
                        dst[dst_idx] = T::ZERO;
                        continue;
                    }

                    let idx = index_val.to_usize();
                    if idx >= src_dim_size {
                        return Err(Error::InvalidIndex {
                            index: idx,
                            size: src_dim_size,
                            op: "gather",
                        }.into());
                    }

                    // 计算 src 的线性索引
                    // src 取值的逻辑:保持 Left(i) 和 Right(k) 不变,Dim 变为 ids 中读出的 idx
                    let src_idx = src_block_start + idx * right_len + k;

                    dst[dst_idx] = src[src_idx];
                }
            }
        }

        Ok(dst)
    }
}

impl<T: NumDType> Storage<T> {
    pub(crate) fn scatter_add<I: IntDType>(
        &self,
        self_layout: &Layout,
        ids: &Storage<I>,
        ids_layout: &Layout,
        source: &Storage<T>,
        source_layout: &Layout,
        dim: usize,
    ) -> Result<Self> {
        if !self_layout.is_contiguous() || !ids_layout.is_contiguous() || !source_layout.is_contiguous() {
            return Err(Error::RequiresContiguous { op: "scatter-add" }.into());
        }

        // 这里的 self 是 destination (arg_grad),source 是 gradient
        let new_data = Self::do_scatter_add(
            self.data(),
            self_layout,
            ids.data(),
            ids_layout,
            source.data(),
            dim
        )?;
        
        Ok(Storage::new(new_data))
    }

    fn do_scatter_add<I: IntDType>(
        dst: &[T],          // arg_grad 的当前数据 (通常是 zero buffer)
        dst_layout: &Layout,
        ids: &[I],          // 索引
        ids_layout: &Layout,
        src: &[T],          // incoming grad
        dim: usize,
    ) -> Result<Vec<T>> {
        // 1. 复制 dst 数据以进行累加 (inplace 模拟)
        let mut result = dst.to_vec();

        let dst_dims = dst_layout.dims();
        let src_dims = ids_layout.dims(); // src 和 ids 的形状应该一致

        // 检查维度一致性
        if dst_dims.len() != src_dims.len() {
             return Err(Error::ShapeMismatchBinaryOp { 
                lhs: dst_layout.shape().clone(), 
                rhs: ids_layout.shape().clone(),
                op: "scatter-add" 
             }.into());
        }

        // 2. 计算三段式维度
        // 我们遍历的是 source (grad) 和 ids,它们的形状是一样的
        let left_len: usize = src_dims[..dim].iter().product();
        let right_len: usize = src_dims[dim + 1..].iter().product();
        
        let src_dim_size = src_dims[dim]; // ids 的 dim 长度
        let dst_dim_size = dst_dims[dim]; // arg (dst) 的 dim 长度

        // 3. 执行 Scatter Add
        // 逻辑:遍历 src(grad) 的每一个元素,找到 ids 中对应的索引 idx,
        // 然后 result[left, idx, right] += src[left, i, right]
        
        for i in 0..left_len {
            let src_block_start = i * src_dim_size * right_len;
            let dst_block_start = i * dst_dim_size * right_len;

            for j in 0..src_dim_size {
                for k in 0..right_len {
                    // src 和 ids 是同步遍历的
                    let linear_idx = src_block_start + j * right_len + k;
                    
                    let index_val = ids[linear_idx];

                    // 处理 Mask (Padding Index)
                    if index_val == I::max_value() {
                        continue;
                    }

                    let idx = index_val.to_usize();
                    if idx >= dst_dim_size {
                        return Err(Error::InvalidIndex {
                            index: idx,
                            size: dst_dim_size,
                            op: "scatter-add",
                        }.into());
                    }

                    // 计算目标位置的索引
                    // 保持 Left(i) 和 Right(k) 不变,Dim 变为从 ids 读出的 idx
                    let dst_idx = dst_block_start + idx * right_len + k;

                    // 累加梯度
                    result[dst_idx] = result[dst_idx] + src[linear_idx];
                }
            }
        }

        Ok(result)
    }
}

#[derive(Clone)]
pub struct StorageArc<T>(pub(crate) Arc<RwLock<Storage<T>>>);

impl<T: WithDType> StorageArc<T> {
    pub fn new(storage: Storage<T>) -> Self {
        Self(Arc::new(RwLock::new(storage)))
    }

    #[inline]
    pub fn read(&self) -> std::sync::RwLockReadGuard<'_, Storage<T>> {
        self.0.read().expect("read in storage arc")
    }

    #[inline]
    pub fn write(&self) -> std::sync::RwLockWriteGuard<'_, Storage<T>> {
        self.0.write().expect("write in storage arc")
    }

    #[inline]
    pub fn get(&self, index: usize) -> Option<T> {
        self.read().get(index)
    }

    #[inline]
    pub fn set(&mut self, index: usize, val: T) -> Option<()> {
        self.write().set(index, val)
    }

    #[inline]
    pub fn get_unchecked(&self, index: usize) -> T {
        self.read().get_unchecked(index)
    }

    #[inline]
    pub fn set_unchecked(&self, index: usize, val: T) {
        self.write().set_unchecked(index, val)
    }

    #[inline]
    pub fn ptr_eq(this: &Self, other: &Self) -> bool {
        Arc::ptr_eq(&this.0, &other.0)
    }

    #[inline]
    pub fn get_ptr(&self, start_offset: usize) -> *mut T {
        let mut s = self.0.write().unwrap();
        let data = &mut s.data_mut()[start_offset..];
        data.as_mut_ptr()
    }
}