DepthML 0.1.0__tar.gz → 0.2.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.
Files changed (68) hide show
  1. {depthml-0.1.0 → depthml-0.2.0}/LICENSE +1 -1
  2. depthml-0.2.0/PKG-INFO +44 -0
  3. depthml-0.2.0/README.md +35 -0
  4. {depthml-0.1.0 → depthml-0.2.0}/pyproject.toml +1 -1
  5. depthml-0.2.0/src/DepthML/__init__.py +10 -0
  6. depthml-0.2.0/src/DepthML/activations/__init__.py +2 -0
  7. depthml-0.2.0/src/DepthML/activations/base_activation.py +23 -0
  8. depthml-0.2.0/src/DepthML/activations/common_activations.py +264 -0
  9. depthml-0.2.0/src/DepthML/block.py +58 -0
  10. depthml-0.2.0/src/DepthML/initializers/__init__.py +4 -0
  11. depthml-0.2.0/src/DepthML/initializers/base_initializer.py +37 -0
  12. depthml-0.2.0/src/DepthML/initializers/glorot.py +50 -0
  13. depthml-0.2.0/src/DepthML/initializers/kaiming.py +71 -0
  14. depthml-0.2.0/src/DepthML/initializers/zeros.py +20 -0
  15. depthml-0.2.0/src/DepthML/layers/__init__.py +5 -0
  16. depthml-0.2.0/src/DepthML/layers/base_layer.py +9 -0
  17. depthml-0.2.0/src/DepthML/layers/conv2d.py +410 -0
  18. depthml-0.2.0/src/DepthML/layers/flatten.py +59 -0
  19. depthml-0.2.0/src/DepthML/layers/input.py +28 -0
  20. depthml-0.2.0/src/DepthML/layers/linear.py +114 -0
  21. depthml-0.2.0/src/DepthML/losses/__init__.py +4 -0
  22. depthml-0.2.0/src/DepthML/losses/base_loss.py +26 -0
  23. depthml-0.2.0/src/DepthML/losses/categorical_cross_entropy.py +81 -0
  24. depthml-0.2.0/src/DepthML/losses/mean_squared_error.py +70 -0
  25. depthml-0.2.0/src/DepthML/losses/softmax_categorical_cross_entropy.py +83 -0
  26. depthml-0.2.0/src/DepthML/models/__init__.py +2 -0
  27. depthml-0.2.0/src/DepthML/models/base_model.py +17 -0
  28. depthml-0.2.0/src/DepthML/models/sequential.py +80 -0
  29. depthml-0.2.0/src/DepthML/optimizers/__init__.py +2 -0
  30. depthml-0.2.0/src/DepthML/optimizers/base_optimizer.py +24 -0
  31. depthml-0.2.0/src/DepthML/optimizers/sgd.py +44 -0
  32. depthml-0.2.0/src/DepthML/typing.py +20 -0
  33. depthml-0.2.0/src/DepthML/utils/__init__.py +2 -0
  34. depthml-0.2.0/src/DepthML/utils/clip_grad_norm.py +22 -0
  35. depthml-0.2.0/src/DepthML/utils/get_xp.py +14 -0
  36. depthml-0.2.0/src/DepthML.egg-info/PKG-INFO +44 -0
  37. depthml-0.2.0/src/DepthML.egg-info/SOURCES.txt +39 -0
  38. depthml-0.1.0/PKG-INFO +0 -8
  39. depthml-0.1.0/README.md +0 -0
  40. depthml-0.1.0/src/DepthML/__init__.py +0 -5
  41. depthml-0.1.0/src/DepthML/components/__init__.py +0 -3
  42. depthml-0.1.0/src/DepthML/components/activation/__init__.py +0 -3
  43. depthml-0.1.0/src/DepthML/components/activation/base_activation.py +0 -19
  44. depthml-0.1.0/src/DepthML/components/activation/identity.py +0 -27
  45. depthml-0.1.0/src/DepthML/components/activation/leaky_relu.py +0 -32
  46. depthml-0.1.0/src/DepthML/components/activation/relu.py +0 -28
  47. depthml-0.1.0/src/DepthML/components/base_component.py +0 -19
  48. depthml-0.1.0/src/DepthML/components/layer/__init__.py +0 -1
  49. depthml-0.1.0/src/DepthML/components/layer/affine.py +0 -25
  50. depthml-0.1.0/src/DepthML/components/layer/base_layer.py +0 -23
  51. depthml-0.1.0/src/DepthML/components/loss/__init__.py +0 -1
  52. depthml-0.1.0/src/DepthML/components/loss/base_loss.py +0 -24
  53. depthml-0.1.0/src/DepthML/components/loss/mean_squared_error.py +0 -14
  54. depthml-0.1.0/src/DepthML/initializers/__init__.py +0 -4
  55. depthml-0.1.0/src/DepthML/initializers/base_initializer.py +0 -33
  56. depthml-0.1.0/src/DepthML/initializers/he.py +0 -16
  57. depthml-0.1.0/src/DepthML/initializers/uniform.py +0 -15
  58. depthml-0.1.0/src/DepthML/initializers/xavier.py +0 -16
  59. depthml-0.1.0/src/DepthML/models/__init__.py +0 -1
  60. depthml-0.1.0/src/DepthML/models/base_model.py +0 -23
  61. depthml-0.1.0/src/DepthML/models/stack.py +0 -57
  62. depthml-0.1.0/src/DepthML/typing.py +0 -19
  63. depthml-0.1.0/src/DepthML.egg-info/PKG-INFO +0 -8
  64. depthml-0.1.0/src/DepthML.egg-info/SOURCES.txt +0 -31
  65. {depthml-0.1.0 → depthml-0.2.0}/setup.cfg +0 -0
  66. {depthml-0.1.0 → depthml-0.2.0}/src/DepthML.egg-info/dependency_links.txt +0 -0
  67. {depthml-0.1.0 → depthml-0.2.0}/src/DepthML.egg-info/requires.txt +0 -0
  68. {depthml-0.1.0 → depthml-0.2.0}/src/DepthML.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2025 Lê Hồng Hà
