-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtensor_operations.py
904 lines (664 loc) · 25.6 KB
/
tensor_operations.py
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
from typing import List
import numpy as np
# Tensor class, with __init__, backward, magic methods, and utils:
class Tensor:
def __init__(self, data, requires_grad = False, operation = None) -> None:
self._data = array(data)
self.requires_grad = requires_grad
self.operation = operation
self.children = []
self.shape = self._data.shape
if self.requires_grad:
self.grad = np.zeros_like(data)
def __repr__(self):
return f"""({self._data}, requires_grad = {self.requires_grad})"""
def data(self):
return self._data
def backward(self, grad = None, z = None):
if not self.requires_grad:
return "this tensor has requires_grad set to False"
if grad is None:
grad = np.ones_like(self._data)
self.grad += grad
if z is not None:
self.children.remove(z)
if self.operation:
if not self.children:
self.operation.backward(self.grad, self)
def tolist(self):
''' Turns the Tensor into a python list. '''
return self._data.tolist()
def toarray(self):
''' Turns the Tensor into a numpy array. '''
return self._data
def zero_grad(self):
''' Reset the Tensor's gradients to zero. '''
self.grad = np.zeros_like(self._data)
def zero_grad_tree(self):
''' Reset the gradients of this Tensor, and of all of the Tensors that led to it. '''
self.zero_grad()
if self.operation:
for parent in self.operation.parents:
parent.zero_grad_tree()
self.operation = None
def __add__(self, other):
""" New = self + other """
op = Add()
return op.forward(self, tensor(other))
def __radd__(self, other):
""" New = other + self """
op = Add()
return op.forward(self, tensor(other))
def __iadd__(self, other):
""" self += other """
op = Add()
return op.forward(self, tensor(other))
def __sub__(self, other):
""" New = self - other """
return self + -other
def __rsub__(self, other):
""" New = other - self """
return other + -self
def __isub__(self, other):
""" self -= other """
return self + -other
def __neg__(self):
""" self = -self """
op = Neg()
return op.forward(self)
def __mul__(self, other):
""" New = self * other """
op = Mul()
return op.forward(self, tensor(other))
def __rmul__(self, other):
""" New = other * self """
op = Mul()
return op.forward(self, tensor(other))
def __imul__(self, other):
""" self *= other """
op = Mul()
return op.forward(self, tensor(other))
def __matmul__(self, other):
""" New = self @ other """
op = MatMul()
return op.forward(self, tensor(other))
def __truediv__(self, other):
""" New = self / other """
op = Div()
return op.forward(self, tensor(other))
def __getitem__(self, index):
""" New = self[index] """
op = Slice()
return op.forward(self, index)
def __gt__(self, other):
""" New = self > other """
return self._data > array(other)
def max(self, dim, keepdims=False):
"""
Returns the largest values across the "dim" dimention.
Example: (B, T, D), dim = 1 -> (B, D).
@param dim (int): dimention to be reduced (only largest remains).
@param keepdims (bool): wether to broadcast result to same shape as input.
"""
op = Max()
return op.forward(self, dim, keepdims=keepdims)
def sum(self, dim=-1, keepdims=False):
"""
Returns the sum of all values across the "dim" dimention.
Example: (B, T, D), dim = 1 -> (B, D).
@param dim (int): dimention to be summed across.
@param keepdims (bool): wether to broadcast result to same shape as input.
"""
op = Sum()
return op.forward(self, dim, keepdims=keepdims)
def mean(self, dim=-1, keepdims=False):
"""
Returns the mean of all values across the "dim" dimention.
Example: (B, T, D), dim = 1 -> (B, D).
@param dim (int): dimention to be averaged across.
@param keepdims (bool): wether to broadcast result to same shape as input.
"""
op = Mean()
return op.forward(self, dim, keepdims=keepdims)
def var(self, dim=-1, keepdims=False):
"""
Returns the variance of all values across the "dim" dimention.
Example: (B, T, D), dim = 1 -> (B, D).
@param dim (int): dimention the variance will be computed across.
@param keepdims (bool): wether to broadcast result to same shape as input.
"""
op = Var()
return op.forward(self, dim, keepdims=keepdims)
def reshape(self, *shape):
"""
Returns the original tensor reshaped to the new shape given.
Example: (16, 8, 4), *shape =(2, 32, 8) -> (2, 32, 8)
@param *shape (integers): new shape of the tensor.
"""
op = Reshape()
return op.forward(self, shape)
def transpose(self, *dims):
"""
Returns the original tensor with the two given dimentions transposed.
Example: (16, 8, 4), *dims=(-2,-1) -> (16, 4, 8)
@param *dims (integers): two dimentions to be transposed.
"""
op = Transpose()
return op.forward(self, *dims)
def masked_fill(self, condition, value):
"""
Returns the original tensor with the values where condition is True set to "value".
@param condition (Array-like): two dimentions to be transposed.
@param value (float): value to fill Tensor with, where condition is True.
"""
op = MaskedFill()
return op.forward(self, array(condition), value )
# Parameter subclass, inherits from Tensor:
class Parameter(Tensor):
''' Subclass of Tensor which always tracks gradients. '''
def __init__(self, data, requires_grad = True, operation = None) -> None:
super().__init__(data, requires_grad=requires_grad, operation=operation)
# Operations between two tensors:
class Add:
def __init__(self) -> None:
pass
def forward(self, a, b):
requires_grad = a.requires_grad or b.requires_grad
# Get new Tensor's data:
data = a._data + b._data
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = (a, b)
a.children.append(z)
b.children.append(z)
self.cache = (a, b)
return z
def backward(self, dz, z):
a, b = self.cache
# Find gradients relative to "a", and pass it downstream:
if a.requires_grad:
da = dz
# Rescale gradient to have the same shape as "a":
grad_dim = len(dz.shape)
in_dim = len(a.shape)
for _ in range(grad_dim - in_dim):
da = da.sum(axis=0)
for n, dim in enumerate(a.shape):
if dim == 1:
da = da.sum(axis=n, keepdims=True)
a.backward(da, z)
# Find gradients relative to "b", and pass it downstream:
if b.requires_grad:
db = dz
# Rescale gradient to have the same shape as "b":
grad_dim = len(dz.shape)
in_dim = len(b.shape)
for _ in range(grad_dim - in_dim):
db = db.sum(axis=0)
for n, dim in enumerate(b.shape):
if dim == 1:
db = db.sum(axis=n, keepdims=True)
b.backward(db, z)
class Neg:
def __init__(self) -> None:
pass
def forward(self, a):
requires_grad = a.requires_grad
# Get new Tensor's data:
data = - a._data
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = (a,)
a.children.append(z)
self.cache = a
return z
def backward(self, dz, z):
a = self.cache
# Find gradients relative to "a", and pass it downstream:
if a.requires_grad:
da = -dz
a.backward(da, z)
class Mul:
def __init__(self) -> None:
pass
def forward(self, a, b):
requires_grad = a.requires_grad or b.requires_grad
# Get new Tensor's data:
data = a._data * b._data
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = (a, b)
a.children.append(z)
b.children.append(z)
self.cache = (a, b)
return z
def backward(self, dz, z):
a, b = self.cache
# Find gradients relative to "a", and pass it downstream:
if a.requires_grad:
# d/da(a*b) = b, apply chain rule:
da = dz * b._data
# Rescale gradient to have the same shape as "a":
grad_dim = len(dz.shape)
in_dim = len(a.shape)
for _ in range(grad_dim - in_dim):
da = da.sum(axis=0)
for n, dim in enumerate(a.shape):
if dim == 1:
da = da.sum(axis=n, keepdims=True)
a.backward(da, z)
# Find gradients relative to "b", and pass it downstream:
if b.requires_grad:
# d/db(a*b) = a, apply chain rule:
db = dz * a._data
# Rescale gradient to have the same shape as "b":
grad_dim = len(dz.shape)
in_dim = len(b.shape)
for _ in range(grad_dim - in_dim):
db = db.sum(axis=0)
for n, dim in enumerate(b.shape):
if dim == 1:
db = db.sum(axis=n, keepdims=True)
b.backward(db, z)
class Div:
def __init__(self) -> None:
pass
def forward(self, a, b):
requires_grad = a.requires_grad or b.requires_grad
# Get new Tensor's data:
data = a._data / b._data
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = (a, b)
a.children.append(z)
b.children.append(z)
self.cache = (a, b)
return z
def backward(self, dz, z):
a, b = self.cache
# Find gradients relative to "a", and pass it downstream:
if a.requires_grad:
# d/da(a/b) = (1/b), apply chain rule:
da = dz * (1 / b._data)
# Rescale gradient to have the same shape as "a":
grad_dim = len(dz.shape)
in_dim = len(a.shape)
for _ in range(grad_dim - in_dim):
da = da.sum(axis=0)
for n, dim in enumerate(a.shape):
if dim == 1:
da = da.sum(axis=n, keepdims=True)
a.backward(da, z)
# Find gradients relative to "b", and pass it downstream:
if b.requires_grad:
# d/db(a/b) = -(a/b^2), apply chain rule:
db = - dz * a._data / (b._data ** 2)
# Rescale gradient to have the same shape as "b":
grad_dim = len(dz.shape)
in_dim = len(b.shape)
for _ in range(grad_dim - in_dim):
db = db.sum(axis=0)
for n, dim in enumerate(b.shape):
if dim == 1:
db = db.sum(axis=n, keepdims=True)
b.backward(db, z)
class MatMul:
def __init__(self) -> None:
pass
def forward(self, a, b):
requires_grad = a.requires_grad or b.requires_grad
# Get new Tensor's data:
data = a._data @ b._data
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = (a, b)
a.children.append(z)
b.children.append(z)
self.cache = (a, b)
return z
def backward(self, dz, z):
a, b = self.cache
# Find gradients relative to "a", and pass it downstream:
if a.requires_grad:
# Backprop through the matmul:
da = dz @ b._data.swapaxes(-1,-2)
# Get difference between "a" size and upstream "da" size, to broadcast grad into "a":
in_dim = len(a.shape)
grad_dim = len(da.shape)
for _ in range(grad_dim - in_dim):
da = da.sum(axis=0)
a.backward(da, z)
# Find gradients relative to "b", and pass it downstream:
if b.requires_grad:
# Backprop through the matmul:
db = a._data.swapaxes(-1,-2) @ dz
# Get difference between "b" size and upstream "db" size, to broadcast grad into "b":
in_dim = len(b.shape)
grad_dim = len(db.shape)
for _ in range(grad_dim - in_dim):
db = db.sum(axis=0)
b.backward(db, z)
# Element-wise operations:
class Exp:
def __init__(self) -> None:
pass
def forward(self, a):
requires_grad = a.requires_grad
# Get new Tensor's data:
data = np.exp(a._data)
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = (a,)
a.children.append(z)
self.cache = (a, data)
return z
def backward(self, dz, z):
a, data = self.cache
# Find gradients relative to "a", and pass it downstream:
if a.requires_grad:
# d/da(e^a) = e^a, apply the chain rule to the derivative of e^a:
da = data * dz
a.backward(da, z)
class Log:
def __init__(self) -> None:
pass
def forward(self, a):
requires_grad = a.requires_grad
# Get new Tensor's data:
data = np.log(a._data)
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = (a,)
a.children.append(z)
self.cache = (a)
return z
def backward(self, dz, z):
a = self.cache
# Find gradients relative to "a", and pass it downstream:
if a.requires_grad:
# d/da(ln(a)) = (1/a), apply the chain rule to the derivative of the natural log:
da = (1 / a._data) * dz
a.backward(da, z)
class Sqrt:
def __init__(self) -> None:
pass
def forward(self, a):
requires_grad = a.requires_grad
# Get new Tensor's data:
data = np.sqrt(a._data)
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = (a,)
a.children.append(z)
self.cache = (a, data)
return z
def backward(self, dz, z):
a, data = self.cache
# Find gradients relative to "a", and pass it downstream:
if a.requires_grad:
# d/dx(sqrt(a)) = (1/2) * (1/a), apply the chain rule to the derivative of the square root:
da = (1 / 2) * (1 / data) * dz
a.backward(da, z)
# Statistics operations:
class Sum:
def __init__(self) -> None:
pass
def forward(self, a, dim, keepdims):
requires_grad = a.requires_grad
# Get new Tensor's data:
data = a._data.sum(axis=dim, keepdims=keepdims)
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = (a,)
a.children.append(z)
self.cache = (a)
return z
def backward(self, dz, z):
a = self.cache
# Find gradients relative to "a", and pass it downstream:
if a.requires_grad:
# Expand upstream gradients to the shape of "a":
da = np.ones(a.shape) * dz
a.backward(da, z)
class Mean:
def __init__(self) -> None:
pass
def forward(self, a, dim, keepdims):
requires_grad = a.requires_grad
# Get new Tensor's data:
data = a._data.mean(axis=dim, keepdims=keepdims)
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = (a,)
a.children.append(z)
self.cache = (a, dim)
return z
def backward(self, dz, z):
a, dim = self.cache
# Find gradients relative to "a", and pass it downstream:
if a.requires_grad:
# Propagate through the mean(x) operation:
da = np.ones(a.shape) * dz
da /= np.prod(np.array(a.shape)[dim])
a.backward(da, z)
class Max:
def __init__(self) -> None:
pass
def forward(self, a, dim, keepdims=False):
requires_grad = a.requires_grad
# Get new Tensor's data:
data = np.max(a._data, axis=dim, keepdims=keepdims)
if keepdims:
data = np.ones(a.shape) * data
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = (a,)
a.children.append(z)
self.cache = (a, data, dim)
return z
def backward(self, dz, z):
a, data, dim = self.cache
# Find gradients relative to "a", and pass it downstream:
if a.requires_grad:
if a.shape != da.shape:
# Brodcast upstream derivative to the size of "a":
dz = np.expand_dims(dz, axis=dim)
dz = dz * np.ones_like(a._data)
# Brodcast upstream output (max) to the size of "a":
max = np.expand_dims(data, axis=dim)
max = max * np.ones_like(a._data)
# Add upstream gradients to the [max] values:
da = dz * np.equal(a._data, max)
a.backward(da, z)
class Var:
def __init__(self) -> None:
pass
def forward(self, a, dim, keepdims):
requires_grad = a.requires_grad
# Get new Tensor's data:
data = a._data.var(axis=dim, keepdims=keepdims)
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = (a,)
a.children.append(z)
self.cache = (a, dim)
return z
def backward(self, dz, z):
a, dim = self.cache
# Find gradients relative to "a", and pass it downstream:
if a.requires_grad:
# Propagate through the var(x) operation:
da = np.ones(a.shape) * dz
da = da * 2 * (a._data - a._data.mean(axis=dim, keepdims=True)) / np.prod(np.array(a.shape)[dim])
a.backward(da, z)
# Tensor Operations:
class Reshape:
def __init__(self) -> None:
pass
def forward(self, a, shape):
requires_grad = a.requires_grad
# Get new Tensor's data:
data = a._data.reshape(*shape)
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = (a,)
a.children.append(z)
self.cache = (a)
return z
def backward(self, dz, z):
a = self.cache
# Find gradients relative to "a", and pass it downstream:
if a.requires_grad:
# Reshape upstream gradients:
da = dz.reshape(a.shape)
a.backward(da, z)
class Transpose:
def __init__(self) -> None:
pass
def forward(self, a, *dims):
requires_grad = a.requires_grad
# Get new Tensor's data:
data = a._data.swapaxes(*dims)
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = (a,)
a.children.append(z)
self.cache = (a, dims)
return z
def backward(self, dz, z):
a, dims = self.cache
# Find gradients relative to "a", and pass it downstream:
if a.requires_grad:
# Transpose upstream gradients:
da = dz.swapaxes(*dims)
a.backward(da, z)
class Cat:
def __init__(self) -> None:
pass
def forward(self, tensors: tuple, dim: int):
requires_grad = False
for tensor in tensors:
if tensor.requires_grad == True:
requires_grad = True
# Get new Tensor's data:
data = np.concatenate([tensor._data for tensor in tensors], axis=dim)
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = tensors
for tensor in tensors:
tensor.children.append(z)
self.cache = (tensors, dim)
return z
def backward(self, dz, z):
tensors, dim = self.cache
dz = np.split(dz, len(tensors), dim)
# Find gradients relative to each tensor in "tensor", and pass it downstream:
for i, tensor in enumerate(tensors):
if tensor.requires_grad:
# For every tensor that generated the output, get gradients relative to that part of "dz":
di = dz[i]
tensor.backward(di, z)
class Stack:
def __init__(self) -> None:
pass
def forward(self, tensors: tuple, dim: int):
# Verify if any original tensors requires grad:
requires_grad = False
for tensor in tensors:
if tensor.requires_grad == True:
requires_grad = True
# Get new Tensor's data:
data = np.stack([tensor._data for tensor in tensors], axis=dim)
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = tensors
for tensor in tensors:
tensor.children.append(z)
self.cache = (tensors, dim)
return z
def backward(self, dz, z):
tensors, dim = self.cache
dz = np.split(dz, len(tensors), dim)
# Find gradients relative to each tensor in "tensor", and pass it downstream:
for i, tensor in enumerate(tensors):
if tensor.requires_grad:
# For every tensor that generated the stack, get gradients relative to that part of "dz":
di = dz[i].reshape(tensor._data.shape)
tensor.backward(di, z)
class MaskedFill:
def __init__(self) -> None:
pass
def forward(self, a, condition, value):
requires_grad = a.requires_grad
# Get new Tensor's data:
data = np.where(condition, a._data, value)
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = (a,)
a.children.append(z)
self.cache = (a)
return z
def backward(self, dz, z):
a = self.cache
# Find gradients relative to "a", and pass it downstream:
if a.requires_grad:
# Because some activations are just set to a value, this operation is not differentiable.
da = dz
a.backward(da, z)
class Slice:
def __init__(self) -> None:
pass
def forward(self, a, index):
requires_grad = a.requires_grad
# Get new Tensor's data:
data = a._data[index]
# Create new Tensor:
z = Tensor(data, requires_grad=requires_grad, operation=self)
# Add new Tensors to "children" and old Tensors to "parents":
self.parents = (a,)
a.children.append(z)
self.cache = (a, index)
return z
def backward(self, dz, z):
a, index = self.cache
# Find gradients relative to "a", and pass it downstream:
if a.requires_grad:
# Add upstream gradients to [index] part of da.
da = np.zeros_like(a._data)
da[index] = dz
a.backward(da, z)
# Some helper functions to transition between iterable data types:
def list(data):
if isinstance(data, List):
return data
else:
return data.tolist()
def array(data):
if isinstance(data, np.ndarray):
return data
if isinstance(data, Tensor):
return data.toarray()
else:
return np.array(data)
def tensor(data):
if isinstance(data, Tensor):
return data
else:
return Tensor(data)