DepthTensor 2.2.1__tar.gz → 2.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {depthtensor-2.2.1 → depthtensor-2.4.0}/LICENSE +1 -1
- depthtensor-2.4.0/PKG-INFO +155 -0
- depthtensor-2.4.0/README.md +115 -0
- depthtensor-2.4.0/pyproject.toml +35 -0
- {depthtensor-2.2.1 → depthtensor-2.4.0}/src/DepthTensor/__init__.py +1 -1
- depthtensor-2.4.0/src/DepthTensor/_core/ops/diff.py +272 -0
- {depthtensor-2.2.1 → depthtensor-2.4.0}/src/DepthTensor/_core/ops/elementwise.py +51 -1
- {depthtensor-2.2.1 → depthtensor-2.4.0}/src/DepthTensor/_core/utils.py +1 -1
- depthtensor-2.4.0/src/DepthTensor/autodiff.py +75 -0
- {depthtensor-2.2.1 → depthtensor-2.4.0}/src/DepthTensor/tensor.py +44 -8
- depthtensor-2.4.0/src/depthtensor.egg-info/PKG-INFO +155 -0
- {depthtensor-2.2.1/src/DepthTensor.egg-info → depthtensor-2.4.0/src/depthtensor.egg-info}/SOURCES.txt +6 -6
- {depthtensor-2.2.1/src/DepthTensor.egg-info → depthtensor-2.4.0/src/depthtensor.egg-info}/requires.txt +1 -1
- depthtensor-2.2.1/PKG-INFO +0 -24
- depthtensor-2.2.1/README.md +0 -14
- depthtensor-2.2.1/pyproject.toml +0 -19
- depthtensor-2.2.1/src/DepthTensor/_core/ops/diff.py +0 -232
- depthtensor-2.2.1/src/DepthTensor/autodiff.py +0 -53
- depthtensor-2.2.1/src/DepthTensor.egg-info/PKG-INFO +0 -24
- {depthtensor-2.2.1 → depthtensor-2.4.0}/setup.cfg +0 -0
- {depthtensor-2.2.1 → depthtensor-2.4.0}/src/DepthTensor/_core/__init__.py +0 -0
- {depthtensor-2.2.1 → depthtensor-2.4.0}/src/DepthTensor/_core/exceptions.py +0 -0
- {depthtensor-2.2.1 → depthtensor-2.4.0}/src/DepthTensor/_core/ops/__init__.py +0 -0
- {depthtensor-2.2.1 → depthtensor-2.4.0}/src/DepthTensor/_core/ops/comparison.py +0 -0
- {depthtensor-2.2.1 → depthtensor-2.4.0}/src/DepthTensor/_core/ops/creation.py +0 -0
- {depthtensor-2.2.1 → depthtensor-2.4.0}/src/DepthTensor/_core/ops/reduction.py +0 -0
- {depthtensor-2.2.1 → depthtensor-2.4.0}/src/DepthTensor/_core/random/__init__.py +0 -0
- {depthtensor-2.2.1 → depthtensor-2.4.0}/src/DepthTensor/_core/random/generator.py +0 -0
- {depthtensor-2.2.1 → depthtensor-2.4.0}/src/DepthTensor/typing.py +0 -0
- {depthtensor-2.2.1/src/DepthTensor.egg-info → depthtensor-2.4.0/src/depthtensor.egg-info}/dependency_links.txt +0 -0
- {depthtensor-2.2.1/src/DepthTensor.egg-info → depthtensor-2.4.0/src/depthtensor.egg-info}/top_level.txt +0 -0
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: depthtensor
|
|
3
|
+
Version: 2.4.0
|
|
4
|
+
Summary: A Hardware-Accelerated Tensor Computation and Autograd Engine
|
|
5
|
+
Author-email: Le Hong Ha <lehahong1310@gmail.com>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2025 Le Hong Ha
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
Project-URL: Homepage, https://github.com/l-h-ha/DepthTensor
|
|
28
|
+
Project-URL: Bug Tracker, https://github.com/l-h-ha/DepthTensor/issues
|
|
29
|
+
Classifier: Programming Language :: Python :: 3
|
|
30
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
31
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
32
|
+
Classifier: Operating System :: OS Independent
|
|
33
|
+
Requires-Python: >=3.8
|
|
34
|
+
Description-Content-Type: text/markdown
|
|
35
|
+
License-File: LICENSE
|
|
36
|
+
Requires-Dist: numpy
|
|
37
|
+
Provides-Extra: gpu
|
|
38
|
+
Requires-Dist: cupy; extra == "gpu"
|
|
39
|
+
Dynamic: license-file
|
|
40
|
+
|
|
41
|
+
# DepthTensor: A Hardware-Accelerated Tensor Computation and Autograd Engine
|
|
42
|
+
|
|
43
|
+
**DepthTensor** is a light-weight, high-performance library for reverse-mode automatic differentiation (AD). It is useful in building the mathematical foundation of deep learning frameworks, with the use of a `Tensor` object which dynamically builds computational graphs and computes gradients using **Vector-Jacobian Products (VJP)**, generalized for tensors of abritrary rank.
|
|
44
|
+
|
|
45
|
+
> **Note**: This is the core autograd and tensor computation engine. For the full deep learning framework, refer to [DepthML](https://github.com/l-h-ha/DepthML).
|
|
46
|
+
|
|
47
|
+
## 1. Mathematical Foundation
|
|
48
|
+
|
|
49
|
+
The goal is to compute the gradient of scalar field $L$ with respect to an input tensor $X$, denoted as the adjoint $\bar{X}$.
|
|
50
|
+
|
|
51
|
+
### 1.1. Generalized VJPs via Tensor Contractions
|
|
52
|
+
|
|
53
|
+
Let $X$ be a tensor of shape $\mathcal{I} = (i_1, \dots, i_n)$ and $Y = f(X)$ be a tensor of shape $\mathcal{J} = (j_1, \dots, j_m)$.
|
|
54
|
+
|
|
55
|
+
Mathematically, the Jacobian is the tensor of rank $n + m$ which contains all the partial derivatives $\frac{\partial Y_{\mathcal{J}}}{\partial X_{\mathcal{I}}}$. DepthTensor does not compute this object, but, rather, it computes the contraction of the incoming adjoint $\bar{Y}$ with the local derivative:
|
|
56
|
+
|
|
57
|
+
$$
|
|
58
|
+
\bar{X}_{i_1 \dots i_n} = \sum_{j_1 \dots j_m} \bar{Y}_{j_1 \dots j_m} \frac{\partial Y_{j_1 \dots j_m}}{\partial X_{i_1 \dots i_n}}
|
|
59
|
+
$$
|
|
60
|
+
|
|
61
|
+
If X and Y are scalars, indices vanish, and this reduces to:
|
|
62
|
+
|
|
63
|
+
$$
|
|
64
|
+
\bar{x} = \bar{y} \cdot f'(x)
|
|
65
|
+
$$
|
|
66
|
+
|
|
67
|
+
If X and Y are matrices, this reduces to:
|
|
68
|
+
|
|
69
|
+
$$
|
|
70
|
+
\bar{X} = \bar{Y} W^{T}
|
|
71
|
+
$$
|
|
72
|
+
|
|
73
|
+
### 1.2. Graph Topology and Gradient Accumulation
|
|
74
|
+
|
|
75
|
+
Gradients are accumulated using a Depth-First Search (DFS) topological sort, which ensures that for any node $X$ with multiple gradient flow streams ${Y^{(1)}, \dots, Y^{k}}$, the gradient sum is the sum of contractions:
|
|
76
|
+
|
|
77
|
+
$$
|
|
78
|
+
\bar{X} = \sum_{k} \mathrm{VJP}(Y^{(k)}, X)
|
|
79
|
+
$$
|
|
80
|
+
|
|
81
|
+
All gradients are aggregated from all gradient downstreams.
|
|
82
|
+
|
|
83
|
+
## 2. Architecture and System Design
|
|
84
|
+
|
|
85
|
+
### 2.1. The differentiable Primitive (`Tensor`)
|
|
86
|
+
|
|
87
|
+
The `Tensor` class acts like a node in the Directed Acyclic Graph (DAG).
|
|
88
|
+
|
|
89
|
+
Operations are automatically dispatched to backend computers, which consists of `numpy` (CPU) and `cupy` (GPU).
|
|
90
|
+
|
|
91
|
+
Computational graphs are built dynamically at runtime.
|
|
92
|
+
|
|
93
|
+
## 3. Empirical Validation
|
|
94
|
+
|
|
95
|
+
We will verify the tensor engine by minimizing the Rosenbrock function, which is a non-convex optimization benchmark:
|
|
96
|
+
|
|
97
|
+
$$
|
|
98
|
+
f(x, y) = (a - x)^2 + b(y - x^2)^2
|
|
99
|
+
$$
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
import depthtensor as dt
|
|
103
|
+
|
|
104
|
+
# Initialize tensors
|
|
105
|
+
x = dt.Tensor([1.2], device="gpu", requires_grad=True)
|
|
106
|
+
y = dt.Tensor([1.2], device="gpu", requires_grad=True)
|
|
107
|
+
|
|
108
|
+
a, b = dt.Tensor([1], device="gpu"), dt.Tensor(
|
|
109
|
+
[100], device="gpu"
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
# 2. Optimization Loop
|
|
113
|
+
lr = 0.001
|
|
114
|
+
for i in range(500):
|
|
115
|
+
# Rosenbrock: f(x,y) = (a-x)^2 + b(y-x^2)^2
|
|
116
|
+
loss = (a - x) ** 2 + b * (y - x**2) ** 2
|
|
117
|
+
|
|
118
|
+
# Backpward pass
|
|
119
|
+
dt.differentiate(loss)
|
|
120
|
+
|
|
121
|
+
# Gradient Descent
|
|
122
|
+
x.data -= lr * x.grad # type: ignore
|
|
123
|
+
y.data -= lr * y.grad # type: ignore
|
|
124
|
+
|
|
125
|
+
# Zero grads
|
|
126
|
+
x.zeros_grad()
|
|
127
|
+
y.zeros_grad()
|
|
128
|
+
|
|
129
|
+
if i % 10 == 0:
|
|
130
|
+
print(loss.item())
|
|
131
|
+
|
|
132
|
+
print(f"Converged: ({x.data}, {y.data})")
|
|
133
|
+
# Target: (1.0, 1.0)
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## 4. Installation
|
|
137
|
+
|
|
138
|
+
Requirements:
|
|
139
|
+
- `numpy`
|
|
140
|
+
- `cupy` (optional: for NVIDIA GPU acceleration)
|
|
141
|
+
|
|
142
|
+
### 4.1. Bash
|
|
143
|
+
|
|
144
|
+
```bash
|
|
145
|
+
git clone https://github.com/YourUsername/DepthTensor.git
|
|
146
|
+
pip install -e .
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
### 4.2. Pip
|
|
150
|
+
|
|
151
|
+
```bash
|
|
152
|
+
pip install depthtensor
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## Author: Le Hong Ha
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# DepthTensor: A Hardware-Accelerated Tensor Computation and Autograd Engine
|
|
2
|
+
|
|
3
|
+
**DepthTensor** is a light-weight, high-performance library for reverse-mode automatic differentiation (AD). It is useful in building the mathematical foundation of deep learning frameworks, with the use of a `Tensor` object which dynamically builds computational graphs and computes gradients using **Vector-Jacobian Products (VJP)**, generalized for tensors of abritrary rank.
|
|
4
|
+
|
|
5
|
+
> **Note**: This is the core autograd and tensor computation engine. For the full deep learning framework, refer to [DepthML](https://github.com/l-h-ha/DepthML).
|
|
6
|
+
|
|
7
|
+
## 1. Mathematical Foundation
|
|
8
|
+
|
|
9
|
+
The goal is to compute the gradient of scalar field $L$ with respect to an input tensor $X$, denoted as the adjoint $\bar{X}$.
|
|
10
|
+
|
|
11
|
+
### 1.1. Generalized VJPs via Tensor Contractions
|
|
12
|
+
|
|
13
|
+
Let $X$ be a tensor of shape $\mathcal{I} = (i_1, \dots, i_n)$ and $Y = f(X)$ be a tensor of shape $\mathcal{J} = (j_1, \dots, j_m)$.
|
|
14
|
+
|
|
15
|
+
Mathematically, the Jacobian is the tensor of rank $n + m$ which contains all the partial derivatives $\frac{\partial Y_{\mathcal{J}}}{\partial X_{\mathcal{I}}}$. DepthTensor does not compute this object, but, rather, it computes the contraction of the incoming adjoint $\bar{Y}$ with the local derivative:
|
|
16
|
+
|
|
17
|
+
$$
|
|
18
|
+
\bar{X}_{i_1 \dots i_n} = \sum_{j_1 \dots j_m} \bar{Y}_{j_1 \dots j_m} \frac{\partial Y_{j_1 \dots j_m}}{\partial X_{i_1 \dots i_n}}
|
|
19
|
+
$$
|
|
20
|
+
|
|
21
|
+
If X and Y are scalars, indices vanish, and this reduces to:
|
|
22
|
+
|
|
23
|
+
$$
|
|
24
|
+
\bar{x} = \bar{y} \cdot f'(x)
|
|
25
|
+
$$
|
|
26
|
+
|
|
27
|
+
If X and Y are matrices, this reduces to:
|
|
28
|
+
|
|
29
|
+
$$
|
|
30
|
+
\bar{X} = \bar{Y} W^{T}
|
|
31
|
+
$$
|
|
32
|
+
|
|
33
|
+
### 1.2. Graph Topology and Gradient Accumulation
|
|
34
|
+
|
|
35
|
+
Gradients are accumulated using a Depth-First Search (DFS) topological sort, which ensures that for any node $X$ with multiple gradient flow streams ${Y^{(1)}, \dots, Y^{k}}$, the gradient sum is the sum of contractions:
|
|
36
|
+
|
|
37
|
+
$$
|
|
38
|
+
\bar{X} = \sum_{k} \mathrm{VJP}(Y^{(k)}, X)
|
|
39
|
+
$$
|
|
40
|
+
|
|
41
|
+
All gradients are aggregated from all gradient downstreams.
|
|
42
|
+
|
|
43
|
+
## 2. Architecture and System Design
|
|
44
|
+
|
|
45
|
+
### 2.1. The differentiable Primitive (`Tensor`)
|
|
46
|
+
|
|
47
|
+
The `Tensor` class acts like a node in the Directed Acyclic Graph (DAG).
|
|
48
|
+
|
|
49
|
+
Operations are automatically dispatched to backend computers, which consists of `numpy` (CPU) and `cupy` (GPU).
|
|
50
|
+
|
|
51
|
+
Computational graphs are built dynamically at runtime.
|
|
52
|
+
|
|
53
|
+
## 3. Empirical Validation
|
|
54
|
+
|
|
55
|
+
We will verify the tensor engine by minimizing the Rosenbrock function, which is a non-convex optimization benchmark:
|
|
56
|
+
|
|
57
|
+
$$
|
|
58
|
+
f(x, y) = (a - x)^2 + b(y - x^2)^2
|
|
59
|
+
$$
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
import depthtensor as dt
|
|
63
|
+
|
|
64
|
+
# Initialize tensors
|
|
65
|
+
x = dt.Tensor([1.2], device="gpu", requires_grad=True)
|
|
66
|
+
y = dt.Tensor([1.2], device="gpu", requires_grad=True)
|
|
67
|
+
|
|
68
|
+
a, b = dt.Tensor([1], device="gpu"), dt.Tensor(
|
|
69
|
+
[100], device="gpu"
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
# 2. Optimization Loop
|
|
73
|
+
lr = 0.001
|
|
74
|
+
for i in range(500):
|
|
75
|
+
# Rosenbrock: f(x,y) = (a-x)^2 + b(y-x^2)^2
|
|
76
|
+
loss = (a - x) ** 2 + b * (y - x**2) ** 2
|
|
77
|
+
|
|
78
|
+
# Backpward pass
|
|
79
|
+
dt.differentiate(loss)
|
|
80
|
+
|
|
81
|
+
# Gradient Descent
|
|
82
|
+
x.data -= lr * x.grad # type: ignore
|
|
83
|
+
y.data -= lr * y.grad # type: ignore
|
|
84
|
+
|
|
85
|
+
# Zero grads
|
|
86
|
+
x.zeros_grad()
|
|
87
|
+
y.zeros_grad()
|
|
88
|
+
|
|
89
|
+
if i % 10 == 0:
|
|
90
|
+
print(loss.item())
|
|
91
|
+
|
|
92
|
+
print(f"Converged: ({x.data}, {y.data})")
|
|
93
|
+
# Target: (1.0, 1.0)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## 4. Installation
|
|
97
|
+
|
|
98
|
+
Requirements:
|
|
99
|
+
- `numpy`
|
|
100
|
+
- `cupy` (optional: for NVIDIA GPU acceleration)
|
|
101
|
+
|
|
102
|
+
### 4.1. Bash
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
git clone https://github.com/YourUsername/DepthTensor.git
|
|
106
|
+
pip install -e .
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### 4.2. Pip
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
pip install depthtensor
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Author: Le Hong Ha
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "depthtensor"
|
|
7
|
+
version = "2.4.0"
|
|
8
|
+
description = "A Hardware-Accelerated Tensor Computation and Autograd Engine"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
authors = [
|
|
11
|
+
{ name = "Le Hong Ha", email = "lehahong1310@gmail.com" }
|
|
12
|
+
]
|
|
13
|
+
license = { file = "LICENSE" }
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence", # Fixed
|
|
17
|
+
"License :: OSI Approved :: MIT License", # Fixed
|
|
18
|
+
"Operating System :: OS Independent"
|
|
19
|
+
]
|
|
20
|
+
requires-python = ">=3.8"
|
|
21
|
+
dependencies = [
|
|
22
|
+
"numpy"
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[project.optional-dependencies]
|
|
26
|
+
gpu = [
|
|
27
|
+
"cupy"
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
"Homepage" = "https://github.com/l-h-ha/DepthTensor"
|
|
32
|
+
"Bug Tracker" = "https://github.com/l-h-ha/DepthTensor/issues"
|
|
33
|
+
|
|
34
|
+
[tool.setuptools.packages.find]
|
|
35
|
+
where = ["src"]
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
from typing import Callable
|
|
2
|
+
|
|
3
|
+
from ...typing import OperandLike, TensorLike, NDArrayLike, AxisLike
|
|
4
|
+
|
|
5
|
+
from ..utils import sum_to_shape, to_xp_array, get_two_operand_op_device
|
|
6
|
+
from ..exceptions import CuPyNotFound, CUPY_NOT_FOUND_MSG
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import math
|
|
10
|
+
|
|
11
|
+
try:
|
|
12
|
+
import cupy as cp
|
|
13
|
+
except (ImportError, ModuleNotFoundError):
|
|
14
|
+
cp = None
|
|
15
|
+
|
|
16
|
+
###
|
|
17
|
+
###
|
|
18
|
+
###
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def wrapper_2in_diff(
|
|
22
|
+
result: TensorLike,
|
|
23
|
+
x1: OperandLike,
|
|
24
|
+
x2: OperandLike,
|
|
25
|
+
callback_x1: Callable,
|
|
26
|
+
callback_x2: Callable,
|
|
27
|
+
) -> TensorLike:
|
|
28
|
+
if not result.requires_grad:
|
|
29
|
+
return result
|
|
30
|
+
from ...tensor import Tensor
|
|
31
|
+
|
|
32
|
+
def backward() -> None:
|
|
33
|
+
if result.grad is None:
|
|
34
|
+
result.zeros_grad()
|
|
35
|
+
|
|
36
|
+
result_grad: NDArrayLike = result.grad
|
|
37
|
+
device = get_two_operand_op_device(x1, x2, None)
|
|
38
|
+
x1_data, x2_data = to_xp_array(x1, device=device), to_xp_array(
|
|
39
|
+
x2, device=device
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
if isinstance(x1, Tensor) and x1.requires_grad:
|
|
43
|
+
if x1.grad is None:
|
|
44
|
+
x1.zeros_grad()
|
|
45
|
+
x1.grad += callback_x1(
|
|
46
|
+
result_grad, x1.shape, device, x1_data, x2_data
|
|
47
|
+
).astype(x1.dtype)
|
|
48
|
+
if isinstance(x2, Tensor) and x2.requires_grad:
|
|
49
|
+
if x2.grad is None:
|
|
50
|
+
x2.zeros_grad()
|
|
51
|
+
x2.grad += callback_x2(
|
|
52
|
+
result_grad, x2.shape, device, x1_data, x2_data
|
|
53
|
+
).astype(x2.dtype)
|
|
54
|
+
|
|
55
|
+
result.backward = backward
|
|
56
|
+
return result
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def wrapper_1in_diff(
|
|
60
|
+
result: TensorLike, x: OperandLike, callback_x1: Callable
|
|
61
|
+
) -> TensorLike:
|
|
62
|
+
if not result.requires_grad:
|
|
63
|
+
return result
|
|
64
|
+
from ...tensor import Tensor
|
|
65
|
+
|
|
66
|
+
def backward() -> None:
|
|
67
|
+
if result.grad is None:
|
|
68
|
+
result.zeros_grad()
|
|
69
|
+
|
|
70
|
+
result_grad: NDArrayLike = result.grad
|
|
71
|
+
_x = to_xp_array(x)
|
|
72
|
+
if isinstance(x, Tensor) and x.requires_grad:
|
|
73
|
+
if x.grad is None:
|
|
74
|
+
x.zeros_grad()
|
|
75
|
+
x.grad += callback_x1(result_grad, x.shape, x.device, _x)
|
|
76
|
+
|
|
77
|
+
result.backward = backward
|
|
78
|
+
return result
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
###
|
|
82
|
+
### Arithmetics
|
|
83
|
+
###
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def add_diff(result: TensorLike, x1: OperandLike, x2: OperandLike) -> TensorLike:
|
|
87
|
+
def callback_x1(result_grad, x1_shape, device, x1_data, x2_data):
|
|
88
|
+
return sum_to_shape(result_grad, x1_shape, device)
|
|
89
|
+
|
|
90
|
+
def callback_x2(result_grad, x2_shape, device, x1_data, x2_data):
|
|
91
|
+
return sum_to_shape(result_grad, x2_shape, device)
|
|
92
|
+
|
|
93
|
+
return wrapper_2in_diff(result, x1, x2, callback_x1, callback_x2)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def subtract_diff(result: TensorLike, x1: OperandLike, x2: OperandLike) -> TensorLike:
|
|
97
|
+
|
|
98
|
+
def callback_x1(result_grad, x1_shape, device, x1_data, x2_data):
|
|
99
|
+
return sum_to_shape(result_grad, x1_shape, device)
|
|
100
|
+
|
|
101
|
+
def callback_x2(result_grad, x2_shape, device, x1_data, x2_data):
|
|
102
|
+
return sum_to_shape(-result_grad, x2_shape, device)
|
|
103
|
+
|
|
104
|
+
return wrapper_2in_diff(result, x1, x2, callback_x1, callback_x2)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def multiply_diff(result: TensorLike, x1: OperandLike, x2: OperandLike) -> TensorLike:
|
|
108
|
+
|
|
109
|
+
def callback_x1(result_grad, x1_shape, device, x1_data, x2_data):
|
|
110
|
+
return sum_to_shape(result_grad * x2_data, x1_shape, device)
|
|
111
|
+
|
|
112
|
+
def callback_x2(result_grad, x2_shape, device, x1_data, x2_data):
|
|
113
|
+
return sum_to_shape(result_grad * x1_data, x2_shape, device)
|
|
114
|
+
|
|
115
|
+
return wrapper_2in_diff(result, x1, x2, callback_x1, callback_x2)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def matmul_diff(result: TensorLike, x1: OperandLike, x2: OperandLike) -> TensorLike:
|
|
119
|
+
|
|
120
|
+
def callback_x1(result_grad, x1_shape, device, x1_data, x2_data):
|
|
121
|
+
return sum_to_shape(result_grad @ x2_data.swapaxes(-2, -1), x1_shape, device)
|
|
122
|
+
|
|
123
|
+
def callback_x2(result_grad, x2_shape, device, x1_data, x2_data):
|
|
124
|
+
return sum_to_shape(x1_data.swapaxes(-2, -1) @ result_grad, x2_shape, device)
|
|
125
|
+
|
|
126
|
+
return wrapper_2in_diff(result, x1, x2, callback_x1, callback_x2)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def divide_diff(result: TensorLike, x1: OperandLike, x2: OperandLike) -> TensorLike:
|
|
130
|
+
|
|
131
|
+
def callback_x1(result_grad, x1_shape, device, x1_data, x2_data):
|
|
132
|
+
return sum_to_shape(result_grad / x2_data, x1_shape, device)
|
|
133
|
+
|
|
134
|
+
def callback_x2(result_grad, x2_shape, device, x1_data, x2_data):
|
|
135
|
+
return sum_to_shape(result_grad * (x1_data * -(x2_data**-2)), x2_shape, device)
|
|
136
|
+
|
|
137
|
+
return wrapper_2in_diff(result, x1, x2, callback_x1, callback_x2)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def power_diff(result: TensorLike, x1: OperandLike, x2: OperandLike) -> TensorLike:
|
|
141
|
+
|
|
142
|
+
def callback_x1(result_grad, x1_shape, device, x1_data, x2_data):
|
|
143
|
+
return sum_to_shape(
|
|
144
|
+
result_grad * x2_data * x1_data ** (x2_data - 1), x1_shape, device
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
def callback_x2(result_grad, x2_shape, device, x1_data, x2_data):
|
|
148
|
+
if device == "cpu":
|
|
149
|
+
return sum_to_shape(
|
|
150
|
+
result_grad * np.log(x1_data) * x1_data**x2_data, x2_shape, device
|
|
151
|
+
)
|
|
152
|
+
else:
|
|
153
|
+
if cp is None:
|
|
154
|
+
raise CuPyNotFound(CUPY_NOT_FOUND_MSG)
|
|
155
|
+
return sum_to_shape(
|
|
156
|
+
result_grad * cp.log(x1_data) * x1_data**x2_data, x2_shape, device
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
return wrapper_2in_diff(result, x1, x2, callback_x1, callback_x2)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def negative_diff(result: TensorLike, x: TensorLike) -> TensorLike:
|
|
163
|
+
|
|
164
|
+
def callback_x1(result_grad, x1_shape, device, x1_data):
|
|
165
|
+
return sum_to_shape(-result_grad, x1_shape, device)
|
|
166
|
+
|
|
167
|
+
return wrapper_1in_diff(result, x, callback_x1)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def sign_diff(result: TensorLike, x: TensorLike) -> TensorLike:
|
|
171
|
+
|
|
172
|
+
def callback_x1(result_grad, x1_shape, device, x1_data):
|
|
173
|
+
return sum_to_shape(result_grad * 0, x1_shape, device)
|
|
174
|
+
|
|
175
|
+
return wrapper_1in_diff(result, x, callback_x1)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def abs_diff(result: TensorLike, x: TensorLike) -> TensorLike:
|
|
179
|
+
|
|
180
|
+
def callback_x1(result_grad, x1_shape, device, x1_data):
|
|
181
|
+
return sum_to_shape(result_grad * result.data / x1_data, x1_shape, device)
|
|
182
|
+
|
|
183
|
+
return wrapper_1in_diff(result, x, callback_x1)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
###
|
|
187
|
+
### Exponents/Logarithms
|
|
188
|
+
###
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def exp_diff(result: TensorLike, x: TensorLike) -> TensorLike:
|
|
192
|
+
|
|
193
|
+
def callback_x1(result_grad, x1_shape, device, x1_data):
|
|
194
|
+
return sum_to_shape(result_grad * result.data, x1_shape, device)
|
|
195
|
+
|
|
196
|
+
return wrapper_1in_diff(result, x, callback_x1)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def sqrt_diff(result: TensorLike, x: TensorLike) -> TensorLike:
|
|
200
|
+
|
|
201
|
+
def callback_x1(result_grad, x1_shape, device, x1_data):
|
|
202
|
+
return sum_to_shape(
|
|
203
|
+
result_grad * (0.5 * result.data ** (-0.5)), x1_shape, device
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
return wrapper_1in_diff(result, x, callback_x1)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def log_diff(result: TensorLike, x: TensorLike) -> TensorLike:
|
|
210
|
+
|
|
211
|
+
def callback_x1(result_grad, x1_shape, device, x1_data):
|
|
212
|
+
return sum_to_shape(result_grad / x1_data, x1_shape, device)
|
|
213
|
+
|
|
214
|
+
return wrapper_1in_diff(result, x, callback_x1)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def square_diff(result: TensorLike, x: TensorLike) -> TensorLike:
|
|
218
|
+
|
|
219
|
+
def callback_x1(result_grad, x1_shape, device, x1_data):
|
|
220
|
+
return sum_to_shape(result_grad * 2 * x1_data, x1_shape, device)
|
|
221
|
+
|
|
222
|
+
return wrapper_1in_diff(result, x, callback_x1)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
###
|
|
226
|
+
###
|
|
227
|
+
###
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def mean_diff(
|
|
231
|
+
result: TensorLike, x: TensorLike, axis: AxisLike, keepdims: bool
|
|
232
|
+
) -> TensorLike:
|
|
233
|
+
def callback_x1(result_grad, x1_shape, device, _x):
|
|
234
|
+
if device == "cpu":
|
|
235
|
+
xp = np
|
|
236
|
+
else:
|
|
237
|
+
if cp is None:
|
|
238
|
+
raise CuPyNotFound(CUPY_NOT_FOUND_MSG)
|
|
239
|
+
xp = cp
|
|
240
|
+
|
|
241
|
+
inp_size = math.prod(x1_shape)
|
|
242
|
+
grad_size = result_grad.size
|
|
243
|
+
N = inp_size / grad_size
|
|
244
|
+
grad = result_grad * (1.0 / N)
|
|
245
|
+
|
|
246
|
+
if not keepdims and axis is not None:
|
|
247
|
+
grad = xp.expand_dims(grad, axis)
|
|
248
|
+
return xp.broadcast_to(grad, x1_shape)
|
|
249
|
+
|
|
250
|
+
return wrapper_1in_diff(result, x, callback_x1)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
###
|
|
254
|
+
###
|
|
255
|
+
###
|
|
256
|
+
|
|
257
|
+
__all__ = [
|
|
258
|
+
"add_diff",
|
|
259
|
+
"subtract_diff",
|
|
260
|
+
"multiply_diff",
|
|
261
|
+
"matmul_diff",
|
|
262
|
+
"divide_diff",
|
|
263
|
+
"power_diff",
|
|
264
|
+
"negative_diff",
|
|
265
|
+
"sign_diff",
|
|
266
|
+
"abs_diff",
|
|
267
|
+
"exp_diff",
|
|
268
|
+
"sqrt_diff",
|
|
269
|
+
"log_diff",
|
|
270
|
+
"square_diff",
|
|
271
|
+
"mean_diff",
|
|
272
|
+
]
|
|
@@ -5,6 +5,7 @@ from ...typing import (
|
|
|
5
5
|
DTypeLike,
|
|
6
6
|
Casting,
|
|
7
7
|
Order,
|
|
8
|
+
AxisLike,
|
|
8
9
|
NDArrayLikeBool,
|
|
9
10
|
NDArrayLike,
|
|
10
11
|
OperandLike,
|
|
@@ -243,7 +244,7 @@ def wrapper_1in_1out(
|
|
|
243
244
|
from ...tensor import Tensor
|
|
244
245
|
|
|
245
246
|
if device is None:
|
|
246
|
-
device_op = get_device(
|
|
247
|
+
device_op = get_device(x)
|
|
247
248
|
else:
|
|
248
249
|
device_op = device
|
|
249
250
|
|
|
@@ -711,6 +712,54 @@ def square(
|
|
|
711
712
|
)
|
|
712
713
|
|
|
713
714
|
|
|
715
|
+
###
|
|
716
|
+
###
|
|
717
|
+
###
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
def mean(
|
|
721
|
+
x: OperandLike,
|
|
722
|
+
/,
|
|
723
|
+
axis: Optional[AxisLike] = None,
|
|
724
|
+
dtype: Optional[DTypeLike] = None,
|
|
725
|
+
out: Optional[NDArrayLike] = None,
|
|
726
|
+
keepdims: bool = False,
|
|
727
|
+
*,
|
|
728
|
+
device: Optional[DeviceLike] = None,
|
|
729
|
+
in_place: bool = False,
|
|
730
|
+
where: Union[bool, NDArrayLikeBool] = True,
|
|
731
|
+
) -> TensorLike:
|
|
732
|
+
from ...tensor import Tensor
|
|
733
|
+
|
|
734
|
+
if device is None:
|
|
735
|
+
device_op = get_device(x)
|
|
736
|
+
else:
|
|
737
|
+
device_op = device
|
|
738
|
+
|
|
739
|
+
a = to_xp_array(x, device=device_op)
|
|
740
|
+
if device_op == "cpu":
|
|
741
|
+
y = np.mean(
|
|
742
|
+
a,
|
|
743
|
+
out=out,
|
|
744
|
+
dtype=dtype,
|
|
745
|
+
where=where,
|
|
746
|
+
axis=axis,
|
|
747
|
+
keepdims=keepdims,
|
|
748
|
+
)
|
|
749
|
+
else:
|
|
750
|
+
if cp is None:
|
|
751
|
+
raise CuPyNotFound(CUPY_NOT_FOUND_MSG)
|
|
752
|
+
y = cp.mean(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
|
|
753
|
+
|
|
754
|
+
requires_grad = False
|
|
755
|
+
if isinstance(x, Tensor):
|
|
756
|
+
if in_place:
|
|
757
|
+
x.data = y
|
|
758
|
+
return x
|
|
759
|
+
requires_grad = x.requires_grad
|
|
760
|
+
return Tensor(y, prev=(x,), requires_grad=requires_grad)
|
|
761
|
+
|
|
762
|
+
|
|
714
763
|
###
|
|
715
764
|
###
|
|
716
765
|
###
|
|
@@ -729,6 +778,7 @@ __all__ = [
|
|
|
729
778
|
"sqrt",
|
|
730
779
|
"log",
|
|
731
780
|
"square",
|
|
781
|
+
"mean",
|
|
732
782
|
"clip",
|
|
733
783
|
"create_2in_1out",
|
|
734
784
|
"create_1in_1out",
|
|
@@ -151,7 +151,7 @@ def get_device(a: OperandLike) -> DeviceLike:
|
|
|
151
151
|
elif isinstance(a, (int, float, list, tuple, bool)):
|
|
152
152
|
return "cpu"
|
|
153
153
|
else:
|
|
154
|
-
raise RuntimeError("Invalid argument type
|
|
154
|
+
raise RuntimeError(f"Invalid argument type: {type(a)}")
|
|
155
155
|
|
|
156
156
|
|
|
157
157
|
def get_complement_device(device: DeviceLike) -> DeviceLike:
|