incin-core 0.1.0

Core tensor operations and static shape checking for incin
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
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Unary tensor operations.
//!
//! This module provides element-wise unary operations (e.g., `abs`, `relu`, `exp`) that act
//! on a single tensor and return a new tensor with the exact same shape. It also includes
//! operations that interact with a scalar (e.g., `mul_scalar`, `add_scalar`).
use crate::err::Result;
use crate::exec::catalog::op;
use crate::shapes::{DynShape, Shape};
use crate::tensor::backend::Backend;
use crate::tensor::backend::Execute;
use crate::tensor::base::Tensor;
use crate::tensor::grad::RequiresGrad;
use crate::tensor::ops::reduce::ReduceSelector;

macro_rules! impl_unary_op {
    (
        $(#[$meta:meta])*
        $method:ident, $operation:ident
    ) => {
        $(#[$meta])*
        pub fn $method(&self) -> Result<Self>
        where
            B: Execute<op::$operation>,
            <B as Execute<op::$operation>>::Output: Into<B::Storage<K>>,
        {
            execute_unary_descriptor::<op::$operation, S, B, K, G>(self)
        }
    };
}

impl<S: Shape, B: Backend, K: crate::tensor::dtype::DType, G: RequiresGrad> Tensor<S, B, K, G> {
    impl_unary_op!(
        /// Elementwise tangent.
        tan, Tan
    );
    impl_unary_op!(
        /// Elementwise arcsine.
        asin, Asin
    );
    impl_unary_op!(
        /// Elementwise arccosine.
        acos, Acos
    );
    impl_unary_op!(
        /// Elementwise arctangent.
        atan, Atan
    );
    impl_unary_op!(
        /// Elementwise hyperbolic sine.
        sinh, Sinh
    );
    impl_unary_op!(
        /// Elementwise hyperbolic cosine.
        cosh, Cosh
    );
    impl_unary_op!(
        /// Elementwise inverse hyperbolic sine.
        asinh, Asinh
    );
    impl_unary_op!(
        /// Elementwise inverse hyperbolic cosine.
        acosh, Acosh
    );
    impl_unary_op!(
        /// Elementwise inverse hyperbolic tangent.
        atanh, Atanh
    );
    impl_unary_op!(
        /// Elementwise error function.
        erf, Erf
    );
    impl_unary_op!(
        /// Elementwise reciprocal square root $1/\sqrt{x}$.
        rsqrt, Rsqrt
    );
    impl_unary_op!(
        /// Elementwise integer truncation toward zero.
        trunc, Trunc
    );
    impl_unary_op!(
        /// Elementwise fractional part.
        frac, Frac
    );

    /// Computes the absolute value of each element in the tensor.
    pub fn abs(&self) -> Result<Self>
    where
        B: Execute<op::Abs>,
        <B as Execute<op::Abs>>::Output: Into<B::Storage<K>>,
    {
        execute_unary_descriptor::<op::Abs, S, B, K, G>(self)
    }

    /// Applies the Rectified Linear Unit (ReLU) function element-wise.
    pub fn relu(&self) -> Result<Self>
    where
        B: Execute<op::Relu>,
        <B as Execute<op::Relu>>::Output: Into<B::Storage<K>>,
    {
        execute_unary_descriptor::<op::Relu, S, B, K, G>(self)
    }

    /// Applies the Gaussian Error Linear Unit (GELU) function element-wise.
    pub fn gelu(&self) -> Result<Self>
    where
        B: Execute<op::Gelu>,
        <B as Execute<op::Gelu>>::Output: Into<B::Storage<K>>,
    {
        execute_unary_descriptor::<op::Gelu, S, B, K, G>(self)
    }

    /// Applies the Step function element-wise.
    pub fn step(&self) -> Result<Self>
    where
        B: Execute<op::Step>,
        <B as Execute<op::Step>>::Output: Into<B::Storage<K>>,
    {
        execute_unary_descriptor::<op::Step, S, B, K, G>(self)
    }

    /// Applies the Mish function element-wise.
    pub fn mish(&self) -> Result<Self>
    where
        B: Execute<op::Mish>,
        <B as Execute<op::Mish>>::Output: Into<B::Storage<K>>,
    {
        execute_unary_descriptor::<op::Mish, S, B, K, G>(self)
    }

    /// Applies the Exponential Linear Unit (ELU) function element-wise with alpha=1.0.
    pub fn elu(&self) -> Result<Self>
    where
        B: Execute<op::Elu>,
        <B as Execute<op::Elu>>::Output: Into<B::Storage<K>>,
    {
        execute_unary_descriptor::<op::Elu, S, B, K, G>(self)
    }

    /// Applies the Swish function element-wise (also known as SiLU).
    pub fn swish(&self) -> Result<Self>
    where
        B: Execute<op::Swish>,
        <B as Execute<op::Swish>>::Output: Into<B::Storage<K>>,
    {
        execute_unary_descriptor::<op::Swish, S, B, K, G>(self)
    }

    /// Applies the Softmax function over the specified dimension.
    #[inline]
    pub fn softmax<A: ReduceSelector<S>>(&self, axis: A) -> Result<Tensor<S, B, K, G>>
    where
        S: DynShape,
        B: Execute<op::Softmax>,
        <B as Execute<op::Softmax>>::Output: Into<B::Storage<K>>,
    {
        let dim = axis.resolve(self.shape_buf().rank())?;
        execute_unary_descriptor_with_attributes::<op::Softmax, S, B, K, G>(
            self,
            crate::exec::catalog::AxisAttributes { axis: dim },
        )
    }

    /// Negates the tensor element-wise, returning recoverable execution errors.
    pub fn try_neg(&self) -> Result<Self>
    where
        B: Execute<op::Neg>,
        <B as Execute<op::Neg>>::Output: Into<B::Storage<K>>,
    {
        execute_unary_descriptor::<op::Neg, S, B, K, G>(self)
    }

    /// Checked compatibility spelling. Prefer [`Self::try_neg`] in new code.
    #[doc(hidden)]
    pub fn neg(&self) -> Result<Self>
    where
        B: Execute<op::Neg>,
        <B as Execute<op::Neg>>::Output: Into<B::Storage<K>>,
    {
        self.try_neg()
    }

    /// Computes the square root of each element.
    pub fn sqrt(&self) -> Result<Self>
    where
        B: Execute<op::Sqrt>,
        <B as Execute<op::Sqrt>>::Output: Into<B::Storage<K>>,
    {
        execute_unary_descriptor::<op::Sqrt, S, B, K, G>(self)
    }

    /// Computes the exponential of each element.
    pub fn exp(&self) -> Result<Self>
    where
        B: Execute<op::Exp>,
        <B as Execute<op::Exp>>::Output: Into<B::Storage<K>>,
    {
        execute_unary_descriptor::<op::Exp, S, B, K, G>(self)
    }

    /// Raises tensor elements to power `exponent`.
    #[inline]
    pub fn powf(&self, exponent: f64) -> Result<Self>
    where
        B: Execute<op::Powf>,
        <B as Execute<op::Powf>>::Output: Into<B::Storage<K>>,
    {
        execute_unary_descriptor_with_attributes::<op::Powf, S, B, K, G>(
            self,
            crate::exec::catalog::ScalarAttributes { value: exponent },
        )
    }

    /// Clamps tensor elements to range `[min, max]`.
    #[inline]
    pub fn clamp(&self, min: f64, max: f64) -> Result<Self>
    where
        B: Execute<op::Clamp>,
        <B as Execute<op::Clamp>>::Output: Into<B::Storage<K>>,
    {
        execute_unary_descriptor_with_attributes::<op::Clamp, S, B, K, G>(
            self,
            crate::exec::catalog::ClampAttributes { min, max },
        )
    }

    impl_unary_op!(
        /// Elementwise sign function (-1.0, 0.0, or +1.0).
        sign, Sign
    );

    impl_unary_op!(
        /// Computes the floor of each element.
        floor, Floor
    );

    impl_unary_op!(
        /// Computes the ceiling of each element.
        ceil, Ceil
    );

    impl_unary_op!(
        /// Rounds each element to nearest integer.
        round, Round
    );

    impl_unary_op!(
        /// Computes base-2 logarithm elementwise.
        log2, Log2
    );

    impl_unary_op!(
        /// Computes base-10 logarithm elementwise.
        log10, Log10
    );

    impl_unary_op!(
        /// Computes sine elementwise.
        sin, Sin
    );

    impl_unary_op!(
        /// Computes cosine elementwise.
        cos, Cos
    );

    /// Computes the natural logarithm of each element.
    pub fn log(&self) -> Result<Self>
    where
        B: Execute<op::Log>,
        <B as Execute<op::Log>>::Output: Into<B::Storage<K>>,
    {
        execute_unary_descriptor::<op::Log, S, B, K, G>(self)
    }

    /// Computes the hyperbolic tangent of each element.
    pub fn tanh(&self) -> Result<Self>
    where
        B: Execute<op::Tanh>,
        <B as Execute<op::Tanh>>::Output: Into<B::Storage<K>>,
    {
        execute_unary_descriptor::<op::Tanh, S, B, K, G>(self)
    }

    /// Computes the sigmoid of each element.
    pub fn sigmoid(&self) -> Result<Self>
    where
        B: Execute<op::Sigmoid>,
        <B as Execute<op::Sigmoid>>::Output: Into<B::Storage<K>>,
    {
        execute_unary_descriptor::<op::Sigmoid, S, B, K, G>(self)
    }

    /// Multiplies the tensor by a scalar value element-wise.
    ///
    /// # Examples
    /// ```rust
    /// # extern crate incin_core as incin;
    /// # type DefaultBackend = incin_backends::cpu::CpuBackendImpl;
    /// use incin::prelude::*;
    /// let t = Tensor::<s![2], DefaultBackend>::from_slice(&[1.0, 2.0], ()).unwrap();
    /// let res = t.mul_scalar(3.0).unwrap(); // [3.0, 6.0]
    /// ```
    pub fn mul_scalar<Sc: Into<crate::tensor::backend::ScalarValue>>(
        &self,
        scalar: Sc,
    ) -> Result<Self>
    where
        B: Execute<op::MulScalar>,
        <B as Execute<op::MulScalar>>::Output: Into<B::Storage<K>>,
    {
        execute_unary_descriptor_with_attributes::<op::MulScalar, S, B, K, G>(
            self,
            crate::exec::catalog::ScalarAttributes {
                value: scalar.into().to_f64(),
            },
        )
    }

    /// Adds a scalar value to the tensor element-wise.
    ///
    /// # Examples
    /// ```rust
    /// # extern crate incin_core as incin;
    /// # type DefaultBackend = incin_backends::cpu::CpuBackendImpl;
    /// use incin::prelude::*;
    /// let t = Tensor::<s![2], DefaultBackend>::from_slice(&[1.0, 2.0], ()).unwrap();
    /// let res = t.add_scalar(3.0).unwrap(); // [4.0, 5.0]
    /// ```
    pub fn add_scalar<Sc: Into<crate::tensor::backend::ScalarValue>>(
        &self,
        scalar: Sc,
    ) -> Result<Self>
    where
        B: Execute<op::AddScalar>,
        <B as Execute<op::AddScalar>>::Output: Into<B::Storage<K>>,
    {
        execute_unary_descriptor_with_attributes::<op::AddScalar, S, B, K, G>(
            self,
            crate::exec::catalog::ScalarAttributes {
                value: scalar.into().to_f64(),
            },
        )
    }
}

use crate::dist::placement::Local;
use crate::exec::catalog::{AttributeContract, CanonicalOperation, NoAttributes};
use crate::exec::context::ExecutionContext;
use crate::exec::dispatch;
use crate::exec::request::TensorHandle;
pub(crate) fn execute_unary_descriptor<
    O,
    S: Shape,
    B: Backend,
    K: crate::tensor::dtype::DType,
    G: RequiresGrad,
>(
    tensor: &Tensor<S, B, K, G>,
) -> Result<Tensor<S, B, K, G>>
where
    O: CanonicalOperation + crate::exec::catalog::Operation<Attributes = NoAttributes>,
    B: Execute<O>,
    <B as Execute<O>>::Output: Into<B::Storage<K>>,
{
    let handle = TensorHandle::from_storage::<B, K, Local>(&tensor.inner);
    let shape_val = tensor._shape.clone();
    let context = crate::tensor::grad::execution_context::<B, G>(&tensor._grad);
    let storage = G::grad_mode(&tensor._grad)
        .restrict(|| {
            dispatch::execute_shaped::<O, B, S>(&context, NoAttributes, &[handle], &shape_val)
        })
        .map_err(crate::err::Error::from)?;
    Tensor::from_shape_value(
        storage.into(),
        tensor._shape.clone(),
        tensor._dtype.clone(),
        tensor._device.clone(),
        tensor._grad.clone(),
    )
}

pub(crate) fn execute_unary_descriptor_with_attributes<
    O,
    S: Shape,
    B: Backend,
    K: crate::tensor::dtype::DType,
    G: RequiresGrad,
>(
    tensor: &Tensor<S, B, K, G>,
    attributes: O::Attributes,
) -> Result<Tensor<S, B, K, G>>
where
    O: CanonicalOperation,
    O::Attributes: AttributeContract,
    B: Execute<O>,
    <B as Execute<O>>::Output: Into<B::Storage<K>>,
{
    let handle = TensorHandle::from_storage::<B, K, Local>(&tensor.inner);
    let shape_val = tensor._shape.clone();
    let context = crate::tensor::grad::execution_context::<B, G>(&tensor._grad);
    let storage = G::grad_mode(&tensor._grad)
        .restrict(|| {
            dispatch::execute_shaped::<O, B, S>(&context, attributes, &[handle], &shape_val)
        })
        .map_err(crate::err::Error::from)?;
    Tensor::from_shape_value(
        storage.into(),
        tensor._shape.clone(),
        tensor._dtype.clone(),
        tensor._device.clone(),
        tensor._grad.clone(),
    )
}

pub(crate) fn execute_logical_unary_descriptor<O, S: Shape, B: Backend, G: RequiresGrad>(
    tensor: &Tensor<S, B, bool, G>,
) -> Result<Tensor<S, B, bool, crate::tensor::grad::NoGrad>>
where
    O: CanonicalOperation + crate::exec::catalog::Operation<Attributes = NoAttributes>,
    B: Execute<O>,
    <B as Execute<O>>::Output: Into<B::Storage<bool>>,
{
    let handle = TensorHandle::from_storage::<B, bool, Local>(&tensor.inner);
    let shape_val = tensor._shape.clone();
    let context =
        ExecutionContext::from_scope(B::default()).with_grad_mode(crate::exec::GradMode::Disabled);
    let storage = crate::tensor::grad::NoGrad::grad_mode(&Default::default())
        .restrict(|| {
            dispatch::execute_shaped::<O, B, S>(&context, NoAttributes, &[handle], &shape_val)
        })
        .map_err(crate::err::Error::from)?;
    Tensor::from_shape_value(
        storage.into(),
        tensor._shape.clone(),
        Default::default(),
        tensor._device.clone(),
        Default::default(),
    )
}

impl<S: Shape, B: Backend, G: RequiresGrad> Tensor<S, B, bool, G> {
    /// Logical NOT element-wise.
    pub fn logical_not(&self) -> Result<Tensor<S, B, bool, crate::tensor::grad::NoGrad>>
    where
        B: Execute<op::LogicalNot>,
        <B as Execute<op::LogicalNot>>::Output: Into<B::Storage<bool>>,
    {
        execute_logical_unary_descriptor::<op::LogicalNot, S, B, G>(self)
    }
}

macro_rules! impl_std_scalar_ops {
    ($t:ty) => {
        impl<S: Shape, B: Backend, K: crate::tensor::dtype::DType, G: RequiresGrad>
            core::ops::Mul<$t> for Tensor<S, B, K, G>
        where
            B: Execute<op::MulScalar>,
            <B as Execute<op::MulScalar>>::Output: Into<B::Storage<K>>,
        {
            /// Scalar multiplication preserves shape/dtype/device.
            type Output = Tensor<S, B, K, G>;
            #[inline]
            /// `tensor * scalar` panics if [`Tensor::mul_scalar`] fails.
            fn mul(self, rhs: $t) -> Self::Output {
                crate::tensor::ops::operator_or_panic("* (scalar)", self.mul_scalar(rhs))
            }
        }
        impl<'a, S: Shape, B: Backend, K: crate::tensor::dtype::DType, G: RequiresGrad>
            core::ops::Mul<$t> for &'a Tensor<S, B, K, G>
        where
            B: Execute<op::MulScalar>,
            <B as Execute<op::MulScalar>>::Output: Into<B::Storage<K>>,
        {
            /// Scalar multiplication preserves shape/dtype/device.
            type Output = Tensor<S, B, K, G>;
            #[inline]
            /// `tensor * scalar` panics if [`Tensor::mul_scalar`] fails.
            fn mul(self, rhs: $t) -> Self::Output {
                crate::tensor::ops::operator_or_panic("* (scalar)", self.mul_scalar(rhs))
            }
        }
        impl<S: Shape, B: Backend, K: crate::tensor::dtype::DType, G: RequiresGrad>
            core::ops::Add<$t> for Tensor<S, B, K, G>
        where
            B: Execute<op::AddScalar>,
            <B as Execute<op::AddScalar>>::Output: Into<B::Storage<K>>,
        {
            /// Scalar addition preserves shape/dtype/device.
            type Output = Tensor<S, B, K, G>;
            #[inline]
            /// `tensor + scalar` panics if [`Tensor::add_scalar`] fails.
            fn add(self, rhs: $t) -> Self::Output {
                crate::tensor::ops::operator_or_panic("+ (scalar)", self.add_scalar(rhs))
            }
        }
        impl<'a, S: Shape, B: Backend, K: crate::tensor::dtype::DType, G: RequiresGrad>
            core::ops::Add<$t> for &'a Tensor<S, B, K, G>
        where
            B: Execute<op::AddScalar>,
            <B as Execute<op::AddScalar>>::Output: Into<B::Storage<K>>,
        {
            /// Scalar addition preserves shape/dtype/device.
            type Output = Tensor<S, B, K, G>;
            #[inline]
            /// `tensor + scalar` panics if [`Tensor::add_scalar`] fails.
            fn add(self, rhs: $t) -> Self::Output {
                crate::tensor::ops::operator_or_panic("+ (scalar)", self.add_scalar(rhs))
            }
        }

        impl<S: Shape, B: Backend, K: crate::tensor::dtype::DType, G: RequiresGrad>
            core::ops::Sub<$t> for Tensor<S, B, K, G>
        where
            B: Execute<op::SubScalar>,
            <B as Execute<op::SubScalar>>::Output: Into<B::Storage<K>>,
        {
            type Output = Tensor<S, B, K, G>;

            fn sub(self, rhs: $t) -> Self::Output {
                crate::tensor::ops::operator_or_panic("- (scalar)", self.sub_scalar(rhs as f64))
            }
        }

        impl<'a, S: Shape, B: Backend, K: crate::tensor::dtype::DType, G: RequiresGrad>
            core::ops::Sub<$t> for &'a Tensor<S, B, K, G>
        where
            B: Execute<op::SubScalar>,
            <B as Execute<op::SubScalar>>::Output: Into<B::Storage<K>>,
        {
            type Output = Tensor<S, B, K, G>;

            fn sub(self, rhs: $t) -> Self::Output {
                crate::tensor::ops::operator_or_panic("- (scalar)", self.sub_scalar(rhs as f64))
            }
        }

        impl<S: Shape, B: Backend, K: crate::tensor::dtype::DType, G: RequiresGrad>
            core::ops::Div<$t> for Tensor<S, B, K, G>
        where
            B: Execute<op::DivScalar>,
            <B as Execute<op::DivScalar>>::Output: Into<B::Storage<K>>,
        {
            type Output = Tensor<S, B, K, G>;

            fn div(self, rhs: $t) -> Self::Output {
                crate::tensor::ops::operator_or_panic("/ (scalar)", self.div_scalar(rhs as f64))
            }
        }

        impl<'a, S: Shape, B: Backend, K: crate::tensor::dtype::DType, G: RequiresGrad>
            core::ops::Div<$t> for &'a Tensor<S, B, K, G>
        where
            B: Execute<op::DivScalar>,
            <B as Execute<op::DivScalar>>::Output: Into<B::Storage<K>>,
        {
            type Output = Tensor<S, B, K, G>;

            fn div(self, rhs: $t) -> Self::Output {
                crate::tensor::ops::operator_or_panic("/ (scalar)", self.div_scalar(rhs as f64))
            }
        }
    };
}

impl_std_scalar_ops!(f32);
impl_std_scalar_ops!(f64);
impl_std_scalar_ops!(i32);
impl_std_scalar_ops!(i64);

impl<S: Shape, B: Backend, K: crate::tensor::dtype::DType, G: RequiresGrad> core::ops::Neg
    for Tensor<S, B, K, G>
where
    B: Execute<op::Neg>,
    <B as Execute<op::Neg>>::Output: Into<B::Storage<K>>,
{
    type Output = Tensor<S, B, K, G>;

    fn neg(self) -> Self::Output {
        crate::tensor::ops::operator_or_panic("- (unary)", self.try_neg())
    }
}

impl<S: Shape, B: Backend, K: crate::tensor::dtype::DType, G: RequiresGrad> core::ops::Neg
    for &Tensor<S, B, K, G>
where
    B: Execute<op::Neg>,
    <B as Execute<op::Neg>>::Output: Into<B::Storage<K>>,
{
    type Output = Tensor<S, B, K, G>;

    fn neg(self) -> Self::Output {
        crate::tensor::ops::operator_or_panic("- (unary)", self.try_neg())
    }
}