3
+ Copyright (c) 2025 Ha Hong Le
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
depthml-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.4
2
+ Name: DepthML
3
+ Version: 0.2.0
4
+ Description-Content-Type: text/markdown
5
+ License-File: LICENSE
6
+ Requires-Dist: numpy>=2.3.1
7
+ Requires-Dist: depthtensor>=2.0.2
8
+ Dynamic: license-file
9
+
10
+ # DepthML: A Deep Learning Framework
11
+
12
+ DepthML is a high-performance, Pythonic deep learning framework, which provides a hybrid structure (**Keras-like** lazy initialization combined with **PyTorch-like** imperative programming), while delegating all low-level tensor calculus to the [DepthTensor](http) backend.
13
+
14
+ ## Features
15
+
16
+ - Hybrid Object-Oriented API: Incorporates design paradigms present in both Keras and PyTorch.
17
+
18
+ - Hardware Agnostic: Easily switches between the CPU (numpy) and the GPU (cupy) via the DepthTensor backend.
19
+
20
+ ## Benchmarks
21
+
22
+ DepthML is capable of training standard architectures.
23
+
24
+ **Task**: MNIST Digit Classifcation (60k samples)
25
+
26
+ **Architecture**: 3-Layer MLP (784 -> 32 -> 10)
27
+
28
+ **Hardware**: NVIDIA GPU
29
+
30
+ | Metric | Result |
31
+ | -------------- | ------ |
32
+ | Final Accuracy | 93.86% |
33
+ | Training Time (5 epochs) | ~45 seconds |
34
+ | Average Step Time | 7.4 ms |
35
+ | Convergence | < 2 epochs |
36
+
37
+ This framework achieves within 3x the step-latency of optimized C++ frameworks for small-scale MLPs.
38
+
39
+ ## Installation
40
+
41
+ ```bash
42
+ pip install depthml
43
+ ```
44
+
@@ -0,0 +1,35 @@
1
+ # DepthML: A Deep Learning Framework
2
+
3
+ DepthML is a high-performance, Pythonic deep learning framework, which provides a hybrid structure (**Keras-like** lazy initialization combined with **PyTorch-like** imperative programming), while delegating all low-level tensor calculus to the [DepthTensor](http) backend.
4
+
5
+ ## Features
6
+
7
+ - Hybrid Object-Oriented API: Incorporates design paradigms present in both Keras and PyTorch.
8
+
9
+ - Hardware Agnostic: Easily switches between the CPU (numpy) and the GPU (cupy) via the DepthTensor backend.
10
+
11
+ ## Benchmarks
12
+
13
+ DepthML is capable of training standard architectures.
14
+
15
+ **Task**: MNIST Digit Classifcation (60k samples)
16
+
17
+ **Architecture**: 3-Layer MLP (784 -> 32 -> 10)
18
+
19
+ **Hardware**: NVIDIA GPU
20
+
21
+ | Metric | Result |
22
+ | -------------- | ------ |
23
+ | Final Accuracy | 93.86% |
24
+ | Training Time (5 epochs) | ~45 seconds |
25
+ | Average Step Time | 7.4 ms |
26
+ | Convergence | < 2 epochs |
27
+
28
+ This framework achieves within 3x the step-latency of optimized C++ frameworks for small-scale MLPs.
29
+
30
+ ## Installation
31
+
32
+ ```bash
33
+ pip install depthml
34
+ ```
35
+
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "DepthML"
7
- version = "0.1.0"
7
+ version = "0.2.0"
8
8
  readme = "README.md"
9
9
  dependencies = [
10
10
  "numpy>=2.3.1",
@@ -0,0 +1,10 @@
1
+ from DepthTensor import Tensor
2
+
3
+ from .layers import *
4
+ from .models import *
5
+ from .activations import *
6
+ from .losses import *
7
+ from .optimizers import *
8
+ from .utils import *
9
+
10
+ __version__ = "0.2.0"
@@ -0,0 +1,2 @@
1
+ from .base_activation import BaseActivation
2
+ from .common_activations import *
@@ -0,0 +1,23 @@
1
+ from typing import Any
2
+ from ..layers import BaseLayer
3
+ from ..typing import tensor_types
4
+
5
+
6
+ class BaseActivation(BaseLayer):
7
+ def __init__(self, name: str = "activation") -> None:
8
+ super().__init__(name=name, trainable=False)
9
+ self.built = True
10
+
11
+ ###
12
+ ### Block abstracts
13
+ ###
14
+
15
+ def build(
16
+ self, input_shape: tuple[int, ...], device: tensor_types.Device, **kwargs: Any
17
+ ) -> None:
18
+ pass
19
+
20
+ def compute_output_shape(
21
+ self, input_shape: tuple[int, ...], **kwargs
22
+ ) -> tuple[int, ...]:
23
+ return input_shape
@@ -0,0 +1,264 @@
1
+ from typing import Any
2
+
3
+ from .base_activation import BaseActivation
4
+ from ..utils import get_xp
5
+
6
+ from DepthTensor import Tensor, TensorData, Function
7
+
8
+
9
+ class SigmoidFunc(Function):
10
+ def link(self, y: Tensor, x: TensorData) -> None:
11
+ def backward() -> None:
12
+ if isinstance(x, Tensor):
13
+ if x.grad is None:
14
+ x.zero_grad()
15
+ if y.grad is None:
16
+ y.zero_grad()
17
+
18
+ # dy/dx = y * (1 - y)
19
+ x.grad += y.grad * (y.data * (1.0 - y.data)) # type: ignore
20
+
21
+ y.prev = (x,)
22
+ y.backward = backward
23
+
24
+ def __call__(self, x: Tensor) -> Tensor:
25
+ xp = get_xp(x)
26
+ y_data = xp.where(
27
+ x >= 0, 1.0 / (1.0 + xp.exp(-x)), xp.exp(x) / (1.0 + xp.exp(x))
28
+ )
29
+ y = Tensor(y_data, requires_grad=x.requires_grad)
30
+ if y.requires_grad:
31
+ self.link(y, x)
32
+ return y
33
+
34
+
35
+ class TanhFunc(Function):
36
+ def link(self, y: Tensor, x: TensorData) -> None:
37
+ def backward() -> None:
38
+ if isinstance(x, Tensor):
39
+ if x.grad is None:
40
+ x.zero_grad()
41
+ if y.grad is None:
42
+ y.zero_grad()
43
+
44
+ # dy/dx = 1 - y^2
45
+ x.grad += y.grad * (1.0 - y.data**2) # type: ignore
46
+
47
+ y.prev = (x,)
48
+ y.backward = backward
49
+
50
+ def __call__(self, x: Tensor) -> Tensor:
51
+ xp = get_xp(x)
52
+ y_data = xp.tanh(x)
53
+ y = Tensor(y_data, requires_grad=x.requires_grad)
54
+ if y.requires_grad:
55
+ self.link(y, x)
56
+ return y
57
+
58
+
59
+ class ReLUFunc(Function):
60
+ def link(self, y: Tensor, x: TensorData) -> None:
61
+ def backward() -> None:
62
+ if isinstance(x, Tensor):
63
+ if x.grad is None:
64
+ x.zero_grad()
65
+ if y.grad is None:
66
+ y.zero_grad()
67
+
68
+ # dy/dx = 1 if x > 0 else 0
69
+ x.grad += y.grad * (x.data > 0).astype(x.data.dtype)
70
+
71
+ y.prev = (x,)
72
+ y.backward = backward
73
+
74
+ def __call__(self, x: Tensor) -> Tensor:
75
+ xp = get_xp(x)
76
+ y_data = xp.maximum(x, 0)
77
+ y = Tensor(y_data, requires_grad=x.requires_grad)
78
+ if y.requires_grad:
79
+ self.link(y, x)
80
+ return y
81
+
82
+
83
+ class LeakyReLUFunc(Function):
84
+ def link(self, y: Tensor, x: TensorData, alpha: float) -> None:
85
+ def backward() -> None:
86
+ if isinstance(x, Tensor):
87
+ if x.grad is None:
88
+ x.zero_grad()
89
+ if y.grad is None:
90
+ y.zero_grad()
91
+
92
+ xp = get_xp(x.data)
93
+ # dy/dx = 1 if x > 0 else alpha
94
+ grad_mask = xp.where(x.data > 0, 1.0, alpha)
95
+ x.grad += y.grad * grad_mask
96
+
97
+ y.prev = (x,)
98
+ y.backward = backward
99
+
100
+ def __call__(
101
+ self, x: Tensor, alpha: float = 0.01, differentiate: bool = False
102
+ ) -> Tensor:
103
+ xp = get_xp(x)
104
+ y_data = xp.maximum(x, x * alpha)
105
+ y = Tensor(y_data, requires_grad=x.requires_grad)
106
+ if y.requires_grad:
107
+ self.link(y, x, alpha)
108
+ return y
109
+
110
+
111
+ class ELUFunc(Function):
112
+ def link(self, y: Tensor, x: TensorData, alpha: float) -> None:
113
+ def backward() -> None:
114
+ if isinstance(x, Tensor):
115
+ if x.grad is None:
116
+ x.zero_grad()
117
+ if y.grad is None:
118
+ y.zero_grad()
119
+
120
+ xp = get_xp(x.data)
121
+ # dy/dx = 1 if x > 0 else alpha * exp(x) (which is y + alpha)
122
+ grad_input = xp.where(x.data > 0, 1.0, y.data + alpha)
123
+ x.grad += y.grad * grad_input
124
+
125
+ y.prev = (x,)
126
+ y.backward = backward
127
+
128
+ def __call__(
129
+ self, x: Tensor, alpha: float = 1.0, differentiate: bool = False
130
+ ) -> Tensor:
131
+ xp = get_xp(x)
132
+ # y = x if x > 0 else alpha * (exp(x) - 1)
133
+ y_data = xp.where(x > 0, x, alpha * (xp.exp(x) - 1))
134
+ y = Tensor(y_data, requires_grad=x.requires_grad)
135
+ if y.requires_grad:
136
+ self.link(y, x, alpha)
137
+ return y
138
+
139
+
140
+ class GELUFunc(Function):
141
+ """
142
+ Gaussian Error Linear Unit.
143
+ Approximation: 0.5 * x * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x^3)))
144
+ """
145
+
146
+ def link(self, y: Tensor, x: TensorData) -> None:
147
+ def backward() -> None:
148
+ if isinstance(x, Tensor):
149
+ if x.grad is None:
150
+ x.zero_grad()
151
+ if y.grad is None:
152
+ y.zero_grad()
153
+
154
+ xp = get_xp(x.data)
155
+ s = x.data / xp.sqrt(2)
156
+ # Tanh approx derivative:
157
+ tanh_val = xp.tanh(0.7978845608 * (x.data + 0.044715 * x.data**3))
158
+
159
+ coeff = 0.5 * (1 + tanh_val)
160
+ inner_deriv = 0.7978845608 * (1 + 3 * 0.044715 * x.data**2)
161
+ sech_sq = 1.0 - tanh_val**2
162
+
163
+ dydx = coeff + (0.5 * x.data * sech_sq * inner_deriv)
164
+ x.grad += y.grad * dydx
165
+
166
+ y.prev = (x,)
167
+ y.backward = backward
168
+
169
+ def __call__(self, x: Tensor) -> Tensor:
170
+ xp = get_xp(x)
171
+ # sqrt(2/pi) ~= 0.7978845608
172
+ inner = 0.7978845608 * (x + 0.044715 * x**3)
173
+ y_data = 0.5 * x * (1.0 + xp.tanh(inner))
174
+ y = Tensor(y_data, requires_grad=x.requires_grad)
175
+ if y.requires_grad:
176
+ self.link(y, x)
177
+ return y
178
+
179
+
180
+ class SoftmaxFunc(Function):
181
+ def link(self, y: Tensor, x: TensorData, axis: int) -> None:
182
+ def backward() -> None:
183
+ if isinstance(x, Tensor):
184
+ if x.grad is None:
185
+ x.zero_grad()
186
+ if y.grad is None:
187
+ y.zero_grad()
188
+
189
+ xp = get_xp(y.data)
190
+ # y * (grad - sum(grad * y))
191
+ prod = xp.sum(y.grad * y.data, axis=axis, keepdims=True)
192
+ x.grad += y.data * (y.grad - prod)
193
+
194
+ y.prev = (x,)
195
+ y.backward = backward
196
+
197
+ def __call__(self, x: Tensor, axis: int = -1) -> Tensor:
198
+ xp = get_xp(x)
199
+ x_max = xp.max(x, axis=axis, keepdims=True)
200
+ exp_x = xp.exp(x - x_max)
201
+ y_data = exp_x / xp.sum(exp_x, axis=axis, keepdims=True)
202
+ y = Tensor(y_data, requires_grad=x.requires_grad)
203
+ if x.requires_grad:
204
+ self.link(y, x, axis)
205
+ return y
206
+
207
+
208
+ sigmoid_op = SigmoidFunc()
209
+ tanh_op = TanhFunc()
210
+ relu_op = ReLUFunc()
211
+ leaky_relu_op = LeakyReLUFunc()
212
+ elu_op = ELUFunc()
213
+ gelu_op = GELUFunc()
214
+ softmax_op = SoftmaxFunc()
215
+
216
+
217
+ class Sigmoid(BaseActivation):
218
+ def __call__(self, X: Tensor, **kwargs: Any) -> Tensor:
219
+ return sigmoid_op(X)
220
+
221
+
222
+ class Tanh(BaseActivation):
223
+ def __call__(self, X: Tensor, **kwargs: Any) -> Tensor:
224
+ return tanh_op(X)
225
+
226
+
227
+ class ReLU(BaseActivation):
228
+ def __call__(self, X: Tensor, **kwargs: Any) -> Tensor:
229
+ return relu_op(X)
230
+
231
+
232
+ class LeakyReLU(BaseActivation):
233
+ def __init__(self, alpha: float = 0.01, name: str = "leaky_relu") -> None:
234
+ super().__init__(name)
235
+ self.alpha = alpha
236
+
237
+ def __call__(self, X: Tensor, **kwargs: Any) -> Tensor:
238
+ return leaky_relu_op(X, alpha=self.alpha)
239
+
240
+
241
+ class ELU(BaseActivation):
242
+ def __init__(self, alpha: float = 1.0, name: str = "elu") -> None:
243
+ super().__init__(name)
244
+ self.alpha = alpha
245
+
246
+ def __call__(self, X: Tensor, **kwargs: Any) -> Tensor:
247
+ return elu_op(X, alpha=self.alpha)
248
+
249
+
250
+ class GELU(BaseActivation):
251
+ def __call__(self, X: Tensor, **kwargs: Any) -> Tensor:
252
+ return gelu_op(X)
253
+
254
+
255
+ class Softmax(BaseActivation):
256
+ def __init__(self, axis: int = -1, name: str = "softmax") -> None:
257
+ super().__init__(name)
258
+ self.axis = axis
259
+
260
+ def __call__(self, X: Tensor, **kwargs: Any) -> Tensor:
261
+ return softmax_op(X, axis=self.axis)
262
+
263
+
264
+ __all__ = ["Sigmoid", "Tanh", "ReLU", "LeakyReLU", "ELU", "GELU", "Softmax"]
@@ -0,0 +1,58 @@
1
+ from __future__ import annotations
2
+ from abc import ABC, abstractmethod
3
+ from collections import abc, OrderedDict
4
+ from typing import Any
5
+ from .typing import tensor_types
6
+
7
+ from DepthTensor import Tensor
8
+
9
+
10
+ class Block(ABC):
11
+ def __init__(self, name: str = "block", trainable: bool = True) -> None:
12
+ super().__init__()
13
+ self._parameters = OrderedDict()
14
+ self._blocks = OrderedDict()
15
+
16
+ self.name = name
17
+ self.trainable = trainable
18
+ self.built = False
19
+
20
+ @abstractmethod
21
+ def build(
22
+ self,
23
+ input_shape: tuple[int, ...],
24
+ device: tensor_types.Device,
25
+ **kwargs: Any,
26
+ ) -> None:
27
+ raise NotImplementedError
28
+
29
+ @abstractmethod
30
+ def compute_output_shape(self, input_shape: tuple[int, ...], **kwargs: Any) -> Any:
31
+ raise NotImplementedError
32
+
33
+ def parameters(self, include_name: bool = False, prefix: str = "") -> abc.Iterator:
34
+ for name, param in self._parameters.items():
35
+ if include_name:
36
+ yield f"{prefix}{name}", param
37
+ else:
38
+ yield param
39
+
40
+ for name, block in self._blocks.items():
41
+ yield from block.parameters(
42
+ include_name=include_name, prefix=f"{prefix}{name}/"
43
+ )
44
+
45
+ def __setattr__(self, name: str, value: Any) -> None:
46
+ if isinstance(value, Tensor):
47
+ if not self.trainable:
48
+ raise RuntimeError(
49
+ "Attempted to set a trainable tensor as an attribute of an untrainable block."
50
+ )
51
+ self._parameters[name] = value
52
+ elif isinstance(value, Block):
53
+ self._blocks[name] = value
54
+ super().__setattr__(name, value)
55
+
56
+ @abstractmethod
57
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
58
+ raise NotImplementedError
@@ -0,0 +1,4 @@
1
+ from .base_initializer import BaseInitializer
2
+ from .glorot import GlorotNormal, GlorotUniform
3
+ from .kaiming import KaimingNormal, KaimingUniform
4
+ from .zeros import Zeros
@@ -0,0 +1,37 @@
1
+ from abc import abstractmethod
2
+ from ..typing import tensor_types
3
+
4
+ from DepthTensor import Tensor
5
+
6
+
7
+ class BaseInitializer:
8
+ def __init__(self, name: str = "initializer") -> None:
9
+ self.name = name
10
+
11
+ @abstractmethod
12
+ def __call__(
13
+ self,
14
+ shape: tensor_types.Shape,
15
+ device: tensor_types.Device,
16
+ requires_grad: bool,
17
+ ) -> Tensor:
18
+ raise NotImplementedError
19
+
20
+ def compute_fans(self, shape: tensor_types.Shape) -> tuple[float, float]:
21
+ if len(shape) == 2:
22
+ # linear Layer: (in, out)
23
+ fan_in = shape[0]
24
+ fan_out = shape[1]
25
+ elif len(shape) == 4:
26
+ # conv Layer: (out_channels, in_channels, kH, kW)
27
+ # fan_in = in_channels * kH * kW
28
+ # fan_out = out_channels * kH * kW
29
+ size = shape[2] * shape[3]
30
+ fan_in = shape[1] * size
31
+ fan_out = shape[0] * size
32
+ else:
33
+ # fallback for 1D or other shapes
34
+ fan_in = shape[0]
35
+ fan_out = shape[0]
36
+
37
+ return fan_in, fan_out
@@ -0,0 +1,50 @@
1
+ from DepthTensor.typing import Shape, Device
2
+ from .base_initializer import BaseInitializer
3
+
4
+ from DepthTensor import Tensor, random, DTypeLike, float32
5
+
6
+ import numpy as np
7
+
8
+
9
+ class GlorotUniform(BaseInitializer):
10
+ def __init__(self, name: str = "glorot_uniform") -> None:
11
+ super().__init__(name)
12
+
13
+ def __call__(
14
+ self,
15
+ shape: Shape,
16
+ device: Device,
17
+ requires_grad: bool,
18
+ dtype: DTypeLike = float32,
19
+ ) -> Tensor:
20
+ fan_in, fan_out = self.compute_fans(shape)
21
+ limit = np.sqrt(6.0 / (fan_in + fan_out))
22
+ return random.uniform(
23
+ low=-limit,
24
+ high=limit,
25
+ size=shape,
26
+ device=device,
27
+ requires_grad=requires_grad,
28
+ dtype=dtype,
29
+ )
30
+
31
+
32
+ class GlorotNormal(BaseInitializer):
33
+ def __init__(self, name: str = "glorot_normal") -> None:
34
+ super().__init__(name)
35
+
36
+ def __call__(
37
+ self,
38
+ shape: Shape,
39
+ device: Device,
40
+ requires_grad: bool,
41
+ dtype: DTypeLike = float32,
42
+ ) -> Tensor:
43
+ fan_in, fan_out = self.compute_fans(shape)
44
+ std = np.sqrt(2.0 / (fan_in + fan_out), dtype=dtype)
45
+ return (
46
+ random.randn(
47
+ *shape, device=device, requires_grad=requires_grad, dtype=dtype
48
+ )
49
+ * std
50
+ )
@@ -0,0 +1,71 @@
1
+ from typing import Literal, TypeAlias
2
+ from DepthTensor.typing import Shape, Device
3
+ from .base_initializer import BaseInitializer
4
+ from DepthTensor import Tensor, random, DTypeLike, float32
5
+ import numpy as np
6
+
7
+ FanMode: TypeAlias = Literal["fan_in", "fan_out"]
8
+
9
+
10
+ class KaimingUniform(BaseInitializer):
11
+ def __init__(
12
+ self,
13
+ a: float = 0,
14
+ mode: FanMode = "fan_in",
15
+ name: str = "kaiming_uniform",
16
+ ) -> None:
17
+ super().__init__(name)
18
+ self.a = a
19
+ self.mode = mode
20
+
21
+ def __call__(
22
+ self,
23
+ shape: Shape,
24
+ device: Device,
25
+ requires_grad: bool,
26
+ dtype: DTypeLike = float32,
27
+ ) -> Tensor:
28
+ fan_in, fan_out = self.compute_fans(shape)
29
+ fan = fan_in if self.mode == "fan_in" else fan_out
30
+ gain = np.sqrt(2.0 / (1 + self.a**2))
31
+ std = gain / np.sqrt(fan)
32
+ limit = np.sqrt(3.0) * std
33
+
34
+ return random.uniform(
35
+ low=-limit,
36
+ high=limit,
37
+ size=shape,
38
+ device=device,
39
+ requires_grad=requires_grad,
40
+ dtype=dtype,
41
+ )
42
+
43
+
44
+ class KaimingNormal(BaseInitializer):
45
+ def __init__(
46
+ self,
47
+ a: float = 0,
48
+ mode: FanMode = "fan_in",
49
+ name: str = "kaiming_normal",
50
+ ) -> None:
51
+ super().__init__(name)
52
+ self.a = a
53
+ self.mode = mode
54
+
55
+ def __call__(
56
+ self,
57
+ shape: Shape,
58
+ device: Device,
59
+ requires_grad: bool,
60
+ dtype: DTypeLike = float32,
61
+ ) -> Tensor:
62
+ fan_in, fan_out = self.compute_fans(shape)
63
+ fan = fan_in if self.mode == "fan_in" else fan_out
64
+ gain = np.sqrt(2.0 / (1 + self.a**2), dtype=dtype)
65
+ std = gain / np.sqrt(fan, dtype=dtype)
66
+ return (
67
+ random.randn(
68
+ *shape, device=device, requires_grad=requires_grad, dtype=dtype
69
+ )
70
+ * std
71
+ )
@@ -0,0 +1,20 @@
1
+ from DepthTensor.typing import Shape, Device
2
+ from .base_initializer import BaseInitializer
3
+
4
+ from DepthTensor import Tensor, zeros, DTypeLike, float32
5
+
6
+
7
+ class Zeros(BaseInitializer):
8
+ def __init__(self, name: str = "zeros") -> None:
9
+ super().__init__(name)
10
+
11
+ def __call__(
12
+ self,
13
+ shape: Shape,
14
+ device: Device,
15
+ requires_grad: bool,
16
+ dtype: DTypeLike = float32,
17
+ ) -> Tensor:
18
+ return zeros(
19
+ shape=shape, device=device, requires_grad=requires_grad, dtype=dtype
20
+ )
@@ -0,0 +1,5 @@
1
+ from .base_layer import BaseLayer
2
+ from .linear import Linear
3
+ from .input import Input
4
+ from .conv2d import Conv2d
5
+ from .flatten import Flatten
@@ -0,0 +1,9 @@
1
+ from typing import Any
2
+ from abc import abstractmethod
3
+ from ..block import Block
4
+ from ..typing import tensor_types
5
+
6
+
7
+ class BaseLayer(Block):
8
+ def __init__(self, name: str = "layer", trainable: bool = True) -> None:
9
+ super().__init__(name=name, trainable=trainable)