DepthTensor 0.0.1__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Lê Hồng Hà
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,10 @@
1
+ Metadata-Version: 2.4
2
+ Name: DepthTensor
3
+ Version: 0.0.1
4
+ License-File: LICENSE
5
+ Requires-Dist: numpy
6
+ Provides-Extra: test
7
+ Requires-Dist: pytest; extra == "test"
8
+ Provides-Extra: gpu
9
+ Requires-Dist: cupy-cuda12x; extra == "gpu"
10
+ Dynamic: license-file
@@ -0,0 +1,14 @@
1
+ # DepthTensor
2
+ This is a NumPy/CuPy wrapper module designed for tensor computations. DepthTensor was created to operate in tandem with another library called Depth, a deep-learning library.
3
+
4
+ # Functionalities
5
+
6
+ * NumPy functionalities (N-dimensional array, broadcasting, etc.)
7
+
8
+ * Auto-differentiation
9
+
10
+ # Installation
11
+
12
+ ```bash
13
+ pip install dtensor
14
+ ```
@@ -0,0 +1,21 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "DepthTensor"
7
+ version = "0.0.1"
8
+ dependencies = [
9
+ "numpy"
10
+ ]
11
+
12
+ [project.optional-dependencies]
13
+ test = [
14
+ "pytest"
15
+ ]
16
+ gpu = [
17
+ "cupy-cuda12x"
18
+ ]
19
+
20
+ [tool.setuptools.packages.find]
21
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,6 @@
1
+ from .cpu import cpu as CPUtensor
2
+ from .gpu import gpu as GPUTensor
3
+ from .autodiff import differentiate
4
+ from .types import *
5
+
6
+ __version__ = "0.0.1"
@@ -0,0 +1,2 @@
1
+ from .api import api
2
+ from .utils import sum_to_shape
@@ -0,0 +1,198 @@
1
+ from __future__ import annotations
2
+ from abc import ABC, abstractmethod
3
+ from typing import Any, Optional, Tuple, Callable, TypeAlias
4
+
5
+ import numpy as np
6
+ try:
7
+ import cupy as cp
8
+ except (ModuleNotFoundError, ImportError):
9
+ cp = None
10
+ DTypeLike: TypeAlias = np.typing.DTypeLike
11
+
12
+ class api(ABC):
13
+ """
14
+ Abstract-base-class numpy / cupy wrapper.
15
+
16
+ Defines behaviors shared by the two libraries.
17
+ """
18
+
19
+ def __init__(self, data: Any, device: str, dtype: Optional[DTypeLike] = None, prev: Tuple = (), requires_grad: bool = False) -> None:
20
+ super().__init__()
21
+ if device == "cpu":
22
+ if isinstance(data, (int, float, list, tuple)):
23
+ data = np.asarray(data)
24
+ elif isinstance(data, (np.ndarray, np.floating, np.integer)):
25
+ data = data
26
+ else:
27
+ if cp is not None:
28
+ if isinstance(data, (cp.ndarray, cp.floating, cp.integer)):
29
+ data = cp.asnumpy(data)
30
+ raise RuntimeError(f"Expected objects of type: int, float, list, tuple, numpy.ndarray, numpy.floating, numpy.integer, cupy.ndarray, cupy.floating, cupy.integer, got: {type(data)}")
31
+ elif device == "gpu":
32
+ if cp is not None:
33
+ if isinstance(data, (int, float, list, tuple)):
34
+ data = cp.asarray(data)
35
+ elif isinstance(data, (cp.ndarray, cp.floating, cp.integer)):
36
+ data = data
37
+ else:
38
+ if isinstance(data, (np.ndarray, np.floating, np.integer)):
39
+ data = cp.asarray(data)
40
+ raise RuntimeError(f"Expected objects of type: int, float, list, tuple, numpy.ndarray, numpy.floating, numpy.integer, cupy.ndarray, cupy.floating, cupy.integer, got: {type(data)}")
41
+ else:
42
+ raise RuntimeError("Module CuPy not found or installed.")
43
+ if dtype is not None and data.dtype != dtype:
44
+ data = data.astype(dtype)
45
+
46
+ self.data = data
47
+ self.device = device
48
+ self.dtype = data.dtype
49
+ self.prev = prev
50
+ self.requires_grad = requires_grad
51
+ self.backward: Optional[Callable[[], None]] = None
52
+
53
+ def get_device(self) -> str:
54
+ return self.device
55
+ def is_device(self, device: str) -> bool:
56
+ return self.device == device
57
+ def is_cpu(self) -> bool:
58
+ return self.device == "cpu"
59
+ def is_gpu(self) -> bool:
60
+ return self.device == "gpu"
61
+
62
+ @property
63
+ def shape(self) -> Tuple:
64
+ return self.data.shape
65
+ @property
66
+ def ndim(self) -> int:
67
+ return self.data.ndim
68
+ @property
69
+ def size(self) -> int:
70
+ return self.data.size
71
+ @property
72
+ def T(self) -> Any:
73
+ raise NotImplementedError
74
+
75
+ ###
76
+ ###
77
+ ###
78
+
79
+ @classmethod
80
+ @abstractmethod
81
+ def zeros_like(cls, a: Any, dtype: Optional[DTypeLike] = None) -> Any:
82
+ raise NotImplementedError
83
+
84
+ @classmethod
85
+ @abstractmethod
86
+ def ones_like(cls, a: Any, dtype: Optional[DTypeLike] = None) -> Any:
87
+ raise NotImplementedError
88
+
89
+ ###
90
+ ###
91
+ ###
92
+
93
+ @abstractmethod
94
+ def add(self, x1: Any, x2: Any, produce_tensor: bool = True) -> Any:
95
+ raise NotImplementedError
96
+ @abstractmethod
97
+ def add_diff(self, result: Any, x1: Any, x2: Any) -> Any:
98
+ raise NotImplementedError
99
+
100
+ @abstractmethod
101
+ def subtract(self, x1: Any, x2: Any, produce_tensor: bool = True) -> Any:
102
+ raise NotImplementedError
103
+ @abstractmethod
104
+ def subtract_diff(self, result: Any, x1: Any, x2: Any) -> Any:
105
+ raise NotImplementedError
106
+
107
+ @abstractmethod
108
+ def multiply(self, x1: Any, x2: Any, produce_tensor: bool = True) -> Any:
109
+ raise NotImplementedError
110
+ @abstractmethod
111
+ def multiply_diff(self, result: Any, x1: Any, x2: Any) -> Any:
112
+ raise NotImplementedError
113
+
114
+ @abstractmethod
115
+ def matmul(self, x1: Any, x2: Any, produce_tensor: bool = True) -> Any:
116
+ raise NotImplementedError
117
+ @abstractmethod
118
+ def matmul_diff(self, result: Any, x1: Any, x2: Any) -> Any:
119
+ raise NotImplementedError
120
+
121
+ @abstractmethod
122
+ def divide(self, x1: Any, x2: Any, produce_tensor: bool = True) -> Any:
123
+ raise NotImplementedError
124
+ @abstractmethod
125
+ def divide_diff(self, result: Any, x1: Any, x2: Any) -> Any:
126
+ raise NotImplementedError
127
+
128
+ ###
129
+ ###
130
+ ###
131
+
132
+ @abstractmethod
133
+ def negative(self, dtype: Optional[DTypeLike] = None, produce_tensor: bool = False) -> Any:
134
+ raise NotImplementedError
135
+
136
+ ###
137
+ ###
138
+ ###
139
+
140
+ def __add__(self: Any, x2: Any) -> Any:
141
+ return self.add(self, x2)
142
+ def __radd__(self: Any, x2: Any) -> Any:
143
+ return self.add(x2, self)
144
+ def __iadd__(self: Any, x2: Any) -> Any:
145
+ self.data = self.add(self, x2, produce_tensor = False)
146
+ return self
147
+
148
+ def __sub__(self: Any, x2: Any) -> Any:
149
+ return self.subtract(self, x2)
150
+ def __rsub__(self: Any, x2: Any) -> Any:
151
+ return self.subtract(x2, self)
152
+ def __isub__(self: Any, x2: Any) -> Any:
153
+ self.data = self.subtract(self, x2, produce_tensor = False)
154
+ return self
155
+
156
+ def __mul__(self: Any, x2: Any) -> Any:
157
+ return self.multiply(self.data, x2)
158
+ def __rmul__(self: Any, x2: Any) -> Any:
159
+ return self.multiply(x2, self.data)
160
+ def __imul__(self: Any, x2: Any) -> Any:
161
+ self.data = self.multiply(self.data, x2, produce_tensor = False)
162
+ return self
163
+
164
+ def __truediv__(self: Any, x2: Any) -> Any:
165
+ return self.divide(self.data, x2)
166
+ def __rtruediv__(self: Any, x2: Any) -> Any:
167
+ return self.divide(x2, self.data)
168
+ def __itruediv__(self: Any, x2: Any) -> Any:
169
+ self.data = self.divide(self.data, x2, produce_tensor = False)
170
+ return self
171
+
172
+ def __matmul__(self: Any, x2: Any) -> Any:
173
+ return self.matmul(self.data, x2)
174
+ def __rmatmul__(self: Any, x2: Any) -> Any:
175
+ return self.matmul(x2, self.data)
176
+ def __imatmul__(self: Any, x2: Any) -> Any:
177
+ self.data = self.matmul(self.data, x2, produce_tensor = False)
178
+ return self
179
+
180
+ ###
181
+ ###
182
+ ###
183
+
184
+ def __neg__(self) -> Any:
185
+ return self.negative()
186
+
187
+ ###
188
+ ###
189
+ ###
190
+
191
+ def __repr__(self) -> str:
192
+ return f"{self.device.upper()}tensor({self.data})"
193
+
194
+ def __getitem__(self, index) -> Any:
195
+ return self.data[index]
196
+
197
+ def __setitem__(self, index, value) -> None:
198
+ self.data[index] = value
@@ -0,0 +1,63 @@
1
+ from typing import Any, Tuple
2
+
3
+ import numpy as np
4
+ try:
5
+ import cupy as cp
6
+ except:
7
+ cp = None
8
+
9
+ CUPY_NOT_FOUND = "Module CuPy not found or installed."
10
+ class CuPyNotFoundError(RuntimeError):
11
+ pass
12
+
13
+ def sum_to_shape(result: Any, target_shape: Tuple, device: str) -> Any:
14
+ """
15
+ Reverses broadcasting to the un-broadcasted shape.
16
+
17
+ When a variable was broadcasted in order to be compatible with the other, e.g. [1.0] + [1.0, 2.0, 3.0], differentiating
18
+ the result w.r.t. the broadcasted variable such that the gradient matches the variable's gradient requires collapsing
19
+ the result's shape down to the variable's.
20
+
21
+ Let's say:
22
+ Scalar A, vector B (1x3)
23
+
24
+ C = A + B (A is broadcasted into a 1x3 vector)
25
+
26
+ In order to calculate A's gradients, per the chain rule, we have to differentiate C w.r.t. A, which gives you a vector
27
+ with the same shape as C's, even though the gradient's shape must match A's.
28
+
29
+ Mathematically, since A influences every components of C, to get the gradient, we would have to sum every connections from
30
+ A to C, which this function generalizes for every cases.
31
+ """
32
+
33
+ result_shape = result.shape
34
+ if result_shape == target_shape:
35
+ return result
36
+
37
+ gained_dims = len(result_shape) - len(target_shape)
38
+ if gained_dims > 0:
39
+ #* We sum for gained dimensions.
40
+ gained_axes = tuple([i for i in range(gained_dims)])
41
+
42
+ if device == "cpu":
43
+ result = np.sum(result, axis=gained_axes)
44
+ elif device == "gpu":
45
+ if cp is None:
46
+ raise CuPyNotFoundError(CUPY_NOT_FOUND)
47
+ result = cp.sum(result, axis=gained_axes)
48
+
49
+ #* Just collapsing the gained dimensions would not be enough, collapsing stretched dimensions is required too.
50
+ stretched_axes = []
51
+ for i, d in enumerate(target_shape):
52
+ if result.ndim == 0:
53
+ continue
54
+ if d == 1 and result.shape[i] > 1:
55
+ stretched_axes.append(i)
56
+ if len(stretched_axes) > 0:
57
+ if device == "cpu":
58
+ result = np.sum(result, axis=tuple(stretched_axes), keepdims=True)
59
+ elif device == "gpu":
60
+ if cp is None:
61
+ raise CuPyNotFoundError(CUPY_NOT_FOUND)
62
+ result = cp.sum(result, axis=tuple(stretched_axes), keepdims=True)
63
+ return result
@@ -0,0 +1,46 @@
1
+ from typing import Union, List, TypeAlias, Optional, Any
2
+
3
+ from . import CPUtensor, GPUTensor
4
+ Tensor: TypeAlias = Union[CPUtensor, GPUTensor]
5
+
6
+ import numpy as np
7
+ try:
8
+ import cupy as cp
9
+ except (ImportError, ModuleNotFoundError):
10
+ cp = None
11
+
12
+ def differentiate(tensor: Tensor, upstream_grad: Optional[Union[Any, Tensor, np.ndarray]] = None) -> List[Tensor]:
13
+ topo: List[Tensor] = []
14
+ visited = set()
15
+
16
+ def build(t: Tensor) -> None:
17
+ if t is visited:
18
+ return
19
+ visited.add(t)
20
+ for prev in t.prev:
21
+ build(prev)
22
+ topo.append(t)
23
+ build(tensor)
24
+ topo.reverse()
25
+
26
+ if upstream_grad is not None:
27
+ if isinstance(upstream_grad, Tensor):
28
+ if not tensor.is_device(upstream_grad.device):
29
+ raise RuntimeError("Upstream gradient must be the same device as the to-be-differentiated tensor's.")
30
+ tensor.grad = upstream_grad.data
31
+ elif isinstance(upstream_grad, np.ndarray) and tensor.is_cpu():
32
+ tensor.grad = upstream_grad
33
+ elif cp is not None and isinstance(upstream_grad, cp.ndarray) and tensor.is_gpu():
34
+ tensor.grad = upstream_grad
35
+ else:
36
+ raise RuntimeError("Upstream gradient must be a numpy/cupy array, or a Tensor.")
37
+ else:
38
+ tensor.grad = tensor.ones_like(tensor.data).data
39
+
40
+ for t in topo:
41
+ if t.backward is None:
42
+ if len(t.prev) > 0:
43
+ raise RuntimeError("Tensor is undifferentiable even though it is expected to; backward method is None.")
44
+ else:
45
+ t.backward()
46
+ return topo
@@ -0,0 +1,133 @@
1
+ from __future__ import annotations
2
+ from typing import Any, Optional, Tuple, Union
3
+
4
+ from ._core.api import api
5
+ from ._core import sum_to_shape
6
+ from .types import DTypeLike
7
+
8
+ import numpy as np
9
+
10
+ class cpu(api):
11
+ def __init__(self, data: Any, dtype: Optional[DTypeLike] = None, prev: Tuple = (), requires_grad: bool = False) -> None:
12
+ super().__init__(data, "cpu", dtype, prev, requires_grad)
13
+ self.grad = np.zeros_like(self.data, self.dtype)
14
+
15
+ @property
16
+ def T(self) -> cpu:
17
+ return cpu(data=self.data.T, dtype=self.dtype)
18
+
19
+ ###
20
+ ###
21
+ ###
22
+
23
+ @classmethod
24
+ def zeros_like(cls, a: Union[cpu, Any], dtype: Optional[DTypeLike] = None) -> Any:
25
+ if isinstance(a, cpu):
26
+ return cls(data=np.zeros_like(a.data, dtype=dtype), dtype=dtype)
27
+ return cls(data=np.zeros_like(a, dtype=dtype), dtype=dtype)
28
+
29
+ @classmethod
30
+ def ones_like(cls, a: Union[cpu, Any], dtype: Optional[DTypeLike] = None) -> Any:
31
+ if isinstance(a, cpu):
32
+ return cls(data=np.ones_like(a.data, dtype=dtype), dtype=dtype)
33
+ return cls(data=np.ones_like(a, dtype=dtype), dtype=dtype)
34
+
35
+
36
+ ###
37
+ ###
38
+ ###
39
+
40
+ def add(self, x1: cpu, x2: cpu, produce_tensor: bool = True) -> Union[cpu, np.ndarray]:
41
+ y = np.add(x1.data, x2.data)
42
+ if produce_tensor:
43
+ return self.add_diff(cpu(data=y, prev=(x1, x2), requires_grad=x1.requires_grad or x2.requires_grad), x1, x2)
44
+ return y
45
+ def add_diff(self, result: cpu, x1: cpu, x2: cpu) -> cpu:
46
+ if not result.requires_grad: return result
47
+ def backward() -> None:
48
+ if x1.requires_grad:
49
+ x1.grad += sum_to_shape(result.grad, x1.shape, result.device)
50
+ if x2.requires_grad:
51
+ x2.grad += sum_to_shape(result.grad, x2.shape, result.device)
52
+ result.backward = backward
53
+ return result
54
+
55
+ def subtract(self, x1: cpu, x2: cpu, produce_tensor: bool = True) -> Union[cpu, np.ndarray]:
56
+ y = np.subtract(x1.data, x2.data)
57
+ if produce_tensor:
58
+ return self.subtract_diff(cpu(data=y, prev=(x1, x2), requires_grad=x1.requires_grad or x2.requires_grad), x1, x2)
59
+ return y
60
+ def subtract_diff(self, result: cpu, x1: cpu, x2: cpu) -> cpu:
61
+ if not result.requires_grad: return result
62
+ def backward() -> None:
63
+ if x1.requires_grad:
64
+ x1.grad += sum_to_shape(result.grad, x1.shape, result.device)
65
+ if x2.requires_grad:
66
+ x2.grad += sum_to_shape(-result.grad, x2.shape, result.device)
67
+ result.backward = backward
68
+ return result
69
+
70
+ def multiply(self, x1: cpu, x2: cpu, produce_tensor: bool = True) -> Union[cpu, np.ndarray]:
71
+ y = np.multiply(x1.data, x2.data)
72
+ if produce_tensor:
73
+ return self.multiply_diff(cpu(data=y, prev=(x1, x2), requires_grad=x1.requires_grad or x2.requires_grad), x1, x2)
74
+ return y
75
+ def multiply_diff(self, result: cpu, x1: cpu, x2: cpu) -> cpu:
76
+ if not result.requires_grad: return result
77
+ def backward() -> None:
78
+ if x1.requires_grad:
79
+ x1.grad += sum_to_shape(result.grad * x2.data, x1.shape, result.device)
80
+ if x2.requires_grad:
81
+ x2.grad += sum_to_shape(result.grad * x1.data, x2.shape, result.device)
82
+ result.backward = backward
83
+ return result
84
+
85
+ def matmul(self, x1: cpu, x2: cpu, produce_tensor: bool = True) -> Union[cpu, np.ndarray]:
86
+ y = np.matmul(x1.data, x2.data)
87
+ if produce_tensor:
88
+ return self.matmul_diff(cpu(data=y, prev=(x1, x2), requires_grad=x1.requires_grad or x2.requires_grad), x1, x2)
89
+ return y
90
+ def matmul_diff(self, result: cpu, x1: cpu, x2: cpu) -> cpu:
91
+ if not result.requires_grad: return result
92
+ def backward() -> None:
93
+ if x1.ndim > 1 and x2.ndim > 1:
94
+ if x1.requires_grad:
95
+ x1.grad += sum_to_shape(result.grad @ x2.data.swapaxes(-2, -1), x1.shape, result.device)
96
+ if x2.requires_grad:
97
+ x2.grad += sum_to_shape(x1.data.swapaxes(-2, -1) @ result.grad, x2.shape, result.device)
98
+ else:
99
+ raise RuntimeError("Performing matrix multiplication requires objects of dimensions higher than a vector.")
100
+ result.backward = backward
101
+ return result
102
+
103
+ def divide(self, x1: cpu, x2: cpu, produce_tensor: bool = True) -> Union[cpu, np.ndarray]:
104
+ y = np.divide(x1.data, x2.data)
105
+ if produce_tensor:
106
+ return self.divide_diff(cpu(data=y, prev=(x1, x2), requires_grad=x1.requires_grad or x2.requires_grad), x1, x2)
107
+ return y
108
+ def divide_diff(self, result: cpu, x1: cpu, x2: cpu) -> cpu:
109
+ if not result.requires_grad: return result
110
+ def backward() -> None:
111
+ if x1.requires_grad:
112
+ x1.grad += sum_to_shape(result.grad / x2.data, x1.shape, result.device)
113
+ if x2.requires_grad:
114
+ x2.grad += sum_to_shape(result.grad * (x1.data * -x2.data**(-2)), x2.shape, result.device)
115
+ result.backward = backward
116
+ return result
117
+
118
+ ###
119
+ ###
120
+ ###
121
+
122
+ def negative(self, dtype: Optional[DTypeLike] = None, produce_tensor: bool = False) -> Any:
123
+ y = -self.data
124
+ if produce_tensor:
125
+ return self.negative_diff(cpu(data=-self.data, dtype=dtype, prev=(self,), requires_grad=self.requires_grad), self)
126
+ return y
127
+ def negative_diff(self, result: cpu, x1: cpu) -> cpu:
128
+ if not result.requires_grad: return result
129
+ def backward() -> None:
130
+ if x1.requires_grad:
131
+ x1.grad += sum_to_shape(result.grad * -1, x1.shape, result.device)
132
+ result.backward = backward
133
+ return result
@@ -0,0 +1,144 @@
1
+ from __future__ import annotations
2
+ from typing import Any, Optional, Tuple, Union
3
+
4
+ from ._core.api import api
5
+ from ._core import sum_to_shape
6
+ from .types import DTypeLike
7
+
8
+ try:
9
+ import cupy as cp
10
+ except (ImportError, ModuleNotFoundError):
11
+ cp = None
12
+ CUPY_NOT_FOUND = "Module CuPy not found or installed."
13
+
14
+ class gpu(api):
15
+ def __init__(self, data: Any, dtype: Optional[DTypeLike] = None, prev: Tuple = (), requires_grad: bool = False) -> None:
16
+ if cp is None: raise RuntimeError(CUPY_NOT_FOUND)
17
+ super().__init__(data, "gpu", dtype, prev, requires_grad)
18
+ self.grad = cp.zeros_like(self.data, self.dtype)
19
+
20
+ @property
21
+ def T(self) -> gpu:
22
+ return gpu(data=self.data.T, dtype=self.dtype)
23
+
24
+ ###
25
+ ###
26
+ ###
27
+
28
+ @classmethod
29
+ def zeros_like(cls, a: Union[gpu, Any], dtype: Optional[DTypeLike] = None) -> Any:
30
+ if cp is None: raise RuntimeError(CUPY_NOT_FOUND)
31
+ if isinstance(a, gpu):
32
+ return cls(data=cp.zeros_like(a.data, dtype=dtype), dtype=dtype)
33
+ return cls(data=cp.zeros_like(a, dtype=dtype), dtype=dtype)
34
+
35
+ @classmethod
36
+ def ones_like(cls, a: Union[gpu, Any], dtype: Optional[DTypeLike] = None) -> Any:
37
+ if cp is None: raise RuntimeError(CUPY_NOT_FOUND)
38
+ if isinstance(a, gpu):
39
+ return cls(data=cp.ones_like(a.data, dtype=dtype), dtype=dtype)
40
+ return cls(data=cp.ones_like(a, dtype=dtype), dtype=dtype)
41
+
42
+ ###
43
+ ###
44
+ ###
45
+
46
+ def add(self, x1: gpu, x2: gpu, produce_tensor: bool = False) -> Union[gpu, Any]:
47
+ if cp is None: raise RuntimeError(CUPY_NOT_FOUND)
48
+ y = cp.add(x1.data, x2.data)
49
+ if produce_tensor:
50
+ return self.add_diff(gpu(data=y, prev=(x1, x2), requires_grad=x1.requires_grad or x2.requires_grad), x1, x2)
51
+ return y
52
+ def add_diff(self, result: gpu, x1: gpu, x2: gpu) -> gpu:
53
+ if not result.requires_grad: return result
54
+ def backward() -> None:
55
+ if x1.requires_grad:
56
+ x1.grad += sum_to_shape(result.grad * 1, x1.shape, result.device)
57
+ if x2.requires_grad:
58
+ x2.grad += sum_to_shape(result.grad * 1, x2.shape, result.device)
59
+ result.backward = backward
60
+ return result
61
+
62
+ def subtract(self, x1: gpu, x2: gpu, produce_tensor: bool = False) -> Union[gpu, Any]:
63
+ if cp is None: raise RuntimeError(CUPY_NOT_FOUND)
64
+ y = cp.subtract(x1.data, x2.data)
65
+ if produce_tensor:
66
+ return self.subtract_diff(gpu(data=y, prev=(x1, x2), requires_grad=x1.requires_grad or x2.requires_grad), x1, x2)
67
+ return y
68
+ def subtract_diff(self, result: gpu, x1: gpu, x2: gpu) -> gpu:
69
+ if not result.requires_grad: return result
70
+ def backward() -> None:
71
+ if x1.requires_grad:
72
+ x1.grad += sum_to_shape(result.grad * 1, x1.shape, result.device)
73
+ if x2.requires_grad:
74
+ x2.grad += sum_to_shape(result.grad * -1, x2.shape, result.device)
75
+ result.backward = backward
76
+ return result
77
+
78
+ def multiply(self, x1: gpu, x2: gpu, produce_tensor: bool = False) -> Union[gpu, Any]:
79
+ if cp is None: raise RuntimeError(CUPY_NOT_FOUND)
80
+ y = cp.multiply(x1.data, x2.data)
81
+ if produce_tensor:
82
+ return self.multiply_diff(gpu(data=y, prev=(x1, x2), requires_grad=x1.requires_grad or x2.requires_grad), x1, x2)
83
+ return y
84
+ def multiply_diff(self, result: gpu, x1: gpu, x2: gpu) -> gpu:
85
+ if not result.requires_grad: return result
86
+ def backward() -> None:
87
+ if x1.requires_grad:
88
+ x1.grad += sum_to_shape(result.grad * x2.data, x1.shape, result.device)
89
+ if x2.requires_grad:
90
+ x2.grad += sum_to_shape(result.grad * x1.data, x2.shape, result.device)
91
+ result.backward = backward
92
+ return result
93
+
94
+ def matmul(self, x1: gpu, x2: gpu, produce_tensor: bool = False) -> Union[gpu, Any]:
95
+ if cp is None: raise RuntimeError(CUPY_NOT_FOUND)
96
+ y = cp.matmul(x1.data, x2.data)
97
+ if produce_tensor:
98
+ return self.matmul_diff(gpu(data=y, prev=(x1, x2), requires_grad=x1.requires_grad or x2.requires_grad), x1, x2)
99
+ return y
100
+ def matmul_diff(self, result: gpu, x1: gpu, x2: gpu) -> gpu:
101
+ if not result.requires_grad: return result
102
+ def backward() -> None:
103
+ if x1.ndim > 1 and x2.ndim > 1:
104
+ if x1.requires_grad:
105
+ x1.grad += sum_to_shape(result.grad @ x2.data.swapaxes(-2, -1), x1.shape, result.device)
106
+ if x2.requires_grad:
107
+ x2.grad += sum_to_shape(x1.data.swapaxes(-2, -1) @ result.grad, x2.shape, result.device)
108
+ else:
109
+ raise RuntimeError("Performing matrix multiplication requires objects of dimensions higher than a vector.")
110
+ result.backward = backward
111
+ return result
112
+
113
+ def divide(self, x1: gpu, x2: gpu, produce_tensor: bool = False) -> Union[gpu, Any]:
114
+ if cp is None: raise RuntimeError(CUPY_NOT_FOUND)
115
+ y = cp.divide(x1.data, x2.data)
116
+ if produce_tensor:
117
+ return self.divide_diff(gpu(data=y, prev=(x1, x2), requires_grad=x1.requires_grad or x2.requires_grad), x1, x2)
118
+ return y
119
+ def divide_diff(self, result: gpu, x1: gpu, x2: gpu) -> gpu:
120
+ if not result.requires_grad: return result
121
+ def backward() -> None:
122
+ if x1.requires_grad:
123
+ x1.grad += sum_to_shape(result.grad / x2.data, x1.shape, result.device)
124
+ if x2.requires_grad:
125
+ x2.grad += sum_to_shape(result.grad * (x1.data * -x2.data**(-2)), x2.shape, result.device)
126
+ result.backward = backward
127
+ return result
128
+
129
+ ###
130
+ ###
131
+ ###
132
+
133
+ def negative(self, dtype: Optional[DTypeLike] = None, produce_tensor: bool = False) -> Any:
134
+ y = -self.data
135
+ if produce_tensor:
136
+ return self.negative_diff(gpu(data=-self.data, dtype=dtype, prev=(self,), requires_grad=self.requires_grad), self)
137
+ return y
138
+ def negative_diff(self, result: gpu, x1: gpu) -> gpu:
139
+ if not result.requires_grad: return result
140
+ def backward() -> None:
141
+ if x1.requires_grad:
142
+ x1.grad += sum_to_shape(result.grad * -1, x1.shape, result.device)
143
+ result.backward = backward
144
+ return result
@@ -0,0 +1,25 @@
1
+ from typing import TypeAlias
2
+ from numpy.typing import DTypeLike as DTypeLike_
3
+ import numpy as np
4
+
5
+ DTypeLike: TypeAlias = DTypeLike_
6
+
7
+ floating: TypeAlias = np.floating
8
+ float16: TypeAlias = np.float16
9
+ float32: TypeAlias = np.float32
10
+ float64: TypeAlias = np.float64
11
+
12
+ integer: TypeAlias = np.integer
13
+ int8: TypeAlias = np.int8
14
+ int16: TypeAlias = np.int16
15
+ int32: TypeAlias = np.int32
16
+ int64: TypeAlias = np.int64
17
+
18
+ double: TypeAlias = np.double
19
+
20
+ __all__ = [
21
+ 'DTypeLike',
22
+ 'floating', 'float16', 'float32', 'float64',
23
+ 'integer', 'int8', 'int16', 'int16', 'int64',
24
+ 'double'
25
+ ]
@@ -0,0 +1,10 @@
1
+ Metadata-Version: 2.4
2
+ Name: DepthTensor
3
+ Version: 0.0.1
4
+ License-File: LICENSE
5
+ Requires-Dist: numpy
6
+ Provides-Extra: test
7
+ Requires-Dist: pytest; extra == "test"
8
+ Provides-Extra: gpu
9
+ Requires-Dist: cupy-cuda12x; extra == "gpu"
10
+ Dynamic: license-file
@@ -0,0 +1,18 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/DepthTensor/__init__.py
5
+ src/DepthTensor/autodiff.py
6
+ src/DepthTensor/cpu.py
7
+ src/DepthTensor/gpu.py
8
+ src/DepthTensor/types.py
9
+ src/DepthTensor.egg-info/PKG-INFO
10
+ src/DepthTensor.egg-info/SOURCES.txt
11
+ src/DepthTensor.egg-info/dependency_links.txt
12
+ src/DepthTensor.egg-info/requires.txt
13
+ src/DepthTensor.egg-info/top_level.txt
14
+ src/DepthTensor/_core/__init__.py
15
+ src/DepthTensor/_core/api.py
16
+ src/DepthTensor/_core/utils.py
17
+ src/example/example.py
18
+ tests/test_tensor.py
@@ -0,0 +1,7 @@
1
+ numpy
2
+
3
+ [gpu]
4
+ cupy-cuda12x
5
+
6
+ [test]
7
+ pytest
@@ -0,0 +1,2 @@
1
+ DepthTensor
2
+ example
@@ -0,0 +1,7 @@
1
+ from ..DepthTensor import CPUtensor, differentiate
2
+
3
+ a = CPUtensor(1.0, requires_grad=True)
4
+ b = CPUtensor(2.0, requires_grad=True)
5
+ c = a + b
6
+ differentiate(c)
7
+ print(a.grad)
@@ -0,0 +1,49 @@
1
+ from DepthTensor import *
2
+
3
+ import numpy as np
4
+ try:
5
+ import cupy as cp
6
+ except:
7
+ cp = None
8
+ import pytest
9
+
10
+ ###
11
+ ###
12
+ ###
13
+
14
+ @pytest.fixture
15
+ def tensor_1_1():
16
+ return CPUtensor(data=1, dtype=float64, requires_grad=True)
17
+
18
+ @pytest.fixture
19
+ def tensor_1_2():
20
+ return CPUtensor(data=1., dtype=float16, requires_grad=True)
21
+
22
+ @pytest.fixture
23
+ def tensor_1_3():
24
+ return CPUtensor(data=[1., 2., 3.], dtype=float16, requires_grad=True)
25
+
26
+ ###
27
+ ###
28
+ ###
29
+
30
+ def test_attr(
31
+ tensor_1_1: CPUtensor,
32
+ tensor_1_2: CPUtensor,
33
+ tensor_1_3: CPUtensor
34
+ ):
35
+
36
+ assert isinstance(tensor_1_1.data, np.ndarray)
37
+ assert tensor_1_1.dtype == float64
38
+ assert tensor_1_1.data.dtype == float64
39
+ assert tensor_1_1.requires_grad == True
40
+
41
+ assert isinstance(tensor_1_2.data, np.ndarray)
42
+ assert tensor_1_2.dtype == float16
43
+ assert tensor_1_2.data.dtype == float16
44
+ assert tensor_1_2.requires_grad == True
45
+
46
+ assert isinstance(tensor_1_3.data, np.ndarray)
47
+ assert tensor_1_3.dtype == float16
48
+ assert tensor_1_3.data.dtype == float16
49
+ assert tensor_1_3.requires_grad == True