Repository navigation
Expand file tree
/
Copy pathdeeplearn_numpy.py
More file actions
2397 lines (2011 loc) · 75.3 KB
/
Copy pathdeeplearn_numpy.py
File metadata and controls
2397 lines (2011 loc) · 75.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# deeplearn_numpy.py
# NumPy-only, parametric deep learning mini-framework in a single file.
# - Supports configurable layers via registries and a JSON-like config
# - Core layers: Dense, Conv2D (im2col), MaxPool2D, AvgPool2D, Flatten, Dropout, Activations, BatchNorm (1D/2D)
# - Losses: MSE, CrossEntropy (with stable softmax), BinaryCrossEntropy
# - Optimizers: SGD, Momentum, Adam
# - Model: Sequential builder from config; training loop (fit/evaluate/predict)
# - Regularization: L1/L2
# - Serialization: save/load weights; save/load config
# - Metrics: accuracy (multi-class), binary_accuracy, top_k_accuracy
#
# Usage (example at bottom of file):
# from deeplearn_numpy import Model, build_model_from_config
# model = build_model_from_config(config)
# model.fit(x_train, y_train, epochs=5, batch_size=32)
#
# This file is self-contained and uses only NumPy.
from __future__ import annotations
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
import numpy as np
# ------------------------------------------------------------
# Utility: RNG and dtypes
# ------------------------------------------------------------
def _get_rng(seed: Optional[int]) -> np.random.Generator:
"""
Retrieves or creates a NumPy random number generator.
Args:
seed: Optional integer seed for reproducibility.
Returns:
A NumPy Generator instance.
"""
return np.random.default_rng(seed) if seed is not None else np.random.default_rng()
DEFAULT_DTYPE = np.float32
# ------------------------------------------------------------
# Parameter wrapper
# ------------------------------------------------------------
class Parameter:
"""
Wrapper for trainable parameters, managing data and gradients.
"""
def __init__(self, data: np.ndarray, name: Optional[str] = None):
"""
Initializes the parameter.
Args:
data: Initial value of the parameter.
name: Optional descriptive name for the parameter.
"""
self.data = data.astype(DEFAULT_DTYPE, copy=False)
self.grad = np.zeros_like(self.data)
self.name = name
def zero_grad(self):
"""Resets the gradient to zero."""
self.grad[...] = 0
# ------------------------------------------------------------
# Initializers (registry + functions)
# ------------------------------------------------------------
INITIALIZER_REGISTRY: Dict[
str, Callable[[Tuple[int, ...], Optional[int]], np.ndarray]
] = {}
def register_initializer(name: str):
"""
Decorator to register an initialization function.
Args:
name: Key to use in the initializer registry.
"""
def deco(fn):
INITIALIZER_REGISTRY[name] = fn
return fn
return deco
@register_initializer("zeros")
def init_zeros(shape: Tuple[int, ...], seed: Optional[int] = None):
"""Initializes weights with zeros."""
return np.zeros(shape, dtype=DEFAULT_DTYPE)
@register_initializer("ones")
def init_ones(shape: Tuple[int, ...], seed: Optional[int] = None):
"""Initializes weights with ones."""
return np.ones(shape, dtype=DEFAULT_DTYPE)
@register_initializer("random_normal")
def init_random_normal(shape: Tuple[int, ...], seed: Optional[int] = None):
"""Initializes weights with a standard normal distribution."""
rng = _get_rng(seed)
return rng.standard_normal(size=shape).astype(DEFAULT_DTYPE)
@register_initializer("glorot_uniform")
def init_glorot_uniform(shape: Tuple[int, ...], seed: Optional[int] = None):
"""Initializes weights using Glorot (Xavier) Uniform distribution."""
# fan_in, fan_out heuristic (for Dense/Conv2D weights)
if len(shape) == 2:
fan_in, fan_out = shape[0], shape[1]
elif len(shape) == 4: # (out_ch, in_ch, kH, kW)
fan_in = shape[1] * shape[2] * shape[3]
fan_out = shape[0] * shape[2] * shape[3]
else:
fan_in = int(np.prod(shape[:-1])) if len(shape) > 1 else shape[0]
fan_out = shape[-1]
limit = np.sqrt(6.0 / (fan_in + fan_out))
rng = _get_rng(seed)
return rng.uniform(-limit, limit, size=shape).astype(DEFAULT_DTYPE)
@register_initializer("he_normal")
def init_he_normal(shape: Tuple[int, ...], seed: Optional[int] = None):
"""Initializes weights using He Normal distribution (best for ReLU)."""
# Good for ReLU
if len(shape) == 2:
fan_in = shape[0]
elif len(shape) == 4:
fan_in = shape[1] * shape[2] * shape[3]
else:
fan_in = int(np.prod(shape[:-1])) if len(shape) > 1 else shape[0]
std = np.sqrt(2.0 / fan_in)
rng = _get_rng(seed)
return (rng.standard_normal(size=shape) * std).astype(DEFAULT_DTYPE)
def get_initializer(
name: str,
) -> Callable[[Tuple[int, ...], Optional[int]], np.ndarray]:
"""
Retrieves an initializer function from the registry.
Args:
name: Name of the initializer.
Returns:
The initialization function.
"""
if name not in INITIALIZER_REGISTRY:
raise ValueError(f"Unknown initializer: {name}")
return INITIALIZER_REGISTRY[name]
# ------------------------------------------------------------
# Activations as layers (registry-based)
# ------------------------------------------------------------
class Layer:
"""Base class for all layers."""
def __init__(self):
self.built = False
self.training = True # toggled by model
self._params: List[Parameter] = []
self._cache: Dict[str, Any] = {}
self.name: Optional[str] = None
def build(self, input_shape: Tuple[int, ...], **kwargs) -> Tuple[int, ...]:
"""
Builds layer structure given input shape.
Returns:
The output shape of the layer.
"""
self.built = True
return input_shape
def forward(self, x: np.ndarray) -> np.ndarray:
"""Computes the forward pass of the layer."""
raise NotImplementedError
def backward(self, dy: np.ndarray) -> np.ndarray:
"""Computes the backward pass (gradients) of the layer."""
raise NotImplementedError
def params(self) -> Iterable[Parameter]:
"""Returns list of trainable parameters in this layer."""
return self._params
def zero_grads(self):
"""Resets gradients of all parameters in this layer."""
for p in self._params:
p.zero_grad()
def set_training(self, mode: bool):
"""Toggles training mode for layers that behave differently during training vs inference."""
self.training = mode
# Optional: for shape inference without allocating params
def infer_output_shape(self, input_shape: Tuple[int, ...]) -> Tuple[int, ...]:
"""Infers output shape without modifying internal state."""
# default: identity
return input_shape
# Activation registry
ACTIVATION_REGISTRY: Dict[str, "Layer"] = {}
LAYER_REGISTRY: Dict[str, Callable[..., Layer]] = {}
def register_layer(name: str):
"""Decorator to register a neural network layer."""
def deco(cls):
LAYER_REGISTRY[name] = cls
return cls
return deco
def register_activation(name: str):
"""Decorator to register an activation function."""
def deco(cls):
ACTIVATION_REGISTRY[name] = cls
return cls
return deco
# ---- Activation implementations ----
@register_activation("relu")
@register_layer("ReLU")
class ReLU(Layer):
"""Rectified Linear Unit activation."""
def forward(self, x):
"""
Applies the ReLU activation function.
Args:
x (np.ndarray): Input array.
Returns:
np.ndarray: Output after applying ReLU.
"""
self._cache["mask"] = x > 0
return np.where(self._cache["mask"], x, 0).astype(DEFAULT_DTYPE)
def backward(self, dy):
"""
Computes the gradient of the ReLU function.
Args:
dy (np.ndarray): Upstream gradient.
Returns:
np.ndarray: Gradient with respect to the input.
"""
return dy * self._cache["mask"]
@register_activation("sigmoid")
@register_layer("Sigmoid")
class Sigmoid(Layer):
"""Sigmoid activation function."""
def forward(self, x):
"""
Applies the Sigmoid activation function.
Args:
x (np.ndarray): Input array.
Returns:
np.ndarray: Output after applying Sigmoid.
"""
out = 1.0 / (1.0 + np.exp(-x))
self._cache["out"] = out
return out.astype(DEFAULT_DTYPE)
def backward(self, dy):
"""
Computes the gradient of the Sigmoid function.
Args:
dy (np.ndarray): Upstream gradient.
Returns:
np.ndarray: Gradient with respect to the input.
"""
out = self._cache["out"]
return dy * out * (1.0 - out)
@register_activation("tanh")
@register_layer("Tanh")
class Tanh(Layer):
"""Hyperbolic tangent activation function."""
def forward(self, x):
"""
Applies the Hyperbolic Tangent activation function.
Args:
x (np.ndarray): Input array.
Returns:
np.ndarray: Output after applying Tanh.
"""
out = np.tanh(x)
self._cache["out"] = out
return out.astype(DEFAULT_DTYPE)
def backward(self, dy):
"""
Computes the gradient of the Tanh function.
Args:
dy (np.ndarray): Upstream gradient.
Returns:
np.ndarray: Gradient with respect to the input.
"""
out = self._cache["out"]
return dy * (1.0 - out**2)
@register_activation("leaky_relu")
@register_layer("LeakyReLU")
class LeakyReLU(Layer):
"""Leaky ReLU activation function."""
def __init__(self, alpha: float = 0.01):
"""
Initializes the LeakyReLU layer.
Args:
alpha (float): Scaling factor for negative input values.
"""
super().__init__()
self.alpha = alpha
def forward(self, x):
"""
Applies the Leaky ReLU activation function.
Args:
x (np.ndarray): Input array.
Returns:
np.ndarray: Output after applying Leaky ReLU.
"""
self._cache["x"] = x
return np.where(x > 0, x, self.alpha * x).astype(DEFAULT_DTYPE)
def backward(self, dy):
"""
Computes the gradient of the Leaky ReLU function.
Args:
dy (np.ndarray): Upstream gradient.
Returns:
np.ndarray: Gradient with respect to the input.
"""
x = self._cache["x"]
dx = np.ones_like(x)
dx[x < 0] = self.alpha
return dy * dx
@register_activation("softmax")
@register_layer("Softmax")
class Softmax(Layer):
"""Softmax activation function."""
def __init__(self, axis: int = -1):
"""
Initializes the Softmax layer.
Args:
axis (int): The axis along which to compute the softmax.
"""
super().__init__()
self.axis = axis
def forward(self, x):
"""
Applies the Softmax activation function (numerically stable).
Args:
x (np.ndarray): Input array.
Returns:
np.ndarray: Output after applying Softmax.
"""
# stable softmax
x_shift = x - np.max(x, axis=self.axis, keepdims=True)
exps = np.exp(x_shift)
sums = np.sum(exps, axis=self.axis, keepdims=True)
out = exps / sums
self._cache["out"] = out
return out.astype(DEFAULT_DTYPE)
def backward(self, dy):
"""
Computes the gradient of the Softmax function.
Args:
dy (np.ndarray): Upstream gradient.
Returns:
np.ndarray: Gradient with respect to the input.
"""
# General softmax backward: J = diag(s) - s s^T; dy @ J
s = self._cache["out"]
# Works for 2D (batch, classes) or higher dims along axis
# Flatten axis to -1 for computation
orig_shape = s.shape
axis = self.axis if self.axis >= 0 else s.ndim + self.axis
s2d = s.reshape(-1, orig_shape[axis])
dy2d = dy.reshape(-1, orig_shape[axis])
# gradient per row: dy - sum(dy*s) * s
dot = np.sum(dy2d * s2d, axis=1, keepdims=True)
dx2d = s2d * (dy2d - dot)
return dx2d.reshape(orig_shape)
# ------------------------------------------------------------
# Core layers
# ------------------------------------------------------------
@register_layer("Dense")
class Dense(Layer):
"""Fully connected layer."""
def __init__(
self,
units: int,
use_bias: bool = True,
kernel_initializer: str = "glorot_uniform",
bias_initializer: str = "zeros",
seed: Optional[int] = None,
):
"""
Initializes the Dense layer.
Args:
units (int): Number of output units.
use_bias (bool): Whether to include a bias vector.
kernel_initializer (str): Initializer for the kernel weights.
bias_initializer (str): Initializer for the bias vector.
seed (int, optional): Random seed for initialization.
"""
super().__init__()
self.units = units
self.use_bias = use_bias
self.kernel_initializer = kernel_initializer
self.bias_initializer = bias_initializer
self.seed = seed
def build(self, input_shape: Tuple[int, ...], **kwargs) -> Tuple[int, ...]:
"""
Builds the layer parameters based on input shape.
Args:
input_shape (tuple): The shape of the input tensor.
Returns:
tuple: The output shape of the layer.
"""
assert len(input_shape) == 2, "Dense expects (batch, features)"
in_dim = input_shape[1]
W = get_initializer(self.kernel_initializer)(
(in_dim, self.units), seed=self.seed
)
self.W = Parameter(W, name="kernel")
self._params.append(self.W)
if self.use_bias:
b = get_initializer(self.bias_initializer)((self.units,), seed=self.seed)
self.b = Parameter(b, name="bias")
self._params.append(self.b)
else:
self.b = None
self.built = True
return (input_shape[0], self.units)
def forward(self, x):
"""
Performs the forward pass of the Dense layer.
Args:
x (np.ndarray): Input tensor.
Returns:
np.ndarray: Transformed output tensor.
"""
self._cache["x"] = x
out = x @ self.W.data
if self.b is not None:
out = out + self.b.data
return out.astype(DEFAULT_DTYPE)
def backward(self, dy):
"""
Computes the gradient of the Dense layer.
Args:
dy (np.ndarray): Upstream gradient.
Returns:
np.ndarray: Gradient with respect to the input.
"""
x = self._cache["x"]
# grads
self.W.grad += x.T @ dy
if self.b is not None:
self.b.grad += np.sum(dy, axis=0)
dx = dy @ self.W.data.T
return dx
# ---- im2col/col2im utilities ----
def get_output_dim(in_size, k, stride, pad, dilation):
"""Calculates output dimension for a spatial operation."""
# For 'valid' pad: pad=0; for 'same': computed elsewhere
return (in_size + 2 * pad - dilation * (k - 1) - 1) // stride + 1
def compute_same_padding(in_size, k, stride, dilation):
"""Calculates padding required for 'same' convolution/pooling."""
# Output size ceil(in/stride); padding to make that
out_size = int(np.ceil(in_size / stride))
pad_needed = max(0, (out_size - 1) * stride + dilation * (k - 1) + 1 - in_size)
# split pad into left/right (we'll use symmetric here)
pad_left = pad_needed // 2
pad_right = pad_needed - pad_left
return pad_left, pad_right, out_size
def im2col_indices(
x, kH, kW, pad_h, pad_w, stride_h, stride_w, dilation_h=1, dilation_w=1
):
"""Transforms image input to column format for efficient convolution."""
# x: (N, C, H, W)
N, C, H, W = x.shape
eff_kH = dilation_h * (kH - 1) + 1
eff_kW = dilation_w * (kW - 1) + 1
out_h = (H + pad_h * 2 - eff_kH) // stride_h + 1
out_w = (W + pad_w * 2 - eff_kW) // stride_w + 1
x_padded = np.pad(
x, ((0, 0), (0, 0), (pad_h, pad_h), (pad_w, pad_w)), mode="constant"
)
i0 = np.repeat(np.arange(kH), kW)
i0 = np.tile(i0, C)
i1 = stride_h * np.repeat(np.arange(out_h), out_w)
j0 = np.tile(np.arange(kW), kH * C)
j1 = stride_w * np.tile(np.arange(out_w), out_h)
i = i0.reshape(-1, 1) * dilation_h + i1.reshape(1, -1)
j = j0.reshape(-1, 1) * dilation_w + j1.reshape(1, -1)
k = np.repeat(np.arange(C), kH * kW).reshape(-1, 1)
cols = x_padded[:, k, i, j] # (N, C*kH*kW, out_h*out_w)
cols = cols.transpose(1, 2, 0).reshape(C * kH * kW, N * out_h * out_w)
return cols, out_h, out_w
def col2im_indices(
cols, x_shape, kH, kW, pad_h, pad_w, stride_h, stride_w, dilation_h=1, dilation_w=1
):
"""Transforms column data back into original image shape."""
N, C, H, W = x_shape
eff_kH = dilation_h * (kH - 1) + 1
eff_kW = dilation_w * (kW - 1) + 1
out_h = (H + pad_h * 2 - eff_kH) // stride_h + 1
out_w = (W + pad_w * 2 - eff_kW) // stride_w + 1
cols_reshaped = cols.reshape(C * kH * kW, N, out_h * out_w).transpose(1, 0, 2)
x_padded = np.zeros((N, C, H + 2 * pad_h, W + 2 * pad_w), dtype=cols.dtype)
i0 = np.repeat(np.arange(kH), kW)
i0 = np.tile(i0, C)
i1 = stride_h * np.repeat(np.arange(out_h), out_w)
j0 = np.tile(np.arange(kW), kH * C)
j1 = stride_w * np.tile(np.arange(out_w), out_h)
i = i0.reshape(-1, 1) * dilation_h + i1.reshape(1, -1)
j = j0.reshape(-1, 1) * dilation_w + j1.reshape(1, -1)
k = np.repeat(np.arange(C), kH * kW).reshape(-1, 1)
for n in range(N):
x_padded[n, k, i, j] += cols_reshaped[n]
return x_padded[:, :, pad_h : pad_h + H, pad_w : pad_w + W]
@register_layer("Conv2D")
class Conv2D(Layer):
"""2D Convolution layer."""
def __init__(
self,
filters: int,
kernel_size: int | Tuple[int, int],
stride: int | Tuple[int, int] = 1,
padding: str | int | Tuple[int, int] = "valid",
dilation: int | Tuple[int, int] = 1,
use_bias: bool = True,
kernel_initializer: str = "he_normal",
bias_initializer: str = "zeros",
seed: Optional[int] = None,
):
"""
Initializes the Conv2D layer.
Args:
filters (int): Number of filters.
kernel_size (int or tuple): Size of the convolution kernel.
stride (int or tuple): Stride of the convolution.
padding (str, int, or tuple): Padding strategy or size.
dilation (int or tuple): Dilation rate.
use_bias (bool): Whether to include bias.
kernel_initializer (str): Initializer for kernel weights.
bias_initializer (str): Initializer for bias weights.
seed (int, optional): Random seed.
"""
super().__init__()
self.filters = filters
if isinstance(kernel_size, int):
self.kH = self.kW = kernel_size
else:
self.kH, self.kW = kernel_size
if isinstance(stride, int):
self.sH = self.sW = stride
else:
self.sH, self.sW = stride
self.padding = padding
if isinstance(dilation, int):
self.dH = self.dW = dilation
else:
self.dH, self.dW = dilation
self.use_bias = use_bias
self.kernel_initializer = kernel_initializer
self.bias_initializer = bias_initializer
self.seed = seed
def _compute_padding(self, H, W):
"""Internal helper to calculate padding."""
if self.padding == "valid":
return (0, 0, 0, 0)
if self.padding == "same":
ph1, ph2, out_h = compute_same_padding(H, self.kH, self.sH, self.dH)
pw1, pw2, out_w = compute_same_padding(W, self.kW, self.sW, self.dW)
# symmetric padding; using total pads
return (ph1, pw1, ph2, pw2)
if isinstance(self.padding, int):
return (self.padding, self.padding, self.padding, self.padding)
if isinstance(self.padding, tuple):
pH, pW = self.padding
return (pH, pW, pH, pW)
raise ValueError("Unsupported padding")
def build(self, input_shape: Tuple[int, ...], **kwargs) -> Tuple[int, ...]:
"""
Builds the layer parameters and computes output shape.
Args:
input_shape (tuple): The input shape (N, C, H, W).
Returns:
tuple: The output shape (N, F, out_h, out_w).
"""
# input: (N, C, H, W)
assert len(input_shape) == 4, "Conv2D expects (N, C, H, W)"
N, C, H, W = input_shape
self.in_channels = C
pad_top, pad_left, pad_bottom, pad_right = self._compute_padding(H, W)
eff_kH = self.dH * (self.kH - 1) + 1
eff_kW = self.dW * (self.kW - 1) + 1
out_h = (H + pad_top + pad_bottom - eff_kH) // self.sH + 1
out_w = (W + pad_left + pad_right - eff_kW) // self.sW + 1
Wshape = (self.filters, C, self.kH, self.kW)
W = get_initializer(self.kernel_initializer)(Wshape, seed=self.seed)
self.W = Parameter(W, name="kernel")
self._params.append(self.W)
if self.use_bias:
b = get_initializer(self.bias_initializer)((self.filters,), seed=self.seed)
self.b = Parameter(b, name="bias")
self._params.append(self.b)
else:
self.b = None
self.pad = (pad_top, pad_left, pad_bottom, pad_right)
self.built = True
return (N, self.filters, out_h, out_w)
def forward(self, x):
"""
Performs the forward pass of the Conv2D layer.
Args:
x (np.ndarray): Input tensor.
Returns:
np.ndarray: Transformed output tensor.
"""
self._cache["x_shape"] = x.shape
pt, pl, pb, pr = self.pad
cols, out_h, out_w = im2col_indices(
x, self.kH, self.kW, pt, pl, self.sH, self.sW, self.dH, self.dW
)
W_col = self.W.data.reshape(self.filters, -1)
out = W_col @ cols # (filters, N*out_h*out_w)
if self.b is not None:
out += self.b.data[:, None]
N = x.shape[0]
out = out.reshape(self.filters, -1, N).transpose(2, 0, 1)
out = out.reshape(N, self.filters, out_h, out_w)
self._cache["cols"] = cols
self._cache["out_shape"] = (N, self.filters, out_h, out_w)
return out.astype(DEFAULT_DTYPE)
def backward(self, dy):
"""
Computes the gradient of the Conv2D layer.
Args:
dy (np.ndarray): Upstream gradient.
Returns:
np.ndarray: Gradient with respect to the input.
"""
cols = self._cache["cols"]
N, F, out_h, out_w = self._cache["out_shape"]
W_col = self.W.data.reshape(self.filters, -1)
dy_reshaped = dy.reshape(N, F, out_h * out_w).transpose(1, 2, 0).reshape(F, -1)
# gradients
self.W.grad += (dy_reshaped @ cols.T).reshape(self.W.data.shape)
if self.b is not None:
self.b.grad += np.sum(dy_reshaped, axis=1)
dcols = W_col.T @ dy_reshaped
pt, pl, pb, pr = self.pad
dx = col2im_indices(
dcols,
self._cache["x_shape"],
self.kH,
self.kW,
pt,
pl,
self.sH,
self.sW,
self.dH,
self.dW,
)
return dx
@register_layer("MaxPool2D")
class MaxPool2D(Layer):
"""2D Max Pooling layer."""
def __init__(
self,
pool_size: int | Tuple[int, int] = 2,
stride: Optional[int | Tuple[int, int]] = None,
padding: str | int | Tuple[int, int] = "valid",
):
"""
Initializes the MaxPool2D layer.
Args:
pool_size (int or tuple): Window size for pooling.
stride (int or tuple, optional): Stride of pooling.
padding (str, int, or tuple): Padding strategy.
"""
super().__init__()
if isinstance(pool_size, int):
self.kH = self.kW = pool_size
else:
self.kH, self.kW = pool_size
if stride is None:
self.sH = self.kH
self.sW = self.kW
elif isinstance(stride, int):
self.sH = self.sW = stride
else:
self.sH, self.sW = stride
self.padding = padding
def _compute_padding(self, H, W):
"""Internal helper to calculate padding."""
if self.padding == "valid":
return (0, 0, 0, 0)
if self.padding == "same":
ph1, ph2, _ = compute_same_padding(H, self.kH, self.sH, 1)
pw1, pw2, _ = compute_same_padding(W, self.kW, self.sW, 1)
return (ph1, pw1, ph2, pw2)
if isinstance(self.padding, int):
return (self.padding, self.padding, self.padding, self.padding)
if isinstance(self.padding, tuple):
pH, pW = self.padding
return (pH, pW, pH, pW)
raise ValueError("Unsupported padding")
def build(self, input_shape, **kwargs):
"""
Builds the layer and computes output shape.
Args:
input_shape (tuple): Input shape.
Returns:
tuple: Output shape.
"""
N, C, H, W = input_shape
pt, pl, pb, pr = self._compute_padding(H, W)
out_h = (H + pt + pb - self.kH) // self.sH + 1
out_w = (W + pl + pr - self.kW) // self.sW + 1
self.pad = (pt, pl, pb, pr)
self.built = True
return (N, C, out_h, out_w)
def forward(self, x):
"""
Performs the forward pass of the MaxPool2D layer.
Args:
x (np.ndarray): Input tensor.
Returns:
np.ndarray: Transformed output tensor.
"""
N, C, H, W = x.shape
pt, pl, pb, pr = self.pad
x_padded = np.pad(
x,
((0, 0), (0, 0), (pt, pb), (pl, pr)),
mode="constant",
constant_values=-np.inf,
)
out_h = (H + pt + pb - self.kH) // self.sH + 1
out_w = (W + pl + pr - self.kW) // self.sW + 1
self._cache["x_shape"] = x.shape
self._cache["pad"] = self.pad
out = np.empty((N, C, out_h, out_w), dtype=DEFAULT_DTYPE)
self._cache["max_idx"] = np.zeros_like(out, dtype=np.int32)
for i in range(out_h):
for j in range(out_w):
h0 = i * self.sH
w0 = j * self.sW
window = x_padded[
:, :, h0 : h0 + self.kH, w0 : w0 + self.kW
] # (N, C, kH, kW)
flat = window.reshape(N, C, -1)
idx = np.argmax(flat, axis=2)
self._cache["max_idx"][:, :, i, j] = idx
out[:, :, i, j] = np.take_along_axis(
flat, idx[..., None], axis=2
).squeeze(-1)
return out
def backward(self, dy):
"""
Computes the gradient of the MaxPool2D layer.
Args:
dy (np.ndarray): Upstream gradient.
Returns:
np.ndarray: Gradient with respect to the input.
"""
N, C, H, W = self._cache["x_shape"]
pt, pl, pb, pr = self._cache["pad"]
out_h, out_w = dy.shape[2], dy.shape[3]
dx_padded = np.zeros((N, C, H + pt + pb, W + pl + pr), dtype=DEFAULT_DTYPE)
idx = self._cache["max_idx"]
for i in range(out_h):
for j in range(out_w):
h0 = i * self.sH
w0 = j * self.sW
mask = np.zeros((N, C, self.kH * self.kW), dtype=DEFAULT_DTYPE)
flat_idx = idx[:, :, i, j]
mask.reshape(N * C, -1)[np.arange(N * C), flat_idx.reshape(-1)] = dy[
:, :, i, j
].reshape(-1)
dx_padded[:, :, h0 : h0 + self.kH, w0 : w0 + self.kW] += mask.reshape(
N, C, self.kH, self.kW
)
return dx_padded[:, :, pt : pt + H, pl : pl + W]
@register_layer("AvgPool2D")
class AvgPool2D(Layer):
"""2D Average Pooling layer."""
def __init__(
self,
pool_size: int | Tuple[int, int] = 2,
stride: Optional[int | Tuple[int, int]] = None,
padding: str | int | Tuple[int, int] = "valid",
):
"""
Initializes the AvgPool2D layer.
Args:
pool_size (int or tuple): The size of the pooling window.
stride (int or tuple, optional): The stride of the pooling operation.
padding (str, int, or tuple): Padding configuration.
"""
super().__init__()
if isinstance(pool_size, int):
self.kH = self.kW = pool_size
else:
self.kH, self.kW = pool_size
if stride is None:
self.sH = self.kH
self.sW = self.kW
elif isinstance(stride, int):
self.sH = self.sW = stride
else:
self.sH, self.sW = stride
self.padding = padding
def _compute_padding(self, H, W):
"""Internal helper to calculate padding."""
if self.padding == "valid":
return (0, 0, 0, 0)
if self.padding == "same":
ph1, ph2, _ = compute_same_padding(H, self.kH, self.sH, 1)
pw1, pw2, _ = compute_same_padding(W, self.kW, self.sW, 1)
return (ph1, pw1, ph2, pw2)
if isinstance(self.padding, int):
return (self.padding, self.padding, self.padding, self.padding)
if isinstance(self.padding, tuple):
pH, pW = self.padding
return (pH, pW, pH, pW)
raise ValueError("Unsupported padding")
def build(self, input_shape, **kwargs):
"""Builds the layer output shape."""
N, C, H, W = input_shape
pt, pl, pb, pr = self._compute_padding(H, W)
out_h = (H + pt + pb - self.kH) // self.sH + 1
out_w = (W + pl + pr - self.kW) // self.sW + 1
self.pad = (pt, pl, pb, pr)
self.built = True
return (N, C, out_h, out_w)
def forward(self, x):
"""
Performs the forward pass of the AvgPool2D layer.
Args:
x (np.ndarray): Input tensor.
Returns:
np.ndarray: Pooled output tensor.
"""
N, C, H, W = x.shape
pt, pl, pb, pr = self.pad
x_padded = np.pad(
x,
((0, 0), (0, 0), (pt, pb), (pl, pr)),
mode="constant",
constant_values=0.0,
)
out_h = (H + pt + pb - self.kH) // self.sH + 1
out_w = (W + pl + pr - self.kW) // self.sW + 1
out = np.empty((N, C, out_h, out_w), dtype=DEFAULT_DTYPE)
for i in range(out_h):
for j in range(out_w):
h0 = i * self.sH
w0 = j * self.sW
window = x_padded[:, :, h0 : h0 + self.kH, w0 : w0 + self.kW]
out[:, :, i, j] = np.mean(window, axis=(2, 3))
self._cache["x_shape"] = x.shape
self._cache["pad"] = self.pad