-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnn_ops.py
1419 lines (1172 loc) · 48.9 KB
/
nn_ops.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
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
"""Neural network related Operations."""
import numpy as np
from .generic_ops import Const
from .mixins import _PickFirstAmongCompatibleShapes, _ShapeAsIs
from .operation import Operation
from .tensor_shape import TensorShape
class _Filters2DBase(Operation):
"""Base class for 2-D filters-based Operations (Conv2D, MaxPool2D, AvgPool2D,
etc.).
"""
def __init__(self, strides, padding, input_list, graph=None, name=None):
"""Constructor.
Args:
strides (tuple): strides in height and width dimension.
padding (string): padding scheme (either "SAME" or "VALID").
"""
self._strides = strides
self._padding = padding
super(_Filters2DBase, self).__init__(
graph=graph, input_list=input_list, name=name
)
def _get_shapes(self, inputs_shape, filters_size):
"""Compute the spatial dimensions of the outputs tensor, and the padding
sizes according to the padding scheme.
Padding sizes are computed according to
https://www.tensorflow.org/versions/r1.3/api_guides/python/nn#Convolution
Args:
inputs_shape (tuple): 4-tuple storing shape of the input tensor in [
batch_size, height, width, in_channels].
filters_size (tuple): filters size in height and width dimension.
Returns:
out_size (tuple): 2-tuple storing height and width of the outputs tensor.
padding (tuple): 4-tuple storing the padding sizes in height dimension (
"pad_top" and "pad_bottom") and width dimension ("pad_left" and
"pad_right").
"""
strides_height, strides_width = self._strides
filters_height, filters_width = filters_size
height, width = inputs_shape[1:3]
if self._padding == "SAME":
out_height = int(np.ceil(float(height) / strides_height))
out_width = int(np.ceil(float(width) / strides_width))
pad_height = (
max(filters_height - strides_height, 0) if height % strides_height
== 0 else max(filters_height - height % strides_height, 0)
)
pad_width = (
max(filters_width - strides_width, 0) if width %
strides_width == 0 else max(filters_width - width % strides_width, 0)
)
padding = (
pad_height // 2, pad_height - pad_height // 2, pad_width // 2,
pad_width - pad_width // 2
)
elif self._padding == "VALID":
out_height = int(
np.ceil(float(height - filters_height + 1) / strides_height)
)
out_width = int(np.ceil(float(width - filters_width + 1) / strides_width))
padding = 0, 0, 0, 0
else:
raise ValueError(f"Invalid padding scheme: {padding}")
out_size = out_height, out_width
return out_size, padding
def _get_img_col_index(self, pad_size, filters_size):
"""Compute the height and width coordinates of the upper left pixel of all
image patches that match the size of the filter. Example:
Given the 4-by-4 image below,
0,0 0,1 0,2 0,3
1,0 1,1 1,2 1,3
2,0 2,1 2,2 2,3
3,0 3,1 3,2 3,3
and a 2-by-2 filter with strides [2, 2], the output is like this:
[(h, w, h_index w_index)] =
[(0, 0, 0, 0),
(0, 2, 0, 1),
(2, 0, 1, 0),
(2, 2, 1, 1)]
Args:
pad_size (tuple): height and width of the padded inputs tensor.
filters_size (tuple): filters size in height and width dimension.
Returns:
img_col_index (ndarray): numpy array of shape [out_height * out_width, 4],
where each row holds a tuple of 4 integers [h, w, h_index, w_index]. `h`
and `w` correspond to the height and width coordinates of the upper left
pixel of each patch that match the size of the filter; `h_index` and
`w_index` correspond to the height and width indices of each path.
"""
pad_height, pad_width = pad_size
strides_height, strides_width = self._strides
filters_height, filters_width = filters_size
h_col_indices = np.arange(
0, pad_height - filters_height + 1, strides_height
)
w_col_indices = np.arange(0, pad_width - filters_width + 1, strides_width)
w_grid, h_grid = np.meshgrid(w_col_indices, h_col_indices)
w_index_grid, h_index_grid = np.meshgrid(
np.arange(w_col_indices.shape[0]), np.arange(h_col_indices.shape[0])
)
img_col_index = np.vstack([
h_grid.ravel(),
w_grid.ravel(),
h_index_grid.ravel(),
w_index_grid.ravel()
]).T
return img_col_index
def _pad(self, inputs, padding):
"""Pad the inputs tensor according to padding sizes.
Args:
inputs (tensor): 4D tensor of shape [batch_size, height, width,
in_channels], the inputs tensor to be padded.
padding (tuple): 4-tuple storing the padding sizes in height dimension (
"pad_top" and "pad_bottom") and width dimension ("pad_left" and
"pad_right").
Returns:
inputs_pad (tensor): 4D tensor of shape [batch_size, pad_height, pad_width
, in_channels], the padded inputs tensor.
"""
pad_value = self._pad_value if hasattr(self, "_pad_value") else 0
inputs_pad = np.pad(
inputs, [[0, 0], padding[:2], padding[2:], [0, 0]],
mode="constant",
constant_values=pad_value
)
return inputs_pad
def _matrixize_inputs_tensor(self, inputs, padding, filters_size):
"""Transform 4D inputs tensor to a 2D matrix layout such that it can be
dot-producted with the matrixized filters tensor.
Args:
inputs (tensor): 4D tensor of shape [batch_size, height, width,
in_channels], the inputs tensor to be padded.
padding (tuple): 4-tuple storing the padding sizes in height dimension (
"pad_top" and "pad_bottom") and width dimension ("pad_left" and
"pad_right").
filters_size (tuple): filters size in height and width dimension.
Returns:
inputs_mat (tensor): 2D tensor of shape [out_height * out_width *
batch_size, in_channels * filters_height * filters_ width], the inputs
tensor in 2D matrix format.
"""
batch_size = inputs.shape[0]
filters_height, filters_width = filters_size
# [out_height * out_width, 4]
img_col_index = self._get_img_col_index((
inputs.shape[1] + padding[0] + padding[1],
inputs.shape[2] + padding[2] + padding[3]
), (filters_height, filters_width))
inputs = self._pad(inputs, padding)
def _func(indices):
"""Slice a patch from the 4D inputs tensor in dim1 (height) and dim2
(width) of the size of the filters tensor.
Returns tensor of shape [batch_size, in_channels * filters_height *
filters_width].
"""
h, w = indices
return inputs[:, h:h + filters_height,
w:w + filters_width, :].transpose(0, 3, 1, 2).reshape(
(batch_size, -1)
)
inputs_mat = np.vstack(np.apply_along_axis(_func, 1, img_col_index[:, :2]))
return inputs_mat
def _flat_channels_dim(self, inputs_mat, out_size, in_channels, filters_size):
"""Reshape the inputs tensor in 2D matrix format by absorbing the
"in_channels" dim from dim-1 into dim-0.
Args:
inputs_mat (tensor): 2D tensor of shape [out_height * out_width *
batch_size, in_channels * filters_height * filters_width], the inputs
tensor in 2D matrix format.
out_size (tuple): height and width of the outputs tensor.
in_channels (int): num of the input channels.
filters_size (tuple): filters size in height and width dimension.
Returns:
inputs_mat (tensor): 2D tensor of shape [out_height * out_width *
batch_size * in_channels, filters_height * filters_ width], the reshaped
inputs tensor in 2D matrix format.
"""
out_height, out_width = out_size
filters_height, filters_width = filters_size
inputs_mat = inputs_mat.reshape(
(out_height, out_width, -1, in_channels, filters_height, filters_width)
).reshape(-1, filters_height * filters_width)
return inputs_mat
def _matrixize_filters_tensor(self, filters):
"""Reshape the 4D filters tensor to 2D matrix format.
Args:
filters (tensor): 4D tensor of shape [filters_height, filters_width,
in_channels, out_channels], the filters tensor.
Returns:
filters_mat (tensor): 2D tensor of shape [in_channels * filters_height *
filters_width, out_channels], the filters tensor in 2D matrix format.
"""
out_channels = filters.shape[3]
filters_mat = filters.transpose(2, 0, 1, 3).reshape(-1, out_channels)
return filters_mat
def _unpad(self, inputs, padding):
"""Strip padding from the padded inputs tensor.
Args:
inputs (tensor): 4D tensor of shape [batch_size, pad_height, pad_width,
in_channels], the padded inputs tensor.
padding (tuple): 4-tuple storing the padding sizes in height dimension (
"pad_top" and "pad_bottom") and width dimension ("pad_left" and
"pad_right").
Returns:
inputs (tensor): 4D tensor of shape [batch_size, height, width,
in_channels], the unpadded inputs tensor.
"""
slice_height = slice(padding[0], -padding[1]
) if padding[1] > 0 else slice(padding[0], None)
slice_width = slice(padding[2], -padding[3]
) if padding[3] > 0 else slice(padding[3], None)
inputs = inputs[:, slice_height, slice_width]
return inputs
def _tensorize_grads_matrix(
self,
inputs_grads_mat,
inputs_shape,
padding,
out_size,
filters_size,
):
"""Transform gradients w.r.t inputs tensor in 2D matrix layout to 4D tensor
format.
Args:
inputs_grads_mat (tensor): 2D tensor of shape [out_height * out_width *
batch_size, in_channels * filters_height * filters_width], gradients
w.r.t. inputs tensor in 2D matrix format.
inputs_shape (tuple): 4-tuple storing shape of the input tensor in [
batch_size, height, width, in_channels].
padding (tuple): 4-tuple storing the padding sizes in height dimension (
"pad_top" and "pad_bottom") and width dimension ("pad_left" and
"pad_right").
out_size (tuple): height and width of the outputs tensor.
filters_size (tuple): filters size in height and width dimension.
Returns:
inputs_grads (tensor): 4D tensor of shape [batch_size, height, width,
in_channels], gradients w.r.t inputs tensor.
"""
filters_height, filters_width = filters_size
out_height, out_width = out_size
in_channels = inputs_shape[3]
pad_height = inputs_shape[1] + padding[0] + padding[1]
pad_width = inputs_shape[2] + padding[2] + padding[3]
# [out_height * out_width, 4]
img_col_index = self._get_img_col_index(
(pad_height, pad_width),
(filters_height, filters_width),
)
# [out_height, out_width, batch_size, filters_height, filters_width,
# in_channels]
inputs_grads_tmp = inputs_grads_mat.reshape(
(out_height, out_width, -1, in_channels, filters_height, filters_width)
).transpose(0, 1, 2, 4, 5, 3)
def _func(indices):
"""Route gradients from `inputs_grads_tmp` to slices in `inputs_grads`."""
h, w, h_index, w_index = indices
inputs_grads = np.zeros(
(inputs_shape[0], pad_height, pad_width, inputs_shape[3]),
dtype="float32"
)
inputs_grads[:, h:h + filters_height,
w:w + filters_width, :] = inputs_grads_tmp[h_index, w_index]
return inputs_grads
# [out_height * out_width, batch_size, pad_height, pad_width, in_channels]
inputs_grads = np.apply_along_axis(_func, 1, img_col_index)
# [batch_size, pad_height, pad_width, in_channels]
# sum the gradients over all `out_height * out_width` slices
inputs_grads = inputs_grads.sum(axis=0)
# [batch_size, height, width, in_channels]
inputs_grads = self._unpad(inputs_grads, padding)
return inputs_grads
def _compute_spatial_size(
self, input_size, kernel_size, stride_size, padding
):
if padding == "SAME":
out_size = int(np.ceil(input_size / stride_size))
else:
out_size = int(np.ceil((input_size - kernel_size + 1) / stride_size))
return out_size
class Conv2D(_Filters2DBase):
"""Regular 2D convolution."""
def _run(self, inputs, filters):
"""Execute the Operation.
Args:
inputs (tensor): 4D tensor of shape [batch_size, height, width,
in_channels], the inputs tensor to be convolved with the filters tensor.
filters (tensor): 4D tensor of shape [filters_height, filters_width,
in_channels, out_channels], the filters tensor.
Returns:
outputs (tensor): 4D tensor of shape [batch_size, out_height, out_width,
out_channels], the result of convolution.
"""
filters_height, filters_width = filters.shape[:2]
(out_height, out_width), padding = self._get_shapes(
inputs.shape, (filters_height, filters_width)
)
batch_size, out_channels = inputs.shape[0], filters.shape[3]
#[out_height*out_width*batch_size, in_channels*filters_height*filters_width]
inputs_mat = self._matrixize_inputs_tensor(
inputs, padding, (filters_height, filters_width)
)
#[in_channels*filters_height*filters_width, out_channels]
filters_mat = self._matrixize_filters_tensor(filters)
#[out_height*out_width*batch_size, out_channels]
outputs = np.dot(inputs_mat, filters_mat
).reshape(out_height, out_width, batch_size,
out_channels).transpose(2, 0, 1, 3)
return outputs
def _grad_func(self, in_grad_tensors):
"""
Args:
in_grad_tensors: list of (Op, tensor_index)
"""
with self._graph.as_default_graph():
op, tensor_index = self._input_list[0].op, self._input_list[0
].tensor_index
bp_inputs = Conv2DBackpropInput(
strides=self._strides,
padding=self._padding,
input_list=[
self._input_list[1], in_grad_tensors[0],
op.get_shape_tensor(tensor_index=tensor_index)
]
)
op, tensor_index = self._input_list[1].op, self._input_list[1
].tensor_index
bp_filters = Conv2DBackpropFilter(
strides=self._strides,
padding=self._padding,
input_list=[
self._input_list[0], in_grad_tensors[0],
op.get_shape_tensor(tensor_index=tensor_index)
]
)
out_grad_tensors = [bp_inputs.output(0), bp_filters.output(0)]
return out_grad_tensors
def _compute_shapes(self):
# validation
inputs_shape = self._input_list[0].shape
filters_shape = self._input_list[1].shape
if inputs_shape.level > 0:
assert inputs_shape.ndims == 4
if filters_shape.level > 0:
assert filters_shape.ndims == 4
if (
inputs_shape.level > 0 and inputs_shape[3] is not None and
filters_shape.level > 0 and filters_shape[2] is not None
):
assert inputs_shape[3] == filters_shape[2]
# compute shapes
batch_size = None
if batch_size is None and inputs_shape.level > 0 and inputs_shape[
0] is not None:
batch_size = inputs_shape[0]
num_channels = None
if filters_shape.level > 0 and filters_shape[3] is not None:
num_channels = filters_shape[3]
height, width = None, None
if (
inputs_shape.level > 0 and filters_shape.level > 0 and
inputs_shape[1] is not None and filters_shape[0] is not None
):
height = self._compute_spatial_size(
inputs_shape[1], filters_shape[0], self._strides[0], self._padding
)
if (
inputs_shape.level > 0 and filters_shape.level > 0 and
inputs_shape[2] is not None and filters_shape[1] is not None
):
width = self._compute_spatial_size(
inputs_shape[2], filters_shape[1], self._strides[1], self._padding
)
return [TensorShape([batch_size, height, width, num_channels])]
class Conv2DBackpropInput(_Filters2DBase):
"""Backprop the gradients from the outputs of `Conv2D` to the input argument
`inputs`.
"""
def _run(self, filters, grads, inputs_shape):
"""Execute the Operation.
Args:
filters (tensor): 4D tensor of shape [filters_height, filters_width,
in_channels, out_channels], the filters tensor.
grads (tensor): 4D tensor of shape [batch_size, out_height, out_width,
out_channels], gradients w.r.t. the outputs tensor.
inputs_shape (tuple): 4-tuple storing shape of the inputs tensor as [
batch_size, height, width, in_channels].
Returns:
inputs_grads (tensor): 4D tensor of shape [batch_size, height, width,
in_channels], gradients w.r.t. the inputs tensor.
"""
filters_height, filters_width = filters.shape[:2]
out_size, padding = self._get_shapes(
inputs_shape, (filters_height, filters_width)
)
out_channels = filters.shape[3]
#[out_height*out_width*batch_size, out_channels]
grads_mat = grads.transpose(1, 2, 0, 3).reshape((-1, out_channels))
#[in_channels*filters_height*filters_width, out_channels]
filters_mat = self._matrixize_filters_tensor(filters)
#[out_height*out_width*batch_size, in_channels*filters_height*filters_width]
inputs_grads_mat = np.dot(grads_mat, filters_mat.T)
inputs_grads = self._tensorize_grads_matrix(
inputs_grads_mat, inputs_shape, padding, out_size,
(filters_height, filters_width)
)
return inputs_grads
def _grad_func(self, in_grad_tensors):
with self._graph.as_default_graph():
op, tensor_index = self._input_list[0].op, self._input_list[0
].tensor_index
bp_filters = Conv2DBackpropFilter(
strides=self._strides,
padding=self._padding,
input_list=[
in_grad_tensors[0], self._input_list[1],
op.get_shape_tensor(tensor_index=tensor_index)
]
)
bp_grads = Conv2D(
strides=self._strides,
padding=self._padding,
input_list=[in_grad_tensors[0], self._input_list[0]]
)
out_grad_tensors = [bp_filters.output(0), bp_grads.output(0)]
return out_grad_tensors
def _get_bp_indices(self):
return [0, 1]
def _compute_shapes(self):
# validation
filters_shape = self._input_list[0].shape
grads_shape = self._input_list[1].shape
inputs_shape = self._input_list[2]
if filters_shape.level > 0:
assert filters_shape.ndims == 4
if grads_shape.level > 0:
assert grads_shape.ndims == 4
if inputs_shape.shape.level > 0:
inputs_shape.shape.ndims == 1
if (
filters_shape.level > 0 and grads_shape.level > 0 and
filters_shape[3] is not None and grads_shape[3] is not None
):
assert filters_shape[3] == grads_shape[3]
if hasattr(inputs_shape.op, "_value"):
if filters_shape.level > 0 and filters_shape[2] is not None:
assert filters_shape[2] == inputs_shape.op._value[3]
if grads_shape.level > 0 and grads_shape[0] is not None:
assert grads_shape[0] == inputs_shape.op._value[0]
# compute shapes
batch_size, height, width, in_channels = None, None, None, None
if hasattr(inputs_shape.op, "_value"):
batch_size, height, width, in_channels = inputs_shape.op._value
if grads_shape.level > 0 and grads_shape[
0] is not None and batch_size is None:
batch_size = grads_shape[0]
if filters_shape.level > 0 and filters_shape[
2] is not None and in_channels is None:
in_channels = filters_shape[2]
return [TensorShape([batch_size, height, width, in_channels])]
class Conv2DBackpropFilter(_Filters2DBase):
"""Backprop the gradients from the outputs of `Conv2D` to the input argument
`filters`.
"""
def _run(self, inputs, grads, filters_shape):
"""Execute the Operation.
Args:
inputs (tensor): 4D tensor of shape [batch_size, height, width,
in_channels], the inputs tensor to be convolved with the filters tensor.
grads (tensor): 4D tensor of shape [batch_size, out_height, out_width,
out_channels], gradients w.r.t. the outputs tensor.
filters_shape (tuple): 4-tuple storing shape of the filters tensor as [
filters_height, filters_width, in_channels, out_channels].
Returns:
filters_grads (tensor): 4D tensor of shape [filters_height, filters_width,
in_channels, out_channels], gradients w.r.t the filters tensor.
"""
filters_height, filters_width, in_channels, out_channels = filters_shape
padding = self._get_shapes(inputs.shape, (filters_height, filters_width))[1]
#[out_height*out_width*batch_size, out_channels]
grads_mat = grads.transpose(1, 2, 0, 3).reshape((-1, out_channels))
#[out_height*out_width*batch_size, in_channels*filters_height*filters_width]
inputs_mat = self._matrixize_inputs_tensor(
inputs, padding, (filters_height, filters_width)
)
#[in_channels*filters_height*filters_width, out_channels]
filters_grads_mat = np.dot(inputs_mat.T, grads_mat)
filters_grads = filters_grads_mat.reshape(
(in_channels, filters_height, filters_width, out_channels)
).transpose(1, 2, 0, 3)
return filters_grads
def _grad_func(self, in_grad_tensors):
with self._graph.as_default_graph():
op, tensor_index = self._input_list[0].op, self._input_list[0
].tensor_index
bp_inputs = Conv2DBackpropInput(
strides=self._strides,
padding=self._padding,
input_list=[
in_grad_tensors[0], self._input_list[1],
op.get_shape_tensor(tensor_index=tensor_index)
]
)
bp_grads = Conv2D(
strides=self._strides,
padding=self._padding,
input_list=[self._input_list[0], in_grad_tensors[0]]
)
out_grad_tensors = [bp_inputs.output(0), bp_grads.output(0)]
return out_grad_tensors
def _get_bp_indices(self):
return [0, 1]
def _compute_shapes(self):
# validation
inputs_shape = self._input_list[0].shape
grads_shape = self._input_list[1].shape
filters_shape = self._input_list[2]
if inputs_shape.level > 0:
assert inputs_shape.ndims == 4
if grads_shape.level > 0:
assert grads_shape.ndims == 4
if filters_shape.shape.level > 0:
filters_shape.shape.ndims == 1
if (
inputs_shape.level > 0 and grads_shape.level > 0 and
inputs_shape[0] is not None and grads_shape[0] is not None
):
assert inputs_shape[0] == grads_shape[0]
if hasattr(filters_shape.op, "_value"):
if inputs_shape.level > 0 and inputs_shape[3] is not None:
assert inputs_shape[3] == filters_shape.op._value[2]
if grads_shape.level > 0 and grads_shape[3] is not None:
assert grads_shape[3] == filters_shape.op._value[3]
# compute shapes
filters_height, filters_width, in_channels, out_channels = None, None, None, None
if hasattr(filters_shape.op, "_value"):
filters_height, filters_width, in_channels, out_channels = filters_shape.op._value
if inputs_shape.level > 0 and inputs_shape[
3] is not None and in_channels is None:
in_channels = inputs_shape[3]
if grads_shape.level > 0 and grads_shape[
3] is not None and out_channels is None:
out_channels = grads_shape[3]
filters_height, filters_width, in_channels, out_channels = None, None, None, None
return [
TensorShape([filters_height, filters_width, in_channels, out_channels])
]
class _Pooling2DBase(_Filters2DBase):
"""Base class for 2D pooling Operations (MaxPool2D, AvgPool2D, etc.)."""
def __init__(
self, strides, filters_size, padding, input_list, graph=None, name=None
):
"""Constructor.
Set `np.nan` as flag of padded value when computing maximum or average.
Args:
strides (tuple): strides in height and width dimension.
filters_size (tuple): filters size in height and width dimension.
padding (string): padding scheme (either "SAME" or "VALID").
"""
self._filters_size = filters_size
super(_Pooling2DBase, self).__init__(
strides=strides,
padding=padding,
graph=graph,
input_list=input_list,
name=name
)
self._pad_value = np.nan
def _compute_shapes(self):
# validation
inputs_shape = self._input_list[0].shape
if inputs_shape.level > 0:
assert inputs_shape.ndims == 4
# compute shapes
batch_size, height, width, num_channels = None, None, None, None
if inputs_shape.level > 0:
if inputs_shape[0] is not None:
batch_size = inputs_shape[0]
if inputs_shape[3] is not None:
num_channels = inputs_shape[3]
if inputs_shape[1] is not None:
height = self._compute_spatial_size(
inputs_shape[1], self._filters_size[0], self._strides[0],
self._padding
)
if inputs_shape[2] is not None:
width = self._compute_spatial_size(
inputs_shape[2], self._filters_size[1], self._strides[1],
self._padding
)
return [TensorShape([batch_size, height, width, num_channels])]
class MaxPool2D(_Pooling2DBase):
"""Regular 2D max pooling."""
def _run(self, inputs):
"""Execute the Operation.
Args:
inputs (tensor): 4D tensor of shape [batch_size, height, width,
in_channels], the inputs tensor to be max-pooled.
Returns:
outputs (tensor): 4D tensor of shape [batch_size, out_height, out_width,
in_channels], the outputs tensor.
"""
out_size, padding = self._get_shapes(inputs.shape, self._filters_size)
batch_size, in_channels = inputs.shape[0], inputs.shape[3]
#[out_height*out_width*batch_size, in_channels*filters_height*filters_width]
inputs_mat = self._matrixize_inputs_tensor(
inputs, padding, self._filters_size
)
#[out_height*out_width*batch_size*in_channels, filters_height*filters_width]
inputs_mat = self._flat_channels_dim(
inputs_mat, out_size, in_channels, self._filters_size
)
#[out_height*out_width*batch_size*in_channels]
outputs = np.nanmax(inputs_mat, axis=1)
outputs = outputs.reshape(
(out_size[0], out_size[1], batch_size, in_channels)
).transpose(2, 0, 1, 3)
return outputs
def _grad_func(self, in_grad_tensors):
with self._graph.as_default_graph():
maxpool2d_grads = MaxPool2DGrad(
strides=self._strides,
filters_size=self._filters_size,
padding=self._padding,
input_list=[self._input_list[0], in_grad_tensors[0]]
)
out_grad_tensors = [maxpool2d_grads.output(0)]
return out_grad_tensors
class MaxPool2DGrad(_Pooling2DBase):
"""Backprop the gradients from the outputs of `MaxPool2D` to the input
argument `inputs`.
"""
def _run(self, inputs, grads):
"""Execute the Operation.
Args:
inputs (tensor): 4D tensor of shape [batch_size, height, width,
in_channels], the inputs tensor to be max-pooled.
grads (tensor): 4D tensor of shape [batch_size, out_height, out_width,
in_channels], gradients w.r.t. the outputs tensor.
Returns:
inputs_grads (tensor): 4D tensor of shape [batch_size, height, width,
in_channels], gradients w.r.t. the inputs tensor.
"""
out_size, padding = self._get_shapes(inputs.shape, self._filters_size)
batch_size, in_channels = inputs.shape[0], inputs.shape[3]
#[out_height*out_width*batch_size, in_channels*filters_height*filters_width]
inputs_mat = self._matrixize_inputs_tensor(
inputs, padding, self._filters_size
)
#[out_height*out_width*batch_size*in_channels, filters_height*filters_width]
inputs_mat = self._flat_channels_dim(
inputs_mat, out_size, in_channels, self._filters_size
)
#[out_height*out_width*batch_size*in_channels]
argmax = np.nanargmax(inputs_mat, axis=1)
#[out_height*out_width*batch_size*in_channels, filters_height*filters_width]
ind_mat = np.zeros_like(inputs_mat, dtype="float32")
ind_mat[np.arange(ind_mat.shape[0]), argmax] = 1
#[out_height*out_width*batch_size*in_channels, filters_height*filters_width]
grads_mat = np.tile(
grads.transpose(1, 2, 0, 3).reshape((-1, 1)), (1, ind_mat.shape[1])
)
#[out_height*out_width*batch_size*in_channels, filters_height*filters_width]
inputs_grads_mat = ind_mat * grads_mat
inputs_grads_mat = inputs_grads_mat.reshape((
out_size[0] * out_size[1] * batch_size,
in_channels * self._filters_size[0] * self._filters_size[1]
))
# [batch_size, height, width, in_channels]
inputs_grads = self._tensorize_grads_matrix(
inputs_grads_mat, inputs.shape, padding, out_size, self._filters_size
)
return inputs_grads
def _grad_func(self, in_grad_tensors):
with self._graph.as_default_graph():
op, tensor_index = self._input_list[1].op, self._input_list[1
].tensor_index
bp_inputs = MaxPool2DGrad(
strides=self._strides,
filters_size=self._filters_size,
padding=self._padding,
input_list=[
self._input_list[0],
op.get_zeros_tensor(tensor_index=tensor_index),
]
)
bp_grads = MaxPool2DGradGrad(
strides=self._strides,
filters_size=self._filters_size,
padding=self._padding,
input_list=[self._input_list[0], in_grad_tensors[0]]
)
out_grad_tensors = [bp_inputs.output(0), bp_grads.output(0)]
return out_grad_tensors
def _compute_shapes(self):
# validation
inputs_shape = self._input_list[0].shape
grads_shape = self._input_list[1].shape
if inputs_shape.level > 0:
assert inputs_shape.ndims == 4
if grads_shape.level > 0:
assert grads_shape.ndims == 4
if (
inputs_shape.level > 0 and grads_shape.level > 0 and
inputs_shape[0] is not None and grads_shape[0] is not None and
inputs_shape[3] is not None and grads_shape[3] is not None
):
assert inputs_shape[0] == grads_shape[0]
assert inputs_shape[3] == grads_shape[3]
# compute shapes
batch_size, height, width, num_channels = None, None, None, None
if inputs_shape.level > 0:
if inputs_shape[0] is not None:
batch_size = inputs_shape[0]
if inputs_shape[1] is not None:
height = inputs_shape[1]
if inputs_shape[2] is not None:
width = inputs_shape[2]
if inputs_shape[3] is not None:
num_channels = inputs_shape[3]
if grads_shape.level > 0:
if batch_size is None and grads_shape[0] is not None:
batch_size = grads_shape[0]
if num_channels is None and grads_shape[3] is not None:
num_channels = grads_shape[3]
return [TensorShape([batch_size, height, width, num_channels])]
class MaxPool2DGradGrad(_Pooling2DBase):
"""Backprop the gradients from the outputs of `MaxPool2DGrad` to the input
argument `grads`.
"""
def _run(self, inputs, inputs_grads_grads):
"""Execute the Operation.
Args:
inputs (tensor): 4D tensor of shape [batch_size, height, width,
in_channels], the inputs tensor to be max-pooled.
inputs_grads_grads (tensor): 4D tensor of shape [batch_size, height, width
, in_channels], gradients w.r.t. the outputs of `MaxPool2DGrad`.
Returns:
grads_grads (tensor): 4D tensor of shape [batch_size, out_height,
out_width, in_channels], gradients w.r.t. the input argument `grads`
of `MaxPool2DGrad`.
"""
out_size, padding = self._get_shapes(
inputs_grads_grads.shape, self._filters_size
)
batch_size, in_channels = (
inputs_grads_grads.shape[0], inputs_grads_grads.shape[3]
)
#[out_height*out_width*batch_size, in_channels*filters_height*filters_width]
inputs_grads_grads_mat = self._matrixize_inputs_tensor(
inputs_grads_grads, padding, self._filters_size
)
#[out_height*out_width*batch_size*in_channels, filters_height*filters_width]
inputs_grads_grads_mat = self._flat_channels_dim(
inputs_grads_grads_mat, out_size, in_channels, self._filters_size
)
#[out_height*out_width*batch_size, in_channels*filters_height*filters_width]
inputs_mat = self._matrixize_inputs_tensor(
inputs, padding, self._filters_size
)
#[out_height*out_width*batch_size*in_channels, filters_height*filters_width]
inputs_mat = self._flat_channels_dim(
inputs_mat, out_size, in_channels, self._filters_size
)
#[out_height*out_width*batch_size*in_channels]
argmax = np.nanargmax(inputs_mat, axis=1)
#[out_height*out_width*batch_size*in_channels]
grads_grads_mat = inputs_grads_grads_mat[
np.arange(inputs_grads_grads_mat.shape[0]), argmax]
grads_grads = grads_grads_mat.reshape(
out_size[0], out_size[1], batch_size, in_channels
).transpose(2, 0, 1, 3)
return grads_grads
def _grad_func(self, in_grad_tensors):
with self._graph.as_default_graph():
op, tensor_index = in_grad_tensors[0].op, in_grad_tensors[0].tensor_index
bp_inputs = MaxPool2DGrad(
strides=self._strides,
filters_size=self._filters_size,
padding=self._padding,
input_list=[
self._input_list[0],
op.get_zeros_tensor(tensor_index=tensor_index),
]
)
bp_inputs_grads_grads = MaxPool2DGrad(
strides=self._strides,
filters_size=self._filters_size,
padding=self._padding,
input_list=[self._input_list[0], in_grad_tensors[0]]
)
out_grad_tensors = [bp_inputs.output(0), bp_inputs_grads_grads.output(0)]
return out_grad_tensors
def _compute_shapes(self):
# validation
inputs_shape = self._input_list[0].shape
inputs_grads_grads_shape = self._input_list[1].shape
if inputs_shape.level > 0:
assert inputs_shape.ndims == 4
assert inputs_shape._compatible_with(inputs_grads_grads_shape)
# compute shapes
batch_size, height, width, num_channels = None, None, None, None
for shape in (inputs_shape, inputs_grads_grads_shape):
if shape.level > 0:
if batch_size is None and shape[0] is not None:
batch_size = shape[0]
if num_channels is None and shape[3] is not None:
num_channels = shape[3]
if height is None and shape[1] is not None:
height = self._compute_spatial_size(
shape[1], self._filters_size[0], self._strides[0], self._padding
)
if width is None and shape[2] is not None:
width = self._compute_spatial_size(
shape[2], self._filters_size[1], self._strides[1], self._padding
)
return [TensorShape([batch_size, height, width, num_channels])]
class AvgPool2D(_Pooling2DBase):
"""Regular 2D average pooling."""
def _run(self, inputs):
"""Execute the Operation.
Args:
inputs (tensor): 4D tensor of shape [batch_size, height, width,
in_channels], the inputs tensor to be average-pooled.
Returns:
outputs (tensor): 4D tensor of shape [batch_size, out_height, out_width,
in_channels], the outputs tensor.
"""
out_size, padding = self._get_shapes(inputs.shape, self._filters_size)
batch_size, in_channels = inputs.shape[0], inputs.shape[3]
#[out_height*out_width*batch_size, in_channels*filters_height*filters_width]
inputs_mat = self._matrixize_inputs_tensor(
inputs, padding, self._filters_size
)
#[out_height*out_width*batch_size*in_channels, filters_height*filters_width]
inputs_mat = self._flat_channels_dim(
inputs_mat, out_size, in_channels, self._filters_size
)
#[out_height*out_width*batch_size*in_channels]
outputs = np.nanmean(inputs_mat, axis=1)