This repository has been archived by the owner on Jan 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 810
/
container.py
1747 lines (1445 loc) · 63.7 KB
/
container.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
# ******************************************************************************
# Copyright 2017-2018 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ******************************************************************************
from __future__ import division
from builtins import str, zip, range
import numpy as np
import itertools as itt
from operator import add
import inspect
from neon import NervanaObject
from neon.layers.layer import Layer, BranchNode, Dropout, DataTransform, LookupTable, Affine
from neon.layers.recurrent import Recurrent, get_steps
from neon.transforms import Softmax
from neon.util.persist import load_class
from functools import reduce
# modified from https://docs.python.org/3/library/itertools.html
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..., (sN, None)"
a, b = itt.tee(iterable + [None])
next(b, None)
return zip(a, b)
def flatten(item):
if hasattr(item, '__iter__'):
for i in iter(item):
for j in flatten(i):
yield j
else:
yield item
class DeltasTree(NervanaObject):
"""
Data structure for maintaining nested global delta buffers
"""
def __init__(self, parent=None):
self.parent = None
self.child = None
self.buffers = [None]*2
self.max_shape = 0
if parent:
assert type(parent) is DeltasTree
self.parent = parent
def decend(self):
if self.child is None:
self.child = DeltasTree()
return self.child
def ascend(self):
return self.parent
def proc_layer(self, layer):
in_size = layer.be.shared_iobuf_size(layer.in_shape,
layer.parallelism)
if in_size > self.max_shape:
self.max_shape = in_size
def allocate_buffers(self):
if self.child:
self.child.allocate_buffers()
for ind in range(len(self.buffers)):
if self.buffers[ind] is None:
if self.max_shape > 0:
self.buffers[ind] = self.be.iobuf(self.max_shape,
persist_values=False,
parallelism="Data")
class LayerContainer(Layer):
"""
Layer containers are a generic class that are used to encapsulate groups of layers and
provide methods for propagating through the constituent layers, allocating memory.
"""
def __init__(self, name=None):
super(LayerContainer, self).__init__(name)
self.is_mklop = True
@property
def layers_to_optimize(self):
lto = []
for l in self.layers:
if isinstance(l, LayerContainer):
lto += l.layers_to_optimize
elif l.has_params:
if hasattr(l, 'init') and l.init.name == "Identity":
continue
lto.append(l)
return lto
@property
def nest_deltas(self):
return False
def nested_str(self, level=0):
"""
Utility function for displaying layer info with a given indentation level.
Arguments:
level (int, optional): indentation level
Returns:
str: layer info at the given indentation level
"""
padstr = '\n' + ' ' * level
ss = ' ' * level + self.classnm + padstr
ss += padstr.join([l.nested_str(level + 1) for l in self.layers])
return ss
@classmethod
def gen_class(cls, pdict):
layers = []
for layer in pdict['layers']:
typ = layer['type']
ccls = load_class(typ)
layers.append(ccls.gen_class(layer['config']))
# the 'layers' key is special in that the layer
# parameters are in there and need to be saved the
# whole pdict['layers'] element can not be replaced
# with the just the layer objects like elsewhere
lsave = pdict.pop('layers')
new_cls = cls(layers=layers, **pdict)
pdict['layers'] = lsave
return new_cls
def get_description(self, get_weights=False, keep_states=False):
"""
Get layer parameters. All parameters are needed for optimization, but
only weights are serialized.
Arguments:
get_weights (bool, optional): Control whether all parameters are returned or
just weights for serialization.
keep_states (bool, optional): Control whether all parameters are returned
or just weights for serialization.
"""
desc = super(LayerContainer, self).get_description(skip=['layers'])
desc['container'] = True
desc['config']['layers'] = []
for layer in self.layers:
desc['config']['layers'].append(layer.get_description(get_weights=get_weights,
keep_states=keep_states))
self._desc = desc
return desc
def fusion_pass(self, layers):
"""
Groups patterns together in list. If pattern is [a, b], will transform
[a, b, c, d, a, b, e] -> [[a, b], c, d, [a, b], e]. Support for multiple
patterns.
"""
patterns = [lambda x, y: x['type'] == 'neon.layers.layer.Convolution' and
y['type'] == 'neon.layers.layer.Bias']
result = []
skip_next = False
for (l1, l2) in pairwise(layers):
if any([pattern(l1, l2) for pattern in patterns]):
result.append([l1, l2])
skip_next = True
elif skip_next:
skip_next = False
else:
result.append(l1)
return result
def load_weights(self, pdict, load_states=True):
"""
Load weights.
Arguments:
pdict:
load_states: (Default value = True)
Returns:
"""
pdict['config']['layers'] = self.fusion_pass(pdict['config']['layers'])
assert len(pdict['config']['layers']) == len(self.layers)
for branch, bdict in zip(self.layers, pdict['config']['layers']):
branch.load_weights(bdict, load_states=load_states)
def revert_tensors(self):
for tensor in itt.chain.from_iterable([l.revert_list for l in self.layers]):
self.be.revert_tensor(tensor)
def propagate_parallelism(self, p):
for l in self.layers:
if isinstance(l, LayerContainer):
l.parallelism = p
l.propagate_parallelism(p)
t = l.get_terminal()
p = t[0].parallelism if isinstance(t, list) else t.parallelism
else:
l.parallelism = p if l.parallelism == "Unknown" else l.parallelism
p = l.parallelism
def set_batch_size(self, N):
"""
Set minibatch size.
Arguments:
N (int): minibatch size
"""
for l in self.layers:
l.set_batch_size(N)
def set_seq_len(self, S):
"""
Set sequence length.
Arguments:
S (int): sequence length
"""
for l in self.layers:
l.set_seq_len(S)
def set_deltas(self, global_deltas):
"""
Set the layer deltas from the shared
global deltas pool
"""
for l in self.layers:
l.set_deltas(global_deltas)
def layers_fprop(self):
"""
Generator to iterator over the layers in the same
order as fprop
"""
for layer in self.layers:
yield layer
if hasattr(layer, 'layers_fprop'):
for layer2 in layer.layers_fprop():
yield layer2
def layers_bprop(self):
"""
Generator to iterator over the layers in the same
order as bprop
"""
for layer in reversed(self.layers):
if hasattr(layer, 'layers_bprop'):
for layer2 in layer.layers_bprop():
yield layer2
yield layer
def set_acc_on(self, acc_on):
"""
Set the acc_on flag according to bool argument for each layer.
If a layer in the container does not support accumulate_updates
it will be skipped.
Arguments:
acc_on (bool): Value to set the acc_on flag of supported layers to.
"""
if (not hasattr(self, "accumulate_updates")):
raise BufferError("accumulate_updates not set")
for l in self.layers:
if hasattr(l, "accumulate_updates"):
l.set_acc_on(acc_on)
class Sequential(LayerContainer):
"""
Layer container that encapsulates a simple linear pathway of layers.
Arguments:
layers (list): List of objects which can be either a list of layers
(including layer containers).
"""
def __init__(self, layers, name=None):
super(Sequential, self).__init__(name)
assert layers, "Provide layers"
self.layers = [l for l in flatten(layers)]
self._layers = [x for x in self.layers if type(x) not in (BranchNode,)]
root = self._layers[0]
assert (root.owns_output or
type(root) in [Dropout, DataTransform]), "Sequential root must own outputs"
def configure(self, in_obj):
"""
Must receive a list of shapes for configuration (one for each pathway)
the shapes correspond to the layer_container attribute
Arguments:
in_obj: any object that has an out_shape (Layer) or shape (Tensor, dataset)
"""
if in_obj:
config_layers = self.layers
in_obj = in_obj
else:
in_obj = self.layers[0]
# Remove the initial branch nodes from the layers
for l_idx, l in enumerate(self.layers):
if type(l) in (BranchNode,):
continue
else:
config_layers = self.layers[l_idx:]
break
super(Sequential, self).configure(in_obj)
prev_layer = None
for l in config_layers:
in_obj = l.configure(in_obj)
if prev_layer is not None:
prev_layer.set_next(l)
prev_layer = l
self.parallelism = in_obj.parallelism
self.out_shape = in_obj.out_shape
return self
def allocate(self, shared_outputs=None, accumulate_updates=False):
"""
Allocate output buffer to store activations from fprop.
Arguments:
shared_outputs (Tensor, optional): pre-allocated tensor for activations to be
computed into
"""
# get the layers that own their outputs
self.accumulate_updates = accumulate_updates
alloc_layers = [l for l in self.layers if l.owns_output]
if 'accumulate_updates' in inspect.getargspec(alloc_layers[-1].allocate).args:
alloc_layers[-1].allocate(shared_outputs, accumulate_updates=accumulate_updates)
else:
alloc_layers[-1].allocate(shared_outputs)
for l in self.layers:
if 'accumulate_updates' in inspect.getargspec(l.allocate).args:
l.allocate(accumulate_updates=accumulate_updates)
else:
l.allocate()
def allocate_deltas(self, global_deltas=None):
if global_deltas is None:
self.global_deltas = DeltasTree()
st_ind = 0 if getattr(self.layers[0], 'nest_deltas', False) else 1
for layer in self.layers[st_ind:]:
layer.allocate_deltas(self.global_deltas)
self.global_deltas.allocate_buffers()
else:
self.global_deltas = global_deltas
self.set_deltas(self.global_deltas)
def fprop(self, inputs, inference=False, beta=0.0):
"""
TODO: Handle final layers that don't own their own outputs (bias, activation)
Arguments:
inputs:
inference: (Default value = False)
beta: (Default value = 0.0)
Returns:
"""
x = inputs
for l in self.layers:
altered_tensor = l.be.distribute_data(x, l.parallelism)
l.revert_list = [altered_tensor] if altered_tensor else []
# try to convert to mkl
l.be.convert_data(x, l.get_is_mklop())
if l is self.layers[-1] and beta != 0:
x = l.fprop(x, inference=inference, beta=beta)
else:
x = l.fprop(x, inference=inference)
if inference:
self.revert_tensors()
return x
def bprop(self, error, alpha=1.0, beta=0.0):
"""
Apply the backward pass transformation to the input data.
Arguments:
error (Tensor): deltas back propagated from the adjacent higher layer
alpha (float, optional): scale to apply to input for activation
gradient bprop. Defaults to 1.0
beta (float, optional): scale to apply to output activation
gradient bprop. Defaults to 0.0
Returns:
Tensor: deltas to propagate to the adjacent lower layer
"""
for l in reversed(self._layers):
altered_tensor = l.be.distribute_data(error, l.parallelism)
# try to convert to mkl
l.be.convert_data(error, l.get_is_mklop())
if altered_tensor:
l.revert_list.append(altered_tensor)
if type(l.prev_layer) is BranchNode or l is self._layers[0]:
error = l.bprop(error, alpha, beta)
else:
error = l.bprop(error)
# for not-mkl op, deltas is cpu tensor, but it is shared thus may have
# meanless mkl tensor info, thus clean it for further operation (beta add)
l.be.clean_data(l.deltas, not l.get_is_mklop())
for tensor in l.revert_list:
self.be.revert_tensor(tensor)
return self._layers[0].deltas
def get_terminal(self):
"""
Used for recursively getting final nodes from layer containers.
"""
terminal = self.layers[-1].get_terminal()
return terminal
class GenerativeAdversarial(Sequential):
"""
Container for Generative Adversarial Net (GAN). It contains the Generator
and Discriminator stacks as sequential containers.
Arguments:
layers (list): A list containing two Sequential containers
"""
def __init__(self, generator, discriminator, name=None):
super(Sequential, self).__init__(name)
self.generator = generator
self.discriminator = discriminator
self.layers = self.generator.layers + self.discriminator.layers
def nested_str(self, level=0):
"""
Utility function for displaying layer info with a given indentation level.
Arguments:
level (int, optional): indentation level
Returns:
str: layer info at the given indentation level
"""
padstr = '\n' + ' ' * level
ss = ' ' * level + self.classnm + padstr
ss += ' ' * level + 'Generator:\n'
ss += padstr.join([l.nested_str(level + 1) for l in self.generator.layers])
ss += '\n' + ' ' * level + 'Discriminator:\n'
ss += padstr.join([l.nested_str(level + 1) for l in self.discriminator.layers])
return ss
class Tree(LayerContainer):
"""
Layer container that encapsulates a simple linear pathway of layers.
Arguments:
layers (list): List of Sequential containers corresponding to the branches of the Tree.
The branches must be provided with main trunk first, and then the auxiliary
branches in the order the branch nodes are encountered
name (string, optional): Name for the container
alphas (list(float), optional): list of weighting factors to apply to each branch for
backpropagating error.
"""
def __init__(self, layers, name=None, alphas=None):
super(Tree, self).__init__(name=name)
self.layers = []
for l in layers:
if isinstance(l, Sequential):
self.layers.append(l)
elif isinstance(l, list):
self.layers.append(Sequential(l))
elif isinstance(l, Layer):
self.layers.append(Sequential([l]))
else:
ValueError("Incompatible element for Tree container")
self.alphas = [1.0 for _ in self.layers] if alphas is None else alphas
# alphas and betas are used for back propagation
# We want to ensure that the branches are ordered according to the origin of their roots
# then the betas will be 0 for the last appearance of the root, and 1 for the rest,
# but the trunk will always be 1 (since it contains all of the branch nodes)
self.betas = []
next_root = None
for l in reversed(self.layers):
root = l.layers[0]
beta = 1.0 if (root is next_root or type(root) is not BranchNode) else 0.0
next_root = root
self.betas.append(beta)
self.betas.reverse()
def nested_str(self, level=0):
"""
Utility function for displaying layer info with a given indentation level.
Arguments:
level (int, optional): indentation level
Returns:
str: layer info at the given indentation level
"""
ss = self.classnm + '\n'
ss += '\n'.join([l.nested_str(level + 1) for l in self.layers])
return ss
def configure(self, in_obj):
"""
Set shape based parameters of this layer given an input tuple, int
or input layer.
Arguments:
in_obj (int, tuple, Layer, Tensor or dataset): object that provides shape
information for layer
Returns:
(tuple): shape of output data
"""
super(Tree, self).configure(in_obj)
self.layers[0].configure(in_obj)
for l in self.layers[1:]:
l.configure(None)
self.out_shape = [l.out_shape for l in self.layers]
return self
def allocate(self, shared_outputs=None):
"""
Allocate output buffer to store activations from fprop.
Arguments:
shared_outputs (Tensor, optional): pre-allocated tensor for activations to be
computed into
"""
for l in self.layers:
l.allocate()
self.outputs = [l.outputs for l in self.layers]
def allocate_deltas(self, global_deltas=None):
for l in reversed(self.layers):
l.allocate_deltas(global_deltas)
def fprop(self, inputs, inference=False):
"""
Apply the forward pass transformation to the input data.
Arguments:
inputs (Tensor): input data
Returns:
Tensor: output data
"""
x = self.layers[0].fprop(inputs, inference)
out = [x] + [l.fprop(None, inference=inference) for l in self.layers[1:]]
return out
def bprop(self, error, alpha=1.0, beta=0.0):
"""
Apply the backward pass transformation to the input data.
Arguments:
error (Tensor): deltas back propagated from the adjacent higher layer
Returns:
Tensor: deltas to propagate to the adjacent lower layer
"""
for l, e, a, b in reversed(list(zip(self.layers, error, self.alphas, self.betas))):
l.bprop(e, alpha=a, beta=b)
def get_terminal(self):
"""
Used for recursively getting final nodes from layer containers.
"""
return [l.get_terminal() for l in self.layers]
class SingleOutputTree(Tree):
"""
Subclass of the Tree container which returns only
the output of the main branch (branch index 0) during
inference.
"""
def fprop(self, inputs, inference=False):
"""
Apply the forward pass transformation to the input data.
Arguments:
inputs (Tensor): input data
Returns:
Tensor: output data
"""
x = self.layers[0].fprop(inputs, inference)
if inference:
return x
else:
out = [x] + [l.fprop(None) for l in self.layers[1:]]
return out
class Broadcast(LayerContainer):
"""
Parent class for MergeSum and MergeBroadcast.
"""
def __init__(self, layers, name=None):
super(Broadcast, self).__init__(name)
# Input list of layers converts:
# lists to Sequential container
# singleton layers to Sequential containers of 1
# leaves Sequentials alone
self.layers = []
for l in layers:
if isinstance(l, Sequential):
self.layers.append(l)
elif isinstance(l, list):
self.layers.append(Sequential(l))
elif isinstance(l, Layer):
self.layers.append(Sequential([l]))
else:
ValueError("Incompatible element for " + self.__class__.__name__ + " Layer")
self.owns_output = True
self.outputs = None
@property
def nest_deltas(self):
return True
def __str__(self):
ss = '\n\t'.join([str(l) for l in self.layers])
ss = '\t' + self.classnm + '\n\t' + ss
return ss
def configure(self, in_obj):
"""
Sets shape based parameters of this layer given an input tuple or int
or input layer
Arguments:
in_obj (int, tuple, Layer or Tensor or dataset): object that provides shape
information for layer
Returns:
(tuple): shape of output data
"""
super(Broadcast, self).configure(in_obj)
# Receiving from single source -- distribute to branches
for l in self.layers:
l.configure(in_obj)
self._configure_merge()
return self
def allocate_deltas(self, global_deltas):
nested_deltas = global_deltas.decend()
for layer in self.layers:
layer.layers[0].allocate_deltas(global_deltas)
for sublayer in layer.layers[1:]:
sublayer.allocate_deltas(nested_deltas)
def set_deltas(self, delta_buffers):
"""
Use pre-allocated (by layer containers) list of buffers for backpropagated error.
Only set deltas for layers that own their own deltas
Only allocate space if layer owns its own deltas (e.g., bias and activation work in-place,
so do not own their deltas).
Arguments:
delta_buffers (DeltasTree): list of pre-allocated tensors (provided by layer container)
"""
bottom_buffer = delta_buffers.buffers[0]
nested_deltas = delta_buffers.decend()
assert nested_deltas is not None
for l in self.layers:
l.layers[0].set_deltas(delta_buffers)
# mkl need allocate new deltas
l.layers[0].deltas = self.be.allocate_new_deltas(
l.layers[0].deltas, l.layers[0].in_shape, l.layers[0].parallelism)
delta_buffers.buffers.reverse() # undo that last reverse
for sublayer in l.layers[1:]:
sublayer.set_deltas(nested_deltas)
# Special case if originating from a branch node
if type(self.prev_layer) is BranchNode:
self.deltas = self.be.iobuf(self.in_shape, shared=self.prev_layer.deltas,
parallelism=self.parallelism)
else:
self.deltas = self.be.iobuf(self.in_shape, shared=bottom_buffer,
parallelism=self.parallelism)
delta_buffers.buffers.reverse()
def get_terminal(self):
"""
Used for recursively getting final nodes from layer containers.
"""
terminals = [l.get_terminal() for l in self.layers]
return terminals
class MergeSum(Broadcast):
"""
"""
def __init__(self, layers, name=None):
super(MergeSum, self).__init__(layers, name)
self.ngLayer = self.be.mergesum_layer(len(layers))
def allocate(self, shared_outputs=None):
"""
Allocate output buffer to store activations from fprop.
Arguments:
shared_outputs (Tensor, optional): pre-allocated tensor for activations to be
computed into
"""
if self.outputs is None:
self.outputs = self.be.iobuf(self.out_shape, shared=shared_outputs,
parallelism=self.parallelism)
for l in self.layers:
self.be.allocate_new_outputs(l, self.outputs)
def _configure_merge(self):
"""
Helper function for configuring output shape
"""
out_shapes = [l.out_shape for l in self.layers]
self.out_shape = out_shapes[0]
def fprop(self, inputs, inference=False):
"""
Apply the forward pass transformation to the input data.
Arguments:
inputs (Tensor): input data
Returns:
Tensor: output data
"""
self.be.fprop_mergesum(self.ngLayer, inputs, inference,
self.layers, self.outputs, self.out_shape)
return self.outputs
def bprop(self, error, alpha=1.0, beta=0.0):
"""
Apply the backward pass transformation to the input data.
Arguments:
error (Tensor): deltas back propagated from the adjacent higher layer
alpha (float, optional): scale to apply to input for activation
gradient bprop. Defaults to 1.0
beta (float, optional): scale to apply to output activation
gradient bprop. Defaults to 0.0
Returns:
Tensor: deltas to propagate to the adjacent lower layer
"""
self.be.bprop_mergesum(self.ngLayer, alpha, beta,
self.layers, error, self.deltas)
return self.deltas
class MergeBroadcast(Broadcast):
"""
Branches a single incoming layer or object (broadcast) into multiple output paths that are
then combined again (merged). This container supports several options for concatenating the
paths ("recurrent", "depth", and "stack").
"recurrent" is used when merging two recurrent output streams.
"depth" concatenates activations that have a notion of spatial dimension. Multiple
activations can be concatenated along the feature map dimension, but the feature map
shapes have to be the same.
"stack" ignores the feature map shape and simply stacks the non-batch dimensions
atop each other. Used to concatenate the output of fully connected layers with each
other, and fully connected layers with convolutional layers.
For example, suppose we are merging a conv layer with output shape (10, 5, 5)
and a fully connected layer with 100 output nodes. Using 'depth' is not allowable.
By using 'stack', the (10, 5, 5) output of the conv layer would just be interpreted as
250 output nodes that are stacked on top of the 100 nodes from the fully connected
layer to get a total merged output of 350 nodes.
Arguments:
layers (list(list(Layer), LayerContainer): list of either layer lists,
or layer containers. Elements that are
lists will be wrapped in Sequential
containers
merge (string): the merging method. Must be 'recurrent', 'depth', or 'stack'
alphas (list(float), optional): list of alpha values by which to weight the
backpropagated errors
name (str): Container name. Defaults to "MergeBroadcast"
"""
def __init__(self, layers, merge, alphas=None, name=None):
super(MergeBroadcast, self).__init__(layers, name)
self.betas = [1.0 for _ in self.layers]
self.betas[-1] = 0.0
self.alphas = [1.0 for _ in self.layers] if alphas is None else alphas
self.merge = merge # How this MergeBroadcast gets merged
assert self.merge in ("recurrent", "depth", "stack")
self.error_views = None
self.ngLayer = self.be.mergebroadcast_layer(len(layers))
def get_partitions(self, x, slices):
"""
Given a partitioning, slices, of an activation buffer, x, determine which axis to slice
along depending on whether x is a sequential tensor or not.
Arguments:
x:
slices:
Returns:
"""
if x.shape[-1] != self.be.bsz: # This is the sequential case
return [x[:, sl] for sl in slices]
else:
return [x[sl] for sl in slices]
def allocate(self, shared_outputs=None):
"""
Allocate output buffer to store activations from fprop.
Arguments:
shared_outputs (Tensor, optional): pre-allocated tensor for activations to be
computed into
"""
if self.outputs is None:
self.outputs = self.be.iobuf(self.out_shape, shared=shared_outputs,
parallelism=self.parallelism)
self.output_views = self.get_partitions(self.outputs, self.slices)
for l, out_view in zip(self.layers, self.output_views):
l.allocate(shared_outputs=out_view)
def _configure_merge(self):
"""
Helper function for configuring shapes depending on the merge concatenation type
"""
in_shapes = [l.out_shape for l in self.layers]
# Figure out how to merge
if self.merge == "recurrent":
catdims = [xs[1] for xs in in_shapes]
self.out_shape = (in_shapes[0][0], sum(catdims))
stride_size = self.be.bsz
elif self.merge == "depth":
catdims = [xs[0] for xs in in_shapes]
self.out_shape = (sum(catdims),) + in_shapes[0][1:]
stride_size = np.prod(in_shapes[0][1:])
elif self.merge == "stack":
catdims = [xs if isinstance(xs, int) else np.prod(xs) for xs in in_shapes]
self.out_shape = sum(catdims)
stride_size = 1
end_idx = [idx * stride_size for idx in np.cumsum(catdims)]
start_idx = [0] + end_idx[:-1]
self.slices = [slice(s, e) for s, e in zip(start_idx, end_idx)]
def fprop(self, inputs, inference=False):
"""
Apply the forward pass transformation to the input data.
Arguments:
inputs (Tensor): input data
Returns:
Tensor: output data
"""
self.be.fprop_mergebroadcast(
self.ngLayer, inputs, inference, self.outputs,
self.layers, self.out_shape)
return self.outputs
def bprop(self, error, alpha=1.0, beta=0.0):
"""
Apply the backward pass transformation to the input data.
Arguments:
error (Tensor): deltas back propagated from the adjacent higher layer
alpha (float, optional): scale to apply to input for activation
gradient bprop. Defaults to 1.0
beta (float, optional): scale to apply to output activation
gradient bprop. Defaults to 0.0
Returns:
Tensor: deltas to propagate to the adjacent lower layer
"""
if self.error_views is None:
self.error_views = self.get_partitions(error, self.slices)
self.be.bprop_mergebroadcast(
self.ngLayer, self.layers, self.error_views, error,
self.deltas, self.out_shape, alpha, beta, self.alphas, self.betas)
return self.deltas
class MergeMultistream(MergeBroadcast):
"""
Merging multiple input sources via concatenation. This container is similar to MergeBroadcast
except that it receives different streams of input directly from a dataset.
"""
def __init__(self, layers, merge, name=None):
super(MergeMultistream, self).__init__(layers, merge=merge, name=name)
@property
def nest_deltas(self):
return False
def configure(self, in_obj):
"""
Must receive a list of shapes for configuration (one for each pathway)
the shapes correspond to the layer_container attribute
Arguments:
in_obj (list(Tensor)): list of Data tensors provided to each sequential container
"""
self.prev_layer = None
if not isinstance(in_obj, list):
assert hasattr(in_obj, 'shape') and isinstance(in_obj.shape, list)
in_obj = in_obj.shape
assert isinstance(in_obj, list), "Multistream inputs must be interpretable as shapes"
for inp, l in zip(in_obj, self.layers):
l.configure(inp)
self._configure_merge()
return self
def set_deltas(self, delta_buffers):
"""
Use pre-allocated (by layer containers) list of buffers for backpropagated error.
Only set deltas for layers that own their own deltas
Only allocate space if layer owns its own deltas (e.g., bias and activation work in-place,
so do not own their deltas).
Arguments:
delta_buffers (list): list of pre-allocated tensors (provided by layer container)
"""
# delta_buffers ignored here, will generate
# new delta buffers for each sequential container
for l in self.layers:
l.allocate_deltas()
def fprop(self, inputs, inference=False):
"""
Apply the forward pass transformation to the input data.
Arguments:
inputs (Tensor): input data
Returns:
Tensor: output data
"""
for l, inp in zip(self.layers, inputs):
l.fprop(inp, inference)
return self.outputs
def bprop(self, error, alpha=1.0, beta=0.0):
"""
Apply the backward pass transformation to the input data.
Arguments:
error (Tensor): deltas back propagated from the adjacent higher layer
alpha (float, optional): scale to apply to input for activation
gradient bprop. Defaults to 1.0
beta (float, optional): scale to apply to output activation
gradient bprop. Defaults to 0.0
Returns:
Tensor: deltas to propagate to the adjacent lower layer
"""
if self.error_views is None:
self.error_views = self.get_partitions(error, self.slices)
for l, e in zip(self.layers, self.error_views):