picodl-nn 0.1.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.
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: picodl-nn
3
+ Version: 0.1.0
4
+ Summary: A tiny deep learning library built from scratch requiring just numpy.
5
+ Requires-Python: >=3.12
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: numpy
8
+ Dynamic: description
9
+ Dynamic: description-content-type
10
+ Dynamic: requires-dist
11
+ Dynamic: requires-python
12
+ Dynamic: summary
13
+
14
+
15
+ # picodl.
16
+
17
+ A tiny deep learning library built from scratch in Python - autograd engine, layers, losses, optimizers, and a training loop, all on top of plain numpy. No PyTorch, no TensorFlow, no hidden framework underneath.
18
+
19
+
20
+ ## Documentation
21
+
22
+ [Documentation](https://picodl.vercel.app/docs.html)
23
+
24
+
25
+ ## Installation
26
+
27
+ Install picodl with pip
28
+
29
+ ```bash
30
+ pip install picodl-nn
31
+ ```
32
+
33
+ ## Demo
34
+
35
+ A sample model
36
+
37
+ ```python
38
+ from picodl.nn import NeuralNet
39
+ from picodl.layers import Linear, GELU
40
+ from picodl.loss import CrossEntropyLoss
41
+ from picodl.optim import AdamW
42
+ from picodl.train import train
43
+
44
+ net = NeuralNet([
45
+ Linear(784, 128),
46
+ GELU(),
47
+ Linear(128, 10),
48
+ ])
49
+
50
+ train(net, x_train, y_train,
51
+ num_epochs=10,
52
+ loss=CrossEntropyLoss(),
53
+ optimizer=AdamW(lr=0.001, weight_decay=0.01))
54
+
55
+ net.save("model.picodl")
56
+ ```
57
+ ## Authors
58
+
59
+ - [@alight659](https://www.github.com/alight659)
60
+
61
+
62
+ ## License
63
+
64
+ [MIT](https://github.com/alight659/picodl/blob/main/LICENSE)
65
+
File without changes
@@ -0,0 +1,26 @@
1
+ from typing import Iterator, NamedTuple
2
+ import numpy as np
3
+ from picodl.tensor import Tensor
4
+
5
+ Batch = NamedTuple("Batch", [("inputs", Tensor), ("targets", Tensor)])
6
+
7
+
8
+ class DataIterator:
9
+ def __call__(self, inputs: Tensor, targets: Tensor) -> Iterator[Batch]:
10
+ raise NotImplementedError
11
+
12
+ class BatchIterator(DataIterator):
13
+ def __init__(self, batch_size: int = 32, shuffle: bool = True) -> None:
14
+ self.batch_size = batch_size
15
+ self.shuffle = shuffle
16
+
17
+ def __call__(self, inputs: Tensor, targets: Tensor) -> Iterator[Batch]:
18
+ starts = np.arange(0, len(inputs), self.batch_size)
19
+ if self.shuffle:
20
+ np.random.shuffle(starts)
21
+
22
+ for start in starts:
23
+ end = start + self.batch_size
24
+ batch_inputs = inputs[start:end]
25
+ batch_targets = targets[start:end]
26
+ yield Batch(batch_inputs, batch_targets)
@@ -0,0 +1,216 @@
1
+ import numpy as np
2
+ from typing import Dict
3
+ from picodl.tensor import Tensor
4
+
5
+
6
+ class Layer:
7
+ def __init__(self) -> None:
8
+ self.params: Dict[str, Tensor] = {}
9
+
10
+ def forward(self, inputs: Tensor) -> Tensor:
11
+ raise NotImplementedError
12
+
13
+
14
+ class Linear(Layer):
15
+ def __init__(self, input_size: int, output_size: int) -> None:
16
+ super().__init__()
17
+ self.params["w"] = Tensor(np.random.randn(input_size, output_size) * 0.1, requires_grad=True)
18
+ self.params["b"] = Tensor(np.random.randn(output_size) * 0.1, requires_grad=True)
19
+
20
+ def forward(self, inputs: Tensor) -> Tensor:
21
+ return inputs.matmul(self.params["w"]) + self.params["b"]
22
+
23
+
24
+ class Tanh(Layer):
25
+ def forward(self, inputs: Tensor) -> Tensor:
26
+ return inputs.tanh()
27
+
28
+
29
+ class ReLU(Layer):
30
+ def forward(self, inputs: Tensor) -> Tensor:
31
+ return inputs.relu()
32
+
33
+
34
+ class GELU(Layer):
35
+ def forward(self, inputs: Tensor) -> Tensor:
36
+ return inputs.gelu()
37
+
38
+
39
+ class Conv2D(Layer):
40
+ # inputs: (N, C, H, W). kernel: (out_c, C, kh, kw)
41
+ def __init__(self, in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, padding: int = 0, pad_mode: str = "constant") -> None:
42
+ super().__init__()
43
+ self.stride = stride
44
+ self.padding = padding
45
+ self.pad_mode = pad_mode
46
+ scale = 0.1
47
+ self.params["w"] = Tensor(np.random.randn(out_channels, in_channels, kernel_size, kernel_size) * scale, requires_grad=True)
48
+ self.params["b"] = Tensor(np.zeros(out_channels), requires_grad=True)
49
+
50
+ def forward(self, inputs: Tensor) -> Tensor:
51
+ out = inputs.conv2d(self.params["w"], stride=self.stride, padding=self.padding, pad_mode=self.pad_mode)
52
+ return self._add_bias(out, self.params["b"])
53
+
54
+ def _add_bias(self, out: Tensor, b: Tensor) -> Tensor:
55
+ bias = Tensor(b.data.reshape(1, -1, 1, 1), b.requires_grad, (b,), "reshape_bias")
56
+
57
+ def _backward():
58
+ if b.requires_grad:
59
+ b._accumulate(bias.grad.sum(axis=(0, 2, 3)))
60
+ bias._backward = _backward
61
+ return out + bias
62
+
63
+
64
+ class Embedding(Layer):
65
+ def __init__(self, vocab_size: int, embed_dim: int) -> None:
66
+ super().__init__()
67
+ self.params["w"] = Tensor(np.random.randn(vocab_size, embed_dim) * 0.1, requires_grad=True)
68
+
69
+ def forward(self, idx) -> Tensor:
70
+ return self.params["w"][idx]
71
+
72
+
73
+ class TiedLinear(Layer):
74
+ def __init__(self, tied_layer: Layer, weight_key: str = "w", bias: bool = False) -> None:
75
+ super().__init__()
76
+ self.tied_weight = tied_layer.params[weight_key] # shape (vocab, dim), shared object
77
+ if bias:
78
+ out_features = self.tied_weight.data.shape[0]
79
+ self.params["b"] = Tensor(np.zeros(out_features), requires_grad=True)
80
+
81
+ def forward(self, inputs: Tensor) -> Tensor:
82
+ out = inputs.matmul(self.tied_weight.transpose(1, 0))
83
+ if "b" in self.params:
84
+ out = out + self.params["b"]
85
+ return out
86
+
87
+
88
+ class MaxPool2D(Layer):
89
+ def __init__(self, kernel_size: int, stride: int = None) -> None:
90
+ super().__init__()
91
+ self.kernel_size = kernel_size
92
+ self.stride = stride
93
+
94
+ def forward(self, inputs: Tensor) -> Tensor:
95
+ return inputs.maxpool2d(self.kernel_size, self.stride)
96
+
97
+
98
+ class AvgPool2D(Layer):
99
+ def __init__(self, kernel_size: int, stride: int = None) -> None:
100
+ super().__init__()
101
+ self.kernel_size = kernel_size
102
+ self.stride = stride
103
+
104
+ def forward(self, inputs: Tensor) -> Tensor:
105
+ return inputs.avgpool2d(self.kernel_size, self.stride)
106
+
107
+
108
+ class Flatten(Layer):
109
+ def forward(self, inputs: Tensor) -> Tensor:
110
+ return inputs.flatten(start_dim=1)
111
+
112
+
113
+ class GlobalAvgPool(Layer):
114
+ def forward(self, inputs: Tensor) -> Tensor:
115
+ return inputs.mean(axis=3).mean(axis=2) # (N,C,H,W) -> (N,C)
116
+
117
+
118
+ class BatchNorm2D(Layer):
119
+ # Normalize over N,H,W per channel. inputs: (N,C,H,W)
120
+ def __init__(self, num_features: int, eps: float = 1e-5, momentum: float = 0.1) -> None:
121
+ super().__init__()
122
+ self.eps = eps
123
+ self.momentum = momentum
124
+ self.params["gamma"] = Tensor(np.ones(num_features), requires_grad=True)
125
+ self.params["beta"] = Tensor(np.zeros(num_features), requires_grad=True)
126
+ self.running_mean = np.zeros(num_features)
127
+ self.running_var = np.ones(num_features)
128
+ self.training = True
129
+
130
+ def forward(self, inputs: Tensor) -> Tensor:
131
+ if self.training:
132
+ mean = inputs.data.mean(axis=(0, 2, 3))
133
+ var = inputs.data.var(axis=(0, 2, 3))
134
+ self.running_mean = (1 - self.momentum) * self.running_mean + self.momentum * mean
135
+ self.running_var = (1 - self.momentum) * self.running_var + self.momentum * var
136
+ else:
137
+ mean = self.running_mean
138
+ var = self.running_var
139
+
140
+ mean_t = Tensor(mean.reshape(1, -1, 1, 1))
141
+ var_t = Tensor(var.reshape(1, -1, 1, 1))
142
+ gamma = self.params["gamma"]
143
+ beta = self.params["beta"]
144
+ gamma_b = Tensor(gamma.data.reshape(1, -1, 1, 1), gamma.requires_grad, (gamma,), "reshape_g")
145
+
146
+ def _bg():
147
+ if gamma.requires_grad:
148
+ gamma._accumulate(gamma_b.grad.sum(axis=(0, 2, 3)))
149
+ gamma_b._backward = _bg
150
+
151
+ beta_b = Tensor(beta.data.reshape(1, -1, 1, 1), beta.requires_grad, (beta,), "reshape_bt")
152
+
153
+ def _bb():
154
+ if beta.requires_grad:
155
+ beta._accumulate(beta_b.grad.sum(axis=(0, 2, 3)))
156
+ beta_b._backward = _bb
157
+
158
+ normed = (inputs - mean_t) / (var_t + self.eps).sqrt()
159
+ return normed * gamma_b + beta_b
160
+
161
+ def eval(self):
162
+ self.training = False
163
+
164
+ def train(self):
165
+ self.training = True
166
+
167
+
168
+ class Dropout(Layer):
169
+ def __init__(self, p: float = 0.5) -> None:
170
+ super().__init__()
171
+ self.p = p
172
+ self.training = True
173
+
174
+ def forward(self, inputs: Tensor) -> Tensor:
175
+ if not self.training or self.p == 0.0:
176
+ return inputs
177
+ mask = (np.random.rand(*inputs.data.shape) > self.p).astype(np.float64) / (1 - self.p)
178
+ mask_t = Tensor(mask)
179
+ return inputs * mask_t
180
+
181
+ def eval(self):
182
+ self.training = False
183
+
184
+ def train(self):
185
+ self.training = True
186
+
187
+
188
+ class LayerNorm(Layer):
189
+ # y = (x - mean) / sqrt(var + eps) * gamma + beta
190
+ def __init__(self, dim: int, eps: float = 1e-5) -> None:
191
+ super().__init__()
192
+ self.eps = eps
193
+ self.params["gamma"] = Tensor(np.ones(dim), requires_grad=True)
194
+ self.params["beta"] = Tensor(np.zeros(dim), requires_grad=True)
195
+
196
+ def forward(self, inputs: Tensor) -> Tensor:
197
+ mu = inputs.mean(axis=-1)
198
+ mu_b = Tensor(np.expand_dims(mu.data, -1), mu.requires_grad, (mu,), "expand")
199
+
200
+ def _backward_mu():
201
+ if mu.requires_grad:
202
+ mu._accumulate(mu_b.grad.sum(axis=-1))
203
+ mu_b._backward = _backward_mu
204
+
205
+ diff = inputs - mu_b
206
+ var = (diff * diff).mean(axis=-1)
207
+ var_b = Tensor(np.expand_dims(var.data, -1), var.requires_grad, (var,), "expand")
208
+
209
+ def _backward_var():
210
+ if var.requires_grad:
211
+ var._accumulate(var_b.grad.sum(axis=-1))
212
+ var_b._backward = _backward_var
213
+
214
+ std = (var_b + self.eps).sqrt()
215
+ normed = diff / std
216
+ return normed * self.params["gamma"] + self.params["beta"]
@@ -0,0 +1,39 @@
1
+ import numpy as np
2
+ from picodl.tensor import Tensor
3
+
4
+
5
+ class Loss:
6
+ def loss(self, predicted: Tensor, actual: Tensor) -> Tensor:
7
+ raise NotImplementedError
8
+
9
+
10
+ class MSE(Loss):
11
+ def loss(self, predicted: Tensor, actual: Tensor) -> Tensor:
12
+ diff = predicted - actual
13
+ return (diff * diff).sum()
14
+
15
+
16
+ class BinaryCrossEntropy(Loss):
17
+ def loss(self, predicted: Tensor, actual: Tensor) -> Tensor:
18
+ eps = 1e-9
19
+ p = predicted.clip(eps, 1 - eps)
20
+ term1 = actual * p.log()
21
+ term2 = (1 - actual) * (1 - p).log()
22
+ return -(term1 + term2).sum()
23
+
24
+
25
+ class NLLLoss(Loss):
26
+ # Expects predicted = log-probabilities (N, C), actual = int class indices (N,)
27
+ def loss(self, predicted: Tensor, actual) -> Tensor:
28
+ n = predicted.shape[0]
29
+ picked = predicted[np.arange(n), actual]
30
+ return -picked.mean()
31
+
32
+
33
+ class CrossEntropyLoss(Loss):
34
+ # Expects predicted = raw logits (N, C), actual = int class indices (N,).
35
+ def loss(self, predicted: Tensor, actual) -> Tensor:
36
+ log_probs = predicted.log_softmax(axis=-1)
37
+ n = predicted.shape[0]
38
+ picked = log_probs[np.arange(n), actual]
39
+ return -picked.mean()
@@ -0,0 +1,41 @@
1
+ from typing import Sequence, Iterator
2
+ import numpy as np
3
+ from picodl.tensor import Tensor
4
+ from picodl.layers import Layer
5
+
6
+
7
+ class NeuralNet:
8
+ def __init__(self, layers: Sequence[Layer]) -> None:
9
+ self.layers = layers
10
+
11
+ def forward(self, inputs: Tensor) -> Tensor:
12
+ for layer in self.layers:
13
+ inputs = layer.forward(inputs)
14
+ return inputs
15
+
16
+ def params(self) -> Iterator[Tensor]:
17
+ for layer in self.layers:
18
+ for param in layer.params.values():
19
+ yield param
20
+
21
+ def zero_grad(self) -> None:
22
+ for param in self.params():
23
+ param.zero_grad()
24
+
25
+ def save(self, path: str) -> None:
26
+ flat = {}
27
+ for i, layer in enumerate(self.layers):
28
+ for name, param in layer.params.items():
29
+ flat[f"{i}_{name}"] = param.data
30
+ with open(path, "wb") as f:
31
+ np.savez(f, **flat)
32
+
33
+ def load(self, path: str) -> None:
34
+ data = np.load(path)
35
+ for i, layer in enumerate(self.layers):
36
+ for name, param in layer.params.items():
37
+ key = f"{i}_{name}"
38
+ if key in data:
39
+ param.data = data[key]
40
+ else:
41
+ raise KeyError(f"missing {key} in {path}, architecture mismatch")
@@ -0,0 +1,92 @@
1
+ import numpy as np
2
+ from picodl.nn import NeuralNet
3
+
4
+
5
+ class Optimizer:
6
+ def step(self, net: NeuralNet) -> None:
7
+ raise NotImplementedError
8
+
9
+
10
+ class SGD(Optimizer):
11
+ def __init__(self, lr: float = 0.01) -> None:
12
+ self.lr = lr
13
+
14
+ def step(self, net: NeuralNet) -> None:
15
+ for param in net.params():
16
+ if param.grad is not None:
17
+ param.data -= self.lr * param.grad
18
+
19
+
20
+ class RMSprop(Optimizer):
21
+ def __init__(self, lr: float = 0.001, decay: float = 0.9, eps: float = 1e-8) -> None:
22
+ self.lr = lr
23
+ self.decay = decay
24
+ self.eps = eps
25
+ self.cache = {}
26
+
27
+ def step(self, net: NeuralNet) -> None:
28
+ for param in net.params():
29
+ if param.grad is None:
30
+ continue
31
+ key = id(param)
32
+ if key not in self.cache:
33
+ self.cache[key] = np.zeros_like(param.data)
34
+ self.cache[key] = self.decay * self.cache[key] + (1 - self.decay) * (param.grad ** 2)
35
+ param.data -= self.lr * param.grad / (np.sqrt(self.cache[key]) + self.eps)
36
+
37
+
38
+ class Adam(Optimizer):
39
+ def __init__(self, lr: float = 0.001, beta1: float = 0.9, beta2: float = 0.999, eps: float = 1e-8) -> None:
40
+ self.lr = lr
41
+ self.beta1 = beta1
42
+ self.beta2 = beta2
43
+ self.eps = eps
44
+ self.m = {}
45
+ self.v = {}
46
+ self.t = 0
47
+
48
+ def step(self, net: NeuralNet) -> None:
49
+ self.t += 1
50
+ for param in net.params():
51
+ if param.grad is None:
52
+ continue
53
+ key = id(param)
54
+ if key not in self.m:
55
+ self.m[key] = np.zeros_like(param.data)
56
+ self.v[key] = np.zeros_like(param.data)
57
+ self.m[key] = self.beta1 * self.m[key] + (1 - self.beta1) * param.grad
58
+ self.v[key] = self.beta2 * self.v[key] + (1 - self.beta2) * (param.grad ** 2)
59
+ m_hat = self.m[key] / (1 - self.beta1 ** self.t)
60
+ v_hat = self.v[key] / (1 - self.beta2 ** self.t)
61
+ param.data -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)
62
+
63
+
64
+ class AdamW(Optimizer):
65
+ # Adam with decoupled weight decay (weight decay applied directly to param.data, not folded into the gradient/momentum like plain Adam+L2)
66
+ def __init__(self, lr: float = 0.001, beta1: float = 0.9, beta2: float = 0.999,
67
+ eps: float = 1e-8, weight_decay: float = 0.01) -> None:
68
+ self.lr = lr
69
+ self.beta1 = beta1
70
+ self.beta2 = beta2
71
+ self.eps = eps
72
+ self.weight_decay = weight_decay
73
+ self.m = {}
74
+ self.v = {}
75
+ self.t = 0
76
+
77
+ def step(self, net: NeuralNet) -> None:
78
+ self.t += 1
79
+ for param in net.params():
80
+ if param.grad is None:
81
+ continue
82
+ key = id(param)
83
+ if key not in self.m:
84
+ self.m[key] = np.zeros_like(param.data)
85
+ self.v[key] = np.zeros_like(param.data)
86
+ # decoupled weight decay: shrink weights directly, not via gradient
87
+ param.data -= self.lr * self.weight_decay * param.data
88
+ self.m[key] = self.beta1 * self.m[key] + (1 - self.beta1) * param.grad
89
+ self.v[key] = self.beta2 * self.v[key] + (1 - self.beta2) * (param.grad ** 2)
90
+ m_hat = self.m[key] / (1 - self.beta1 ** self.t)
91
+ v_hat = self.v[key] / (1 - self.beta2 ** self.t)
92
+ param.data -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)
@@ -0,0 +1,535 @@
1
+ import numpy as np
2
+
3
+
4
+ class Tensor:
5
+
6
+ def __init__(self, data, requires_grad=False, _children=(), _op=""):
7
+ self.data = np.asarray(data, dtype=np.float64)
8
+ self.requires_grad = requires_grad
9
+ self.grad = None
10
+ self._backward = lambda: None
11
+ self._prev = set(_children)
12
+ self._op = _op
13
+
14
+ @property
15
+ def shape(self):
16
+ return self.data.shape
17
+
18
+ def zero_grad(self):
19
+ self.grad = None
20
+
21
+ def _wrap(self, other):
22
+ return other if isinstance(other, Tensor) else Tensor(other)
23
+
24
+ def _accumulate(self, grad):
25
+ if self.grad is None:
26
+ self.grad = np.zeros_like(self.data)
27
+ while grad.ndim > self.data.ndim:
28
+ grad = grad.sum(axis=0)
29
+ for i, dim in enumerate(self.data.shape):
30
+ if dim == 1 and grad.shape[i] != 1:
31
+ grad = grad.sum(axis=i, keepdims=True)
32
+ self.grad += grad
33
+
34
+ def __add__(self, other):
35
+ other = self._wrap(other)
36
+ out = Tensor(self.data + other.data, self.requires_grad or other.requires_grad, (self, other), "+")
37
+
38
+ def _backward():
39
+ if self.requires_grad:
40
+ self._accumulate(out.grad)
41
+ if other.requires_grad:
42
+ other._accumulate(out.grad)
43
+ out._backward = _backward
44
+ return out
45
+
46
+ def __radd__(self, other):
47
+ return self.__add__(other)
48
+
49
+ def __neg__(self):
50
+ out = Tensor(-self.data, self.requires_grad, (self,), "neg")
51
+
52
+ def _backward():
53
+ if self.requires_grad:
54
+ self._accumulate(-out.grad)
55
+ out._backward = _backward
56
+ return out
57
+
58
+ def __sub__(self, other):
59
+ return self + (-self._wrap(other))
60
+
61
+ def __rsub__(self, other):
62
+ return self._wrap(other) + (-self)
63
+
64
+ def __mul__(self, other):
65
+ other = self._wrap(other)
66
+ out = Tensor(self.data * other.data, self.requires_grad or other.requires_grad, (self, other), "*")
67
+
68
+ def _backward():
69
+ if self.requires_grad:
70
+ self._accumulate(out.grad * other.data)
71
+ if other.requires_grad:
72
+ other._accumulate(out.grad * self.data)
73
+ out._backward = _backward
74
+ return out
75
+
76
+ def __rmul__(self, other):
77
+ return self.__mul__(other)
78
+
79
+ def __pow__(self, power):
80
+ out = Tensor(self.data ** power, self.requires_grad, (self,), f"**{power}")
81
+
82
+ def _backward():
83
+ if self.requires_grad:
84
+ self._accumulate(out.grad * power * (self.data ** (power - 1)))
85
+ out._backward = _backward
86
+ return out
87
+
88
+ def __truediv__(self, other):
89
+ other = self._wrap(other)
90
+ return self * (other ** -1)
91
+
92
+ def matmul(self, other):
93
+ other = self._wrap(other)
94
+ out = Tensor(self.data @ other.data, self.requires_grad or other.requires_grad, (self, other), "matmul")
95
+
96
+ def _backward():
97
+ if self.requires_grad:
98
+ self._accumulate(out.grad @ other.data.T)
99
+ if other.requires_grad:
100
+ other._accumulate(self.data.T @ out.grad)
101
+ out._backward = _backward
102
+ return out
103
+
104
+ def __matmul__(self, other):
105
+ return self.matmul(other)
106
+
107
+ def sum(self, axis=None):
108
+ out = Tensor(self.data.sum(axis=axis), self.requires_grad, (self,), "sum")
109
+
110
+ def _backward():
111
+ if self.requires_grad:
112
+ grad = out.grad
113
+ if axis is not None:
114
+ grad = np.expand_dims(grad, axis)
115
+ self._accumulate(np.ones_like(self.data) * grad)
116
+ out._backward = _backward
117
+ return out
118
+
119
+ def tanh(self):
120
+ t = np.tanh(self.data)
121
+ out = Tensor(t, self.requires_grad, (self,), "tanh")
122
+
123
+ def _backward():
124
+ if self.requires_grad:
125
+ self._accumulate(out.grad * (1 - t ** 2))
126
+ out._backward = _backward
127
+ return out
128
+
129
+ def log(self):
130
+ out = Tensor(np.log(self.data), self.requires_grad, (self,), "log")
131
+
132
+ def _backward():
133
+ if self.requires_grad:
134
+ self._accumulate(out.grad / self.data)
135
+ out._backward = _backward
136
+ return out
137
+
138
+ def clip(self, min_val, max_val):
139
+ out = Tensor(np.clip(self.data, min_val, max_val), self.requires_grad, (self,), "clip")
140
+
141
+ def _backward():
142
+ if self.requires_grad:
143
+ mask = (self.data >= min_val) & (self.data <= max_val)
144
+ self._accumulate(out.grad * mask)
145
+ out._backward = _backward
146
+ return out
147
+
148
+ def relu(self):
149
+ out = Tensor(np.maximum(0, self.data), self.requires_grad, (self,), "relu")
150
+
151
+ def _backward():
152
+ if self.requires_grad:
153
+ self._accumulate(out.grad * (self.data > 0))
154
+ out._backward = _backward
155
+ return out
156
+
157
+ def mean(self, axis=None):
158
+ out = Tensor(self.data.mean(axis=axis), self.requires_grad, (self,), "mean")
159
+ n = self.data.size if axis is None else self.data.shape[axis]
160
+
161
+ def _backward():
162
+ if self.requires_grad:
163
+ grad = out.grad
164
+ if axis is not None:
165
+ grad = np.expand_dims(grad, axis)
166
+ self._accumulate(np.ones_like(self.data) * grad / n)
167
+ out._backward = _backward
168
+ return out
169
+
170
+ def sqrt(self):
171
+ s = np.sqrt(self.data)
172
+ out = Tensor(s, self.requires_grad, (self,), "sqrt")
173
+
174
+ def _backward():
175
+ if self.requires_grad:
176
+ self._accumulate(out.grad / (2 * s))
177
+ out._backward = _backward
178
+ return out
179
+
180
+ def __getitem__(self, idx):
181
+ out = Tensor(self.data[idx], self.requires_grad, (self,), "getitem")
182
+
183
+ def _backward():
184
+ if self.requires_grad:
185
+ grad = np.zeros_like(self.data)
186
+ np.add.at(grad, idx, out.grad)
187
+ self._accumulate(grad)
188
+ out._backward = _backward
189
+ return out
190
+
191
+ def conv2d(self, kernel, stride=1, padding=0, pad_mode="constant"):
192
+ other = self._wrap(kernel)
193
+ x = self.data
194
+ w = other.data
195
+ N, C, H, W = x.shape
196
+ out_c, _, kh, kw = w.shape
197
+
198
+ np_mode = {"constant": "constant", "reflect": "reflect", "replicate": "edge", "circular": "wrap"}[pad_mode]
199
+ if padding > 0:
200
+ x = np.pad(x, ((0, 0), (0, 0), (padding, padding), (padding, padding)), mode=np_mode)
201
+
202
+ Hp, Wp = x.shape[2], x.shape[3]
203
+ out_h = (Hp - kh) // stride + 1
204
+ out_w = (Wp - kw) // stride + 1
205
+
206
+ # im2col
207
+ cols = np.zeros((N, C, kh, kw, out_h, out_w))
208
+ for i in range(kh):
209
+ for j in range(kw):
210
+ cols[:, :, i, j, :, :] = x[:, :, i:i + stride * out_h:stride, j:j + stride * out_w:stride]
211
+ cols_reshaped = cols.transpose(0, 4, 5, 1, 2, 3).reshape(N * out_h * out_w, -1)
212
+ w_reshaped = w.reshape(out_c, -1)
213
+ out_data = cols_reshaped @ w_reshaped.T
214
+ out_data = out_data.reshape(N, out_h, out_w, out_c).transpose(0, 3, 1, 2)
215
+
216
+ out = Tensor(out_data, self.requires_grad or other.requires_grad, (self, other), "conv2d")
217
+
218
+ def _backward():
219
+ grad_out = out.grad.transpose(0, 2, 3, 1).reshape(N * out_h * out_w, out_c)
220
+ if other.requires_grad:
221
+ dw = grad_out.T @ cols_reshaped
222
+ other._accumulate(dw.reshape(w.shape))
223
+ if self.requires_grad:
224
+ dcols = grad_out @ w_reshaped
225
+ dcols = dcols.reshape(N, out_h, out_w, C, kh, kw).transpose(0, 3, 4, 5, 1, 2)
226
+ dx = np.zeros_like(x)
227
+ for i in range(kh):
228
+ for j in range(kw):
229
+ dx[:, :, i:i + stride * out_h:stride, j:j + stride * out_w:stride] += dcols[:, :, i, j, :, :]
230
+ if padding > 0:
231
+ dx = dx[:, :, padding:-padding, padding:-padding]
232
+ self._accumulate(dx)
233
+ out._backward = _backward
234
+ return out
235
+
236
+ def reshape(self, *shape):
237
+ if len(shape) == 1 and isinstance(shape[0], (tuple, list)):
238
+ shape = shape[0]
239
+ orig_shape = self.data.shape
240
+ out = Tensor(self.data.reshape(shape), self.requires_grad, (self,), "reshape")
241
+
242
+ def _backward():
243
+ if self.requires_grad:
244
+ self._accumulate(out.grad.reshape(orig_shape))
245
+ out._backward = _backward
246
+ return out
247
+
248
+ def view(self, *shape):
249
+ return self.reshape(*shape)
250
+
251
+ def flatten(self, start_dim=0):
252
+ shape = self.data.shape
253
+ new_shape = shape[:start_dim] + (-1,)
254
+ return self.reshape(new_shape)
255
+
256
+ def transpose(self, *axes):
257
+ if len(axes) == 1 and isinstance(axes[0], (tuple, list)):
258
+ axes = axes[0]
259
+ if not axes:
260
+ axes = tuple(reversed(range(self.data.ndim)))
261
+ out = Tensor(self.data.transpose(axes), self.requires_grad, (self,), "transpose")
262
+
263
+ def _backward():
264
+ if self.requires_grad:
265
+ inv = np.argsort(axes)
266
+ self._accumulate(out.grad.transpose(inv))
267
+ out._backward = _backward
268
+ return out
269
+
270
+ def permute(self, *axes):
271
+ return self.transpose(*axes)
272
+
273
+ def softmax(self, axis=-1):
274
+ shifted = self.data - np.max(self.data, axis=axis, keepdims=True)
275
+ exp = np.exp(shifted)
276
+ s = exp / exp.sum(axis=axis, keepdims=True)
277
+ out = Tensor(s, self.requires_grad, (self,), "softmax")
278
+
279
+ def _backward():
280
+ if self.requires_grad:
281
+ grad_out = out.grad
282
+ dot = np.sum(grad_out * s, axis=axis, keepdims=True)
283
+ self._accumulate(s * (grad_out - dot))
284
+ out._backward = _backward
285
+ return out
286
+
287
+ def log_softmax(self, axis=-1):
288
+ shifted = self.data - np.max(self.data, axis=axis, keepdims=True)
289
+ logsumexp = np.log(np.exp(shifted).sum(axis=axis, keepdims=True))
290
+ result = shifted - logsumexp
291
+ out = Tensor(result, self.requires_grad, (self,), "log_softmax")
292
+
293
+ def _backward():
294
+ if self.requires_grad:
295
+ s = np.exp(result) # softmax probs
296
+ grad_out = out.grad
297
+ sum_grad = grad_out.sum(axis=axis, keepdims=True)
298
+ self._accumulate(grad_out - s * sum_grad)
299
+ out._backward = _backward
300
+ return out
301
+
302
+ def gelu(self):
303
+ # tanh approximation: 0.5 * x * (1 + tanh(sqrt(2 / pi) * (x + 0.044715 * x^3)))
304
+ c = np.sqrt(2 / np.pi)
305
+ x = self.data
306
+ inner = c * (x + 0.044715 * x ** 3)
307
+ t = np.tanh(inner)
308
+ result = 0.5 * x * (1 + t)
309
+ out = Tensor(result, self.requires_grad, (self,), "gelu")
310
+
311
+ def _backward():
312
+ if self.requires_grad:
313
+ dtanh = 1 - t ** 2
314
+ dinner = c * (1 + 3 * 0.044715 * x ** 2)
315
+ dresult = 0.5 * (1 + t) + 0.5 * x * dtanh * dinner
316
+ self._accumulate(out.grad * dresult)
317
+ out._backward = _backward
318
+ return out
319
+
320
+ def max(self, axis=None, keepdims=False):
321
+ out_data = self.data.max(axis=axis, keepdims=True)
322
+ mask = (self.data == out_data).astype(np.float64)
323
+ # break ties: only count first occurrence
324
+ count = mask.sum(axis=axis, keepdims=True)
325
+ mask = mask / count
326
+ if not keepdims:
327
+ out_data = out_data.squeeze(axis=axis) if axis is not None else out_data.reshape(())
328
+ out = Tensor(out_data, self.requires_grad, (self,), "max")
329
+
330
+ def _backward():
331
+ if self.requires_grad:
332
+ grad = out.grad
333
+ if axis is not None and not keepdims:
334
+ grad = np.expand_dims(grad, axis)
335
+ self._accumulate(mask * grad)
336
+ out._backward = _backward
337
+ return out
338
+
339
+ def argmax(self, axis=None):
340
+ return np.argmax(self.data, axis=axis)
341
+
342
+ def multinomial(self, num_samples=1):
343
+ probs = self.data
344
+ if probs.ndim == 1:
345
+ probs = probs[None, :]
346
+ out = np.zeros((probs.shape[0], num_samples), dtype=np.int64)
347
+ for i in range(probs.shape[0]):
348
+ out[i] = np.random.choice(probs.shape[1], size=num_samples, p=probs[i])
349
+ return out
350
+
351
+ @staticmethod
352
+ def cat(tensors, axis=0):
353
+ tensors = [t if isinstance(t, Tensor) else Tensor(t) for t in tensors]
354
+ datas = [t.data for t in tensors]
355
+ out_data = np.concatenate(datas, axis=axis)
356
+ req = any(t.requires_grad for t in tensors)
357
+ out = Tensor(out_data, req, tuple(tensors), "cat")
358
+ sizes = [d.shape[axis] for d in datas]
359
+
360
+ def _backward():
361
+ idx = 0
362
+ for t, size in zip(tensors, sizes):
363
+ if t.requires_grad:
364
+ sl = [slice(None)] * out.grad.ndim
365
+ sl[axis] = slice(idx, idx + size)
366
+ t._accumulate(out.grad[tuple(sl)])
367
+ idx += size
368
+ out._backward = _backward
369
+ return out
370
+
371
+ @staticmethod
372
+ def stack(tensors, axis=0):
373
+ tensors = [t if isinstance(t, Tensor) else Tensor(t) for t in tensors]
374
+ out_data = np.stack([t.data for t in tensors], axis=axis)
375
+ req = any(t.requires_grad for t in tensors)
376
+ out = Tensor(out_data, req, tuple(tensors), "stack")
377
+
378
+ def _backward():
379
+ for i, t in enumerate(tensors):
380
+ if t.requires_grad:
381
+ sl = [slice(None)] * out.grad.ndim
382
+ sl[axis] = i
383
+ t._accumulate(out.grad[tuple(sl)])
384
+ out._backward = _backward
385
+ return out
386
+
387
+ def split(self, size_or_sections, axis=0):
388
+ dim = self.data.shape[axis]
389
+ if isinstance(size_or_sections, int):
390
+ starts = list(range(0, dim, size_or_sections))
391
+ sizes = [min(size_or_sections, dim - s) for s in starts]
392
+ else:
393
+ sizes = list(size_or_sections)
394
+ starts = np.cumsum([0] + sizes[:-1]).tolist()
395
+ outs = []
396
+ for start, size in zip(starts, sizes):
397
+ sl = [slice(None)] * self.data.ndim
398
+ sl[axis] = slice(start, start + size)
399
+ piece = Tensor(self.data[tuple(sl)], self.requires_grad, (self,), "split")
400
+
401
+ def make_backward(sl_local, piece_local):
402
+ def _backward():
403
+ if self.requires_grad:
404
+ grad = np.zeros_like(self.data)
405
+ grad[tuple(sl_local)] = piece_local.grad
406
+ self._accumulate(grad)
407
+ return _backward
408
+ piece._backward = make_backward(sl, piece)
409
+ outs.append(piece)
410
+ return outs
411
+
412
+ def topk(self, k, axis=-1):
413
+ idx = np.argsort(-self.data, axis=axis)
414
+ idx = np.take(idx, range(k), axis=axis)
415
+ values_data = np.take_along_axis(self.data, idx, axis=axis)
416
+ out = Tensor(values_data, self.requires_grad, (self,), "topk")
417
+
418
+ def _backward():
419
+ if self.requires_grad:
420
+ grad = np.zeros_like(self.data)
421
+ np.put_along_axis(grad, idx, out.grad, axis=axis)
422
+ self._accumulate(grad)
423
+ out._backward = _backward
424
+ return out, idx
425
+
426
+ def scatter(self, axis, index, src):
427
+ src_t = src if isinstance(src, Tensor) else Tensor(src)
428
+ out_data = self.data.copy()
429
+ np.put_along_axis(out_data, index, src_t.data, axis=axis)
430
+ out = Tensor(out_data, self.requires_grad or src_t.requires_grad, (self, src_t), "scatter")
431
+
432
+ def _backward():
433
+ if src_t.requires_grad:
434
+ grad_src = np.take_along_axis(out.grad, index, axis=axis)
435
+ src_t._accumulate(grad_src)
436
+ if self.requires_grad:
437
+ grad_self = out.grad.copy()
438
+ np.put_along_axis(grad_self, index, 0, axis=axis)
439
+ self._accumulate(grad_self)
440
+ out._backward = _backward
441
+ return out
442
+
443
+ def index_add(self, axis, index, src):
444
+ src_t = src if isinstance(src, Tensor) else Tensor(src)
445
+ out_data = self.data.copy()
446
+ np.add.at(out_data, (tuple(slice(None) for _ in range(axis)) + (index,)), src_t.data)
447
+ out = Tensor(out_data, self.requires_grad or src_t.requires_grad, (self, src_t), "index_add")
448
+
449
+ def _backward():
450
+ if self.requires_grad:
451
+ self._accumulate(out.grad)
452
+ if src_t.requires_grad:
453
+ sl = (tuple(slice(None) for _ in range(axis)) + (index,))
454
+ src_t._accumulate(out.grad[sl])
455
+ out._backward = _backward
456
+ return out
457
+
458
+ def maxpool2d(self, kernel_size, stride=None):
459
+ stride = stride or kernel_size
460
+ x = self.data
461
+ N, C, H, W = x.shape
462
+ kh = kw = kernel_size
463
+ out_h = (H - kh) // stride + 1
464
+ out_w = (W - kw) // stride + 1
465
+
466
+ cols = np.zeros((N, C, kh, kw, out_h, out_w))
467
+ for i in range(kh):
468
+ for j in range(kw):
469
+ cols[:, :, i, j, :, :] = x[:, :, i:i + stride * out_h:stride, j:j + stride * out_w:stride]
470
+ cols_flat = cols.reshape(N, C, kh * kw, out_h, out_w)
471
+ out_data = cols_flat.max(axis=2)
472
+ argmax = cols_flat.argmax(axis=2) # (N,C,out_h,out_w)
473
+
474
+ out = Tensor(out_data, self.requires_grad, (self,), "maxpool2d")
475
+
476
+ def _backward():
477
+ if self.requires_grad:
478
+ dx = np.zeros_like(x)
479
+ grad = out.grad
480
+ for i in range(kh):
481
+ for j in range(kw):
482
+ mask = (argmax == (i * kw + j)).astype(np.float64)
483
+ dx[:, :, i:i + stride * out_h:stride, j:j + stride * out_w:stride] += mask * grad
484
+ self._accumulate(dx)
485
+ out._backward = _backward
486
+ return out
487
+
488
+ def avgpool2d(self, kernel_size, stride=None):
489
+ stride = stride or kernel_size
490
+ x = self.data
491
+ N, C, H, W = x.shape
492
+ kh = kw = kernel_size
493
+ out_h = (H - kh) // stride + 1
494
+ out_w = (W - kw) // stride + 1
495
+
496
+ cols = np.zeros((N, C, kh, kw, out_h, out_w))
497
+ for i in range(kh):
498
+ for j in range(kw):
499
+ cols[:, :, i, j, :, :] = x[:, :, i:i + stride * out_h:stride, j:j + stride * out_w:stride]
500
+ out_data = cols.mean(axis=(2, 3))
501
+
502
+ out = Tensor(out_data, self.requires_grad, (self,), "avgpool2d")
503
+
504
+ def _backward():
505
+ if self.requires_grad:
506
+ dx = np.zeros_like(x)
507
+ grad = out.grad / (kh * kw)
508
+ for i in range(kh):
509
+ for j in range(kw):
510
+ dx[:, :, i:i + stride * out_h:stride, j:j + stride * out_w:stride] += grad
511
+ self._accumulate(dx)
512
+ out._backward = _backward
513
+ return out
514
+
515
+ def backward(self, grad=None):
516
+ topo = []
517
+ visited = set()
518
+
519
+ def build(v):
520
+ if v not in visited:
521
+ visited.add(v)
522
+ for child in v._prev:
523
+ build(child)
524
+ topo.append(v)
525
+ build(self)
526
+
527
+ if grad is None:
528
+ grad = np.ones_like(self.data)
529
+ self.grad = grad
530
+
531
+ for node in reversed(topo):
532
+ node._backward()
533
+
534
+ def __repr__(self):
535
+ return f"Tensor({self.data}, requires_grad={self.requires_grad})"
@@ -0,0 +1,27 @@
1
+ import numpy as np
2
+ from picodl.tensor import Tensor
3
+ from picodl.nn import NeuralNet
4
+ from picodl.loss import Loss, MSE
5
+ from picodl.optim import Optimizer, SGD
6
+ from picodl.data import DataIterator, BatchIterator
7
+
8
+
9
+ def train(net: NeuralNet, inputs: Tensor, targets: Tensor, num_epochs: int = 1000,
10
+ iterator: DataIterator = BatchIterator(), loss: Loss = MSE(), optimizer: Optimizer = SGD()) -> None:
11
+ raw_inputs = inputs.data if isinstance(inputs, Tensor) else inputs
12
+ raw_targets = targets.data if isinstance(targets, Tensor) else targets
13
+ for epoch in range(num_epochs):
14
+ epoch_loss = 0.0
15
+ for batch in iterator(raw_inputs, raw_targets):
16
+ net.zero_grad()
17
+ batch_in = Tensor(batch.inputs)
18
+ # classification losses (CrossEntropyLoss, NLLLoss) expect plain int
19
+ # class-index targets, not a Tensor - only wrap float targets
20
+ targets_are_int = np.issubdtype(np.asarray(batch.targets).dtype, np.integer)
21
+ batch_tgt = batch.targets if targets_are_int else Tensor(batch.targets)
22
+ predicted = net.forward(batch_in)
23
+ loss_val = loss.loss(predicted, batch_tgt)
24
+ epoch_loss += loss_val.data
25
+ loss_val.backward()
26
+ optimizer.step(net)
27
+ print(epoch, epoch_loss)
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: picodl-nn
3
+ Version: 0.1.0
4
+ Summary: A tiny deep learning library built from scratch requiring just numpy.
5
+ Requires-Python: >=3.12
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: numpy
8
+ Dynamic: description
9
+ Dynamic: description-content-type
10
+ Dynamic: requires-dist
11
+ Dynamic: requires-python
12
+ Dynamic: summary
13
+
14
+
15
+ # picodl.
16
+
17
+ A tiny deep learning library built from scratch in Python - autograd engine, layers, losses, optimizers, and a training loop, all on top of plain numpy. No PyTorch, no TensorFlow, no hidden framework underneath.
18
+
19
+
20
+ ## Documentation
21
+
22
+ [Documentation](https://picodl.vercel.app/docs.html)
23
+
24
+
25
+ ## Installation
26
+
27
+ Install picodl with pip
28
+
29
+ ```bash
30
+ pip install picodl-nn
31
+ ```
32
+
33
+ ## Demo
34
+
35
+ A sample model
36
+
37
+ ```python
38
+ from picodl.nn import NeuralNet
39
+ from picodl.layers import Linear, GELU
40
+ from picodl.loss import CrossEntropyLoss
41
+ from picodl.optim import AdamW
42
+ from picodl.train import train
43
+
44
+ net = NeuralNet([
45
+ Linear(784, 128),
46
+ GELU(),
47
+ Linear(128, 10),
48
+ ])
49
+
50
+ train(net, x_train, y_train,
51
+ num_epochs=10,
52
+ loss=CrossEntropyLoss(),
53
+ optimizer=AdamW(lr=0.001, weight_decay=0.01))
54
+
55
+ net.save("model.picodl")
56
+ ```
57
+ ## Authors
58
+
59
+ - [@alight659](https://www.github.com/alight659)
60
+
61
+
62
+ ## License
63
+
64
+ [MIT](https://github.com/alight659/picodl/blob/main/LICENSE)
65
+
@@ -0,0 +1,14 @@
1
+ setup.py
2
+ picodl/__init__.py
3
+ picodl/data.py
4
+ picodl/layers.py
5
+ picodl/loss.py
6
+ picodl/nn.py
7
+ picodl/optim.py
8
+ picodl/tensor.py
9
+ picodl/train.py
10
+ picodl_nn.egg-info/PKG-INFO
11
+ picodl_nn.egg-info/SOURCES.txt
12
+ picodl_nn.egg-info/dependency_links.txt
13
+ picodl_nn.egg-info/requires.txt
14
+ picodl_nn.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ numpy
@@ -0,0 +1 @@
1
+ picodl
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,14 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="picodl-nn",
5
+ version="0.1.0",
6
+ description="A tiny deep learning library built from scratch requiring just numpy.",
7
+ long_description=open("readme.md").read(),
8
+ long_description_content_type="text/markdown",
9
+ packages=find_packages(),
10
+ python_requires=">=3.12",
11
+ install_requires=[
12
+ "numpy",
13
+ ]
14
+ )