forked from rwth-i6/returnn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NetworkHiddenLayer.py
4166 lines (3675 loc) · 184 KB
/
NetworkHiddenLayer.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
from __future__ import print_function
import theano
import numpy
try:
import scipy
import scipy.signal
except ImportError:
scipy = None
import json
import h5py
import sys
from theano import tensor as T
from theano.tensor.nnet import conv
from theano.ifelse import ifelse
try:
from theano.tensor.signal import pool
except ImportError: # old Theano or so...
pool = None
from NetworkBaseLayer import Layer
from ActivationFunctions import strtoact, strtoact_single_joined, elu
import TheanoUtil
from TheanoUtil import class_idx_seq_to_1_of_k
from Log import log
from math import ceil
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from TheanoUtil import print_to_file, DumpOp
class HiddenLayer(Layer):
def __init__(self, activation="sigmoid", **kwargs):
"""
:type activation: str | list[str]
"""
super(HiddenLayer, self).__init__(**kwargs)
self.set_attr('activation', activation.encode("utf8"))
self.activation = strtoact(activation)
self.W_in = [self.add_param(self.create_forward_weights(s.attrs['n_out'],
self.attrs['n_out'],
name="W_in_%s_%s" % (s.name, self.name)))
for s in self.sources]
self.set_attr('from', ",".join([s.name for s in self.sources]))
def get_linear_forward_output(self, with_bias=True, sources=None):
if with_bias:
z = self.b
else:
z = 0
if sources is None:
sources = self.sources
assert len(sources) == len(self.masks) == len(self.W_in)
for s, m, W_in in zip(sources, self.masks, self.W_in):
if s.attrs['sparse']:
if s.output.ndim == 3: out_dim = s.output.shape[2]
elif s.output.ndim == 2: out_dim = 1
else: assert False, s.output.ndim
z += W_in[T.cast(s.output, 'int32')].reshape((s.output.shape[0],s.output.shape[1],out_dim * W_in.shape[1]))
elif m is None:
z += self.dot(s.output, W_in)
else:
z += self.dot(self.mass * m * s.output, W_in)
if self.attrs.get('input_scale', 1.0) != 1.0:
z *= numpy.float32(self.attrs['input_scale'])
return z
class ForwardLayer(HiddenLayer):
layer_class = "hidden"
def __init__(self, sparse_window = 1, **kwargs):
super(ForwardLayer, self).__init__(**kwargs)
self.set_attr('sparse_window', sparse_window) # TODO this is ugly
self.attrs['n_out'] = sparse_window * kwargs['n_out']
self.z = self.get_linear_forward_output()
self.make_output(self.z if self.activation is None else self.activation(self.z))
class SharedForwardLayer(HiddenLayer):
layer_class = "hidden_shared"
def __init__(self, base = None, sparse_window = 1, **kwargs):
kwargs['n_out'] = base[0].b.get_value().shape[0]
super(SharedForwardLayer, self).__init__(**kwargs)
self.params = {}
self.W_in = base[0].W_in
self.b = base[0].b
self.set_attr('sparse_window', sparse_window) # TODO this is ugly
self.attrs['n_out'] = sparse_window * kwargs['n_out']
self.z = self.get_linear_forward_output()
self.make_output(self.z if self.activation is None else self.activation(self.z))
class ClippingLayer(HiddenLayer):
layer_class = "clip"
def __init__(self, sparse_window = 1, **kwargs):
super(ClippingLayer, self).__init__(**kwargs)
z = self.get_linear_forward_output()
target = 'classes' if not 'target' in self.attrs else self.attrs['target']
i = (self.y_in[target].flatten() > 0).nonzero()
znew = z.reshape((z.shape[0]*z.shape[1],z.shape[2]))
#self.make_output(z)
self.make_output(znew[i].reshape((T.sum(self.y_in[target]), z.shape[1], z.shape[2])))
self.index = T.ones((self.output.shape[0], self.output.shape[1]), 'int8')
class EmbeddingLayer(ForwardLayer):
layer_class = "embedding"
def __init__(self, **kwargs):
super(EmbeddingLayer, self).__init__(**kwargs)
self.z -= self.b
self.make_output(self.z if self.activation is None else self.activation(self.z))
class _NoOpLayer(Layer):
"""
Use this as a base class if you want to remove all params by the Layer base class.
Note that this overwrites n_out, so take care of that yourself.
"""
def __init__(self, **kwargs):
# The base class will already have a bias.
# We will reset all this.
# This is easier for now than to refactor the ForwardLayer.
kwargs['n_out'] = 1 # This is a hack so that the super init is fast. Will be reset later.
super(_NoOpLayer, self).__init__(**kwargs)
self.params = {} # Reset all params.
self.set_attr('from', ",".join([s.name for s in self.sources]))
def concat_sources(sources, masks=None, mass=None, unsparse=False, expect_source=True):
"""
:type sources: list[Layer]
:type masks: None | list[theano.Variable]
:type mass: None | theano.Variable
:param bool unsparse: whether to make sparse sources into 1-of-k
:param bool expect_source: whether to throw an exception if there is no source
:returns (concatenated sources, out dim)
:rtype: (theano.Variable, int)
"""
if masks is None: masks = [None] * len(sources)
else: assert mass
assert len(sources) == len(masks)
zs = []
n_out = 0
have_sparse = False
have_non_sparse = False
for s, m in zip(sources, masks):
if s.attrs['sparse']:
if s.output.ndim == 3: out = s.output.reshape((s.output.shape[0], s.output.shape[1]))
elif s.output.ndim == 2: out = s.output
else: assert False, s.output.ndim
if unsparse:
n_out += s.attrs['n_out']
have_non_sparse = True
out_1_of_k = class_idx_seq_to_1_of_k(out, num_classes=s.attrs['n_out'])
zs += [out_1_of_k]
else:
zs += [out.reshape((out.shape[0], out.shape[1], 1))]
assert not have_non_sparse, "mixing sparse and non-sparse sources"
if not have_sparse:
have_sparse = True
n_out = s.attrs['n_out']
else:
assert n_out == s.attrs['n_out'], "expect same num labels but got %i != %i" % (n_out, s.attrs['n_out'])
else: # non-sparse source
n_out += s.attrs['n_out']
have_non_sparse = True
assert not have_sparse, "mixing sparse and non-sparse sources"
if m is None:
zs += [s.output]
else:
zs += [mass * m * s.output]
if len(zs) > 1:
# We get (time,batch,dim) input shape.
# Concat over dimension, axis=2.
return T.concatenate(zs, axis=2), n_out
elif len(zs) == 1:
return zs[0], n_out
else:
if expect_source:
raise Exception("We expected at least one source but did not get any.")
return None, 0
_concat_sources = concat_sources
class CopyLayer(_NoOpLayer):
"""
It's mostly the Identity function. But it will make sparse to non-sparse.
"""
layer_class = "copy"
def __init__(self, activation=None, **kwargs):
super(CopyLayer, self).__init__(**kwargs)
if activation:
self.set_attr('activation', activation.encode("utf8"))
act_f = strtoact_single_joined(activation)
self.z, n_out = concat_sources(self.sources, masks=self.masks, mass=self.mass, unsparse=True)
self.set_attr('n_out', n_out)
self.make_output(act_f(self.z))
class WindowLayer(_NoOpLayer):
layer_class = "window"
def __init__(self, window, delta=0, delta_delta=0, **kwargs):
super(WindowLayer, self).__init__(**kwargs)
source, n_out = concat_sources(self.sources, unsparse=False)
self.set_attr('n_out', n_out * window)
self.set_attr('window', window)
self.set_attr('delta', delta)
self.set_attr('delta_delta', delta_delta)
from TheanoUtil import windowed_batch, delta_batch
out = windowed_batch(source, window=window)
#d = delta_batch() # TODO...
self.make_output(out)
class WindowContextLayer(_NoOpLayer):
layer_class = "window_context"
def __init__(self, window, average='concat', direction = -1, scan=False, n_out=None, **kwargs):
super(WindowContextLayer, self).__init__(**kwargs)
source, n_in = concat_sources(self.sources, unsparse=False)
if n_out is not None:
b = self.create_bias(n_out)
W = self.create_random_normal_weights(n_in, n_out)
source = T.tanh(b + T.dot(source, W))
else:
n_out = n_in
self.set_attr('n_out', n_out)
self.set_attr('window', window)
self.set_attr('average', average)
self.set_attr('direction', direction)
if average == 'exponential':
weights = numpy.float32(1) / T.arange(1, window + 1,dtype='float32')[::-1]
elif average == 'uniform':
weights = numpy.float32(1) / (T.cast(window,'float32') * T.ones((window,),'float32'))
elif average == 'concat':
weights = None
self.set_attr('n_out', n_out * window)
else:
assert False, "invalid averaging method: " + str(average)
if scan:
source = source[::-direction]
inp = T.concatenate([T.zeros((window - 1, source.shape[1], source.shape[2]), 'float32'), source], axis=0)
def wnd(x, i, inp, weights):
return T.dot(inp[i:i + window].dimshuffle(1, 2, 0), weights), i
mapped_out, _ = theano.map(wnd, sequences=[source, T.arange(source.shape[0])], non_sequences=[inp, weights])
self.make_output(mapped_out[0][::-direction])
else:
from TheanoUtil import context_batched
out = context_batched(source[::-direction], window=window)[::-direction]
self.make_output(out)
class DownsampleLayer(_NoOpLayer):
"""
E.g. method == "average", axis == 0, factor == 2 -> each 2 time-frames are averaged.
See TheanoUtil.downsample. You can also use method == "max".
"""
layer_class = "downsample"
def __init__(self, factor, axis, method="average", padding=False, sample_target=False, fit_target=False, base=None, **kwargs):
super(DownsampleLayer, self).__init__(**kwargs)
self.set_attr("method", method)
if isinstance(axis, (str)):
axis = json.loads(axis)
if isinstance(axis, set): axis = tuple(axis)
assert isinstance(axis, int) or isinstance(axis, (tuple, list)), "int or list[int] expected for axis"
if isinstance(axis, int): axis = [axis]
axis = list(sorted(axis))
self.set_attr("axis", axis)
if isinstance(factor, (str)):
factor = json.loads(factor)
assert isinstance(factor, (int, float)) or isinstance(axis, (tuple, list)), "int|float or list[int|float] expected for factor"
if isinstance(factor, (int, float)): factor = [factor] * len(axis)
assert len(factor) == len(axis)
self.set_attr("factor", factor)
z, z_dim = concat_sources(self.sources, unsparse=False)
target = self.attrs.get('target','classes')
self.y_out = self.network.y[target] if base is None else base[0].y_out
self.index_out = self.network.j[target] if base is None else base[0].index_out
n_out = z_dim
import theano.ifelse
for f, a in zip(factor, axis):
if f == 1:
continue
if a == 0:
if padding:
z = T.concatenate([z,T.zeros((f-T.mod(z.shape[a], f), z.shape[1], z.shape[2]), 'float32')],axis=0)
z = TheanoUtil.downsample(z, axis=a, factor=f, method=method)
if sample_target or fit_target:
if self.y_out.dtype == 'float32':
if padding:
self.y_out = T.concatenate(
[self.y_out, T.zeros((f - T.mod(self.y_out.shape[0], f), self.y_out.shape[1], self.y_out.shape[2]),
'float32')], axis=0)
if sample_target:
self.y_out = TheanoUtil.downsample(self.y_out, axis=0, factor=f, method=method)
else:
if padding:
self.y_out = T.concatenate(
[self.y_out, T.zeros((f - T.mod(self.y_out.shape[0], f), self.y_out.shape[1]), 'int32')], axis=0)
if sample_target:
self.y_out = TheanoUtil.downsample(self.y_out, axis=0, factor=f, method='max')
else:
z = TheanoUtil.downsample(z, axis=a, factor=f, method=method)
if a < self.y_out.ndim:
self.y_out = TheanoUtil.downsample(self.y_out, axis=a, factor=f, method='max')
if a == 0:
self.index = self.sources[0].index
if padding:
self.index = T.concatenate([self.index, T.zeros((f-T.mod(self.index.shape[0], f), self.index.shape[1]), 'int8')], axis=0)
if fit_target:
self.index_out = self.index
self.index = TheanoUtil.downsample(self.index, axis=0, factor=f, method="min")
if sample_target:
self.index_out = TheanoUtil.downsample(self.index_out, axis=0, factor=f, method="min")
elif not fit_target:
self.index_out = self.index if base is None else base[0].index_out
elif a == 2:
n_out = int(n_out / f)
output = z
if method == 'concat':
n_out *= numpy.prod(factor)
elif method == 'mlp':
self.DP = self.add_param(self.create_forward_weights(n_out * numpy.prod(factor),z_dim,self.name + "_DP"))
self.b = self.add_param(self.create_bias(z_dim))
output = T.nnet.relu(T.dot(output,self.DP) + self.b)
elif method == 'lstm':
num_batches = z.shape[2]
#z = theano.printing.Print("a", attrs=['shape'])(z)
z = z.dimshuffle(1,0,2,3).reshape((z.shape[1],z.shape[0]*z.shape[2],z.shape[3]))
#z = theano.printing.Print("b", attrs=['shape'])(z)
from math import sqrt
from ActivationFunctions import elu
l = sqrt(6.) / sqrt(6 * n_out)
values = numpy.asarray(self.rng.uniform(low=-l, high=l, size=(n_out, n_out)), dtype=theano.config.floatX)
self.A_in = self.add_param(self.shared(value=values, borrow=True, name = "A_in_" + self.name))
values = numpy.asarray(self.rng.uniform(low=-l, high=l, size=(n_out, n_out)), dtype=theano.config.floatX)
self.A_re = self.add_param(self.shared(value=values, borrow=True, name = "A_re_" + self.name))
def lstmk(z_t, y_p, c_p):
z_t += T.dot(y_p, self.A_re)
partition = z_t.shape[1] / 4
ingate = T.nnet.sigmoid(z_t[:,:partition])
forgetgate = T.nnet.sigmoid(z_t[:,partition:2*partition])
outgate = T.nnet.sigmoid(z_t[:,2*partition:3*partition])
input = T.tanh(z_t[:,3*partition:4*partition])
c_t = forgetgate * c_p + ingate * input
y_t = outgate * T.tanh(c_t)
return (y_t, c_t)
def attent(xt, yp, W_re):
return T.tanh(xt + elu(T.dot(yp, W_re)))
#return T.tanh(T.dot(xt, W_in) + T.dot(yp, W_re))
####z, _ = theano.scan(attent, sequences = T.dot(z,self.A_in), outputs_info = [T.zeros_like(z[0])], non_sequences=[self.A_re])
result, _ = theano.scan(lstmk, sequences = T.dot(z,self.A_in), outputs_info = [T.zeros_like(z[0]),T.zeros_like(z[0])])
z = result[0]
#from OpLSTM import LSTMOpInstance
#inp = T.alloc(numpy.cast[theano.config.floatX](0), z.shape[0], z.shape[1], z.shape[2] * 4) + T.dot(z,self.A_in)
#sta = T.alloc(numpy.cast[theano.config.floatX](0), z.shape[1], z.shape[2])
#idx = T.alloc(numpy.cast[theano.config.floatX](1), z.shape[0], z.shape[1])
#result = LSTMOpInstance(inp, self.A_re, sta, idx)
#result = LSTMOpInstance(T.dot(z,self.A_in), self.A_re, T.zeros_like(z[0]), T.ones_like(z[:,:,0]))
output = z[-1].reshape((z.shape[1] / num_batches, num_batches, z.shape[2]))
#output = result[0][0].reshape((z.shape[1] / num_batches, num_batches, z.shape[2]))
elif method == 'batch':
self.index = TheanoUtil.downsample(self.sources[0].index, axis=0, factor=factor[0], method="batch")
#z = theano.printing.Print("d", attrs=['shape'])(z)
self.set_attr('n_out', n_out)
self.make_output(output)
if fit_target:
self.output = print_to_file('o.out', self.output, shape=True)
self.index_out = print_to_file('o.idx', self.index_out, shape=True)
self.y_out = print_to_file('o.y', self.y_out, shape=True)
class UpsampleLayer(_NoOpLayer):
layer_class = "upsample"
def __init__(self, factor, axis, time_like_last_source=False, method="nearest-neighbor", **kwargs):
super(UpsampleLayer, self).__init__(**kwargs)
self.set_attr("method", method)
self.set_attr("time_like_last_source", time_like_last_source)
if isinstance(axis, (str, unicode)):
axis = json.loads(axis)
if isinstance(axis, set): axis = tuple(axis)
assert isinstance(axis, int) or isinstance(axis, (tuple, list)), "int or list[int] expected for axis"
if isinstance(axis, int): axis = [axis]
axis = list(sorted(axis))
self.set_attr("axis", axis)
if isinstance(factor, (str, unicode)):
factor = json.loads(factor)
assert isinstance(factor, (int, float)) or isinstance(axis, (tuple, list)), "int|float or list[int|float] expected for factor"
if isinstance(factor, (int, float)): factor = [factor] * len(axis)
assert len(factor) == len(axis)
self.set_attr("factor", factor)
sources = self.sources
assert len(sources) > 0
if time_like_last_source:
assert len(sources) >= 2
source_for_time = sources[-1]
sources = sources[:-1]
else:
source_for_time = None
z, z_dim = concat_sources(sources, unsparse=False)
n_out = z_dim
for f, a in zip(factor, axis):
target_axis_len = None
if a == 0:
assert source_for_time, "not implemented yet otherwise. but this makes most sense anyway."
self.index = source_for_time.index
target_axis_len = self.index.shape[0]
elif a == 2:
n_out = int(n_out * f)
z = TheanoUtil.upsample(z, axis=a, factor=f, method=method, target_axis_len=target_axis_len)
self.set_attr('n_out', n_out)
self.make_output(z)
class RepetitionLayer(_NoOpLayer):
layer_class = "rep"
def __init__(self, factor, **kwargs):
super(RepetitionLayer, self).__init__(**kwargs)
factor = numpy.int32(factor)
self.set_attr("factor", factor)
inp, n_out = _concat_sources(self.sources, masks=self.masks, mass=self.mass)
self.set_attr('n_out', n_out)
time, batch, dim = inp.shape[0], inp.shape[1], inp.shape[2]
self.index = self.index.dimshuffle(0,'x',1).repeat(factor,axis=1).reshape((time * factor, batch))
self.output = inp.dimshuffle(0,'x',1,2).repeat(factor,axis=1).reshape((time * factor,batch,dim))
class FrameConcatZeroLayer(_NoOpLayer): # TODO: This is not correct for max_seqs > 1
"""
Concats zero at the start (left=True) or end in the time-dimension.
I.e. you can e.g. delay the input by N frames.
See also FrameConcatZeroLayer (frame_cutoff).
"""
layer_class = "frame_concat_zero"
def __init__(self, num_frames, left=True, **kwargs):
super(FrameConcatZeroLayer, self).__init__(**kwargs)
self.set_attr("num_frames", num_frames)
self.set_attr("left", left)
assert len(self.sources) == 1
s = self.sources[0]
for attr in ["n_out", "sparse"]:
self.set_attr(attr, s.attrs[attr])
inp = s.output
# We get (time,batch,dim) input shape.
time_shape = [inp.shape[i] for i in range(1, inp.ndim)]
zeros_shape = [num_frames] + time_shape
zeros = T.zeros(zeros_shape, dtype=inp.dtype)
if left:
self.output = T.concatenate([zeros, inp], axis=0)
self.index = T.concatenate([T.repeat(s.index[:1], num_frames, axis=0), s.index], axis=0)
else:
self.output = T.concatenate([inp, zeros], axis=0)
self.index = T.concatenate([s.index, T.repeat(s.index[-1:], num_frames, axis=0)], axis=0)
class FrameCutoffLayer(_NoOpLayer): # TODO: This is not correct for max_seqs > 1
"""
Cutoffs frames at the start (left=True) or end in the time-dimension.
You should use this when you used FrameConcatZeroLayer(frame_concat_zero).
"""
layer_class = "frame_cutoff"
def __init__(self, num_frames, left=True, **kwargs):
super(FrameCutoffLayer, self).__init__(**kwargs)
self.set_attr("num_frames", num_frames)
self.set_attr("left", left)
x_in, n_in = _concat_sources(self.sources, masks=self.masks, mass=self.mass)
i_in = self.sources[0].index
self.set_attr("n_out", n_in)
if left:
self.output = x_in[num_frames:]
self.index = i_in[num_frames:]
else:
self.output = x_in[:-num_frames]
self.index = i_in[:-num_frames]
class ReverseLayer(_NoOpLayer):
"""
Reverses the time-dimension.
"""
layer_class = "reverse"
def __init__(self, **kwargs):
super(ReverseLayer, self).__init__(**kwargs)
assert len(self.sources) == 1
s = self.sources[0]
for attr in ["n_out", "sparse"]:
self.set_attr(attr, s.attrs[attr])
# We get (time,batch,dim) input shape.
self.index = s.index[::-1]
self.output = s.output[::-1]
class CalcStepLayer(_NoOpLayer):
layer_class = "calc_step"
def __init__(self, n_out=None, from_prev="", apply=False, step=None, initial="zero", **kwargs):
super(CalcStepLayer, self).__init__(**kwargs)
if n_out is not None:
self.set_attr("n_out", n_out)
if from_prev:
self.set_attr("from_prev", from_prev.encode("utf8"))
self.set_attr("apply", apply)
if step is not None:
self.set_attr("step", step)
self.set_attr("initial", initial.encode("utf8"))
if not apply:
assert n_out is not None
assert self.network
if self.network.calc_step_base:
prev_layer = self.network.calc_step_base.get_layer(from_prev)
if not prev_layer:
self.network.calc_step_base.print_network_info("Prev-Calc-Step network")
raise Exception("%s not found in prev calc step network" % from_prev)
assert n_out == prev_layer.attrs["n_out"]
self.output = prev_layer.output
else:
# First calc step. Just use zero.
shape = [self.index.shape[0], self.index.shape[1], n_out]
if initial == "zero":
self.output = T.zeros(shape, dtype="float32")
elif initial == "param":
values = numpy.asarray(self.rng.normal(loc=0.0, scale=numpy.sqrt(12. / n_out), size=(n_out,)), dtype="float32")
initial_param = self.add_param(self.shared(value=values, borrow=True, name="output_initial"))
self.output = initial_param.dimshuffle('x', 'x', 0)
else:
raise Exception("CalcStepLayer: initial %s invalid" % initial)
else:
assert step is not None
assert len(self.sources) == 1
assert not from_prev
# We will refer to the previous calc-step layer this way
# so that we ensure that we have already traversed it.
# This is important so that share_params correctly works.
from_prev = self.sources[0].name
assert self.network
subnetwork = self.network.get_calc_step(step)
prev_layer = subnetwork.get_layer(from_prev)
assert prev_layer, "%s not found in subnetwork" % from_prev
if n_out is not None:
assert n_out == prev_layer.attrs["n_out"]
self.set_attr("n_out", prev_layer.attrs["n_out"])
self.output = prev_layer.output
class SubnetworkLayer(_NoOpLayer):
layer_class = "subnetwork"
recurrent = True # we don't know. depends on the subnetwork.
def __init__(self, n_out, subnetwork, load="<random>", data_map=None, trainable=True,
concat_sources=True,
**kwargs):
"""
:param int n_out: output dimension of output layer
:param dict[str,dict] network: subnetwork as dict (JSON content)
:param list[str] data_map: maps the sources (from) of the layer to data input.
the list should be as long as the sources.
default is ["data"], i.e. it expects one source and maps it as data in the subnetwork.
:param bool concat_sources: if we concatenate all sources into one, like it is standard for most other layers
:param str load: load string. filename but can have placeholders via str.format. Or "<random>" for no load.
:param bool trainable: if we take over all params from the subnetwork
"""
super(SubnetworkLayer, self).__init__(**kwargs)
self.set_attr("n_out", n_out)
if isinstance(subnetwork, str):
subnetwork = json.loads(subnetwork)
self.set_attr("subnetwork", subnetwork)
self.set_attr("load", load)
if isinstance(data_map, str):
data_map = json.loads(data_map)
if data_map:
self.set_attr("data_map", data_map)
self.set_attr('concat_sources', concat_sources)
self.set_attr("trainable", trainable)
self.trainable = trainable
if concat_sources:
assert not data_map, "We expect the implicit canonical data_map with concat_sources."
assert self.sources
data, n_in = _concat_sources(self.sources, masks=self.masks, mass=self.mass)
s0 = self.sources[0]
sub_n_out = {"data": [n_in, 1 if s0.attrs['sparse'] else 2],
"classes": [n_out, 1 if self.attrs['sparse'] else 2]}
data_map_d = {"data": data}
data_map_di = {"data": s0.index, "classes": self.index}
data_map = []
else: # not concat_sources
if not data_map:
data_map = ["data"]
assert isinstance(data_map, list)
assert len(data_map) == len(self.sources)
sub_n_out = {"classes": [n_out, 1 if self.attrs['sparse'] else 2]}
data_map_d = {}
data_map_di = {"classes": self.index}
for k, s in zip(data_map, self.sources):
sub_n_out[k] = [s.attrs["n_out"], s.output.ndim - 1]
data_map_d[k] = s.output
data_map_di[k] = s.index
print("New subnetwork", self.name, "with data", {k: s.name for (k, s) in zip(data_map, self.sources)}, sub_n_out, file=log.v2)
self.subnetwork = self.network.new_subnetwork(
json_content=subnetwork, n_out=sub_n_out, data_map=data_map_d, data_map_i=data_map_di)
self.subnetwork.print_network_info(name="layer %r subnetwork" % self.name)
assert self.subnetwork.output["output"].attrs['n_out'] == n_out
if trainable:
self.params.update(self.subnetwork.get_params_shared_flat_dict())
if load == "<random>":
print("subnetwork with random initialization", file=log.v2)
else:
from Config import get_global_config
config = get_global_config() # this is a bit hacky but works fine in all my cases...
model_filename = load % {"self": self,
"global_config_load": config.value("load", None),
"global_config_epoch": config.value("epoch", 0)}
print("loading subnetwork weights from", model_filename, file=log.v2)
import h5py
model_hdf = h5py.File(model_filename, "r")
self.subnetwork.load_hdf(model_hdf)
print("done loading subnetwork weights for", self.name, file=log.v2)
self.output = self.subnetwork.output["output"].output
def cost(self):
if not self.trainable:
return super(SubnetworkLayer, self).cost()
try:
const_cost = T.get_scalar_constant_value(self.subnetwork.total_cost)
if const_cost == 0:
return None, None
except T.NotScalarConstantError:
pass
return self.subnetwork.total_cost, self.subnetwork.known_grads
def make_constraints(self):
if not self.trainable:
return super(SubnetworkLayer, self).make_constraints()
return self.subnetwork.total_constraints
class ClusterDependentSubnetworkLayer(_NoOpLayer):
layer_class = "clustersubnet"
recurrent = True # we don't know. depends on the subnetwork.
def __init__(self, n_out, subnetwork, n_clusters, load="<random>", data_map=None, trainable=True,
concat_sources=True,
**kwargs):
"""
:param int n_out: output dimension of output layer
:param dict[str,dict] network: subnetwork as dict (JSON content)
:param list[str] data_map: maps the sources (from) of the layer to data input.
the list should be as long as the sources.
default is ["data"], i.e. it expects one source and maps it as data in the subnetwork.
:param str load: load string. filename but can have placeholders via str.format. Or "<random>" for no load.
:param bool trainable: if we take over all params from the subnetwork
"""
super(ClusterDependentSubnetworkLayer, self).__init__(**kwargs)
self.set_attr("n_out", n_out)
if isinstance(subnetwork, str):
subnetwork = json.loads(subnetwork)
self.set_attr("subnetwork", subnetwork)
self.set_attr("load", load)
if isinstance(data_map, str):
data_map = json.loads(data_map)
if data_map:
self.set_attr("data_map", data_map)
self.set_attr('concat_sources', concat_sources)
self.set_attr("trainable", trainable)
self.trainable = trainable
self.set_attr("n_clusters", n_clusters)
self.n_clusters = n_clusters
print("ClusterDependentSubnetworkLayer: have %s clusters" % self.n_clusters, file=log.v2)
assert len(self.sources) >= 2, "need input, ..., cluster_map"
sources, cluster_map_source = self.sources[:-1], self.sources[-1]
if concat_sources:
assert not data_map, "We expect the implicit canonical data_map with concat_sources."
assert self.sources
data, n_in = _concat_sources(sources, masks=self.masks[:-1], mass=self.mass)
s0 = sources[0]
sub_n_out = {"data": [n_in, 1 if s0.attrs['sparse'] else 2],
"classes": [n_out, 1 if self.attrs['sparse'] else 2]}
data_map_d = {"data": data}
data_map_di = {"data": s0.index, "classes": self.index}
data_map = []
else: # not concat_sources
if not data_map:
data_map = ["data"]
assert isinstance(data_map, list)
assert len(data_map) == len(sources)
sub_n_out = {"classes": [n_out, 1 if self.attrs['sparse'] else 2]}
data_map_d = {}
data_map_di = {"classes": self.index}
for k, s in zip(data_map, sources):
sub_n_out[k] = [s.attrs["n_out"], s.output.ndim - 1]
data_map_d[k] = s.output
data_map_di[k] = s.index
self.subnetworks = []
for idx in range(0, self.n_clusters):
print("New subnetwork", self.name, "with data", {k: s.name for (k, s) in zip(data_map, sources)}, sub_n_out, file=log.v2)
self.subnetworks.append(self.network.new_subnetwork(
json_content=subnetwork, n_out=sub_n_out, data_map=data_map_d, data_map_i=data_map_di))
assert self.subnetworks[idx].output["output"].attrs['n_out'] == n_out
if trainable:
self.params.update(self.subnetworks[idx].get_params_shared_flat_dict())
if load == "<random>":
print("subnetwork with random initialization", file=log.v2)
else:
from Config import get_global_config
config = get_global_config() # this is a bit hacky but works fine in all my cases...
model_filename = load % {"self": self,
"global_config_load": config.value("load", None),
"global_config_epoch": config.int("epoch", 0)}
print("loading subnetwork weights from", model_filename, file=log.v2)
import h5py
model_hdf = h5py.File(model_filename, "r")
self.subnetworks[idx].load_hdf(model_hdf)
print("done loading subnetwork weights for", self.name, file=log.v2)
self.ref = cluster_map_source.output[0]
## generate output lists and sums with ifelse to only compute specified paths
# output
self.zero_output = T.zeros_like(self.subnetworks[0].output["output"].output)
self.y = [ifelse(T.prod(T.neq(idx, self.ref)), self.zero_output, self.subnetworks[idx].output["output"].output) for idx in range(0, self.n_clusters)]
self.z = self.y[0]
for idx in range(1, self.n_clusters):
self.z += self.y[idx]
self.output = self.z
# costs
self.costs = [ifelse(T.prod(T.neq(idx, self.ref)), T.constant(0), self.subnetworks[idx].total_cost) for idx in
range(0, self.n_clusters)]
self.total_cost = T.sum([self.costs[idx] for idx in range(0, self.n_clusters)])
# grads
# TODO for each TheanoVar in dict do the ifelse thing
self.output_grads = {}
if not self.subnetworks[0].known_grads:
print("known grads is empty", file=log.v5)
else:
raise NotImplementedError
# constraints
self.constraints = [ifelse(T.prod(T.neq(idx, self.ref)), T.constant(0), self.subnetworks[idx].total_constraints) for idx in
range(0, self.n_clusters)]
self.total_constraints = T.sum([self.costs[idx] for idx in range(0, self.n_clusters)])
def cost(self):
if not self.trainable:
return super(SubnetworkLayer, self).cost()
try:
const_cost = T.get_scalar_constant_value(self.total_cost)
if const_cost == 0:
return None, None
except T.NotScalarConstantError:
pass
return self.total_cost, self.output_grads
def make_constraints(self):
if not self.trainable:
return super(SubnetworkLayer, self).make_constraints()
return self.total_constraints
def update_cluster_target(self, seq_tag):
self.ref.set_value(self.cluster_dict(seq_tag))
class IndexToVecLayer(_NoOpLayer):
# IndexToVec convert a running index to a vektor like onehot
# source: [time][batch][1]
# out: [time][batch][n_out]
layer_class = "idx_to_vec"
def __init__(self, n_out, **kwargs):
super(IndexToVecLayer, self).__init__(**kwargs)
self.set_attr('n_out', n_out)
z = T.cast(TheanoUtil.class_idx_seq_to_1_of_k(self.sources[0].output, n_out), dtype="float32")
self.output = z # (time, batch, n_out)
class InterpolationLayer(_NoOpLayer):
# InterpolationLayer interpolates between several layers given an interpolation vector
# source: (n-1) sources[n_out] 1 source[n-1]
# out: [time][batch][n_out]
layer_class = "interp"
def __init__(self, n_out, **kwargs):
super(InterpolationLayer, self).__init__(**kwargs)
self.set_attr('n_out', n_out)
dict_s = []
for s, m in zip(self.sources[:-1], self.masks[:-1]):
assert s.attrs['n_out'] == n_out
if m is None:
s_data = s.output
else:
s_data = self.mass * m * s.output
s_shuffled = s_data.dimshuffle(0, 1, 2, 'x')
dict_s += [s_shuffled]
Y = T.concatenate(dict_s, axis=3) # [time][batch][n_out][n-1]
interp_vec = self.sources[-1].output
# if only one interpolation vector for the whole time is given, extens vector along time axis
import theano.ifelse
x = theano.ifelse.ifelse(T.eq(interp_vec.shape[0],1), T.extra_ops.repeat(interp_vec, Y.shape[0], axis=0), interp_vec)
i, j, m, k = Y.shape # time, batch, n_out, interp
x_ = x.reshape((i * j, k))
Y_ = Y.reshape((i * j, m, k))
z_ = T.batched_tensordot(x_, Y_, (1, 2))
z = z_.reshape((i, j, m))
self.output = z
class ChunkingSublayer(_NoOpLayer):
layer_class = "chunking_sublayer"
recurrent = True # we don't know
def __init__(self, n_out, sublayer,
chunk_size, chunk_step,
chunk_distribution="uniform",
add_left_context=0,
add_right_context=0,
normalize_output=True,
trainable=False,
**kwargs):
super(ChunkingSublayer, self).__init__(**kwargs)
self.set_attr('n_out', n_out)
self.set_attr('chunk_size', chunk_size)
self.set_attr('chunk_step', chunk_step)
if isinstance(sublayer, str):
sublayer = json.loads(sublayer)
self.set_attr('sublayer', sublayer.copy())
self.set_attr('chunk_distribution', chunk_distribution)
self.set_attr('add_left_context', add_left_context)
self.set_attr('add_right_context', add_right_context)
self.set_attr('normalize_output', normalize_output)
self.set_attr('trainable', trainable)
self.trainable = trainable
sub_n_out = sublayer.pop("n_out", None)
if sub_n_out: assert sub_n_out == n_out
if trainable:
sublayer["train_flag"] = self.train_flag
sublayer["mask"] = self.attrs.get("mask", "none")
sublayer["dropout"] = self.attrs.get("dropout", 0.0)
assert len(self.sources) == 1
source = self.sources[0].output
n_in = self.sources[0].attrs["n_out"]
index = self.sources[0].index
assert source.ndim == 3 # not complicated to support others, just not implemented
t_last_start = T.maximum(source.shape[0] - chunk_size, 1)
t_range = T.arange(t_last_start, step=chunk_step)
from NetworkBaseLayer import SourceLayer
from NetworkLayer import get_layer_class
def make_sublayer(source, index, name):
layer_opts = sublayer.copy()
cl = layer_opts.pop("class")
layer_class = get_layer_class(cl)
source_layer = SourceLayer(name="%s_source" % name, n_out=n_in, x_out=source, index=index)
layer = layer_class(sources=[source_layer], index=index, name=name, n_out=n_out, network=self.network, **layer_opts)
self.sublayer = layer
return layer
self.sublayer = None
output = T.zeros((source.shape[0], source.shape[1], n_out), dtype=source.dtype)
output_index_sum = T.zeros([source.shape[0], source.shape[1]], dtype="float32")
def step(t_start, output, output_index_sum, source, index):
t_end = T.minimum(t_start + chunk_size, source.shape[0])
if add_left_context > 0:
t_start_c = T.maximum(t_start - add_left_context, 0)
else:
t_start_c = t_start
if add_right_context > 0:
t_end_c = T.minimum(t_end + add_right_context, source.shape[0])
else:
t_end_c = t_end
chunk = source[t_start_c:t_end_c]
chunk_index = index[t_start_c:t_end_c]
layer = make_sublayer(source=chunk, index=chunk_index, name="%s_sublayer" % self.name)
l_output = layer.output
l_index_f32 = T.cast(layer.index, dtype="float32")
if add_left_context > 0:
l_output = l_output[t_start - t_start_c:]
l_index_f32 = l_index_f32[t_start - t_start_c:]
if add_right_context > 0:
l_output = l_output[:l_output.shape[0] + t_end - t_end_c]
l_index_f32 = l_index_f32[:l_index_f32.shape[0] + t_end - t_end_c]
if chunk_distribution == "uniform": pass # just leave it as it is
elif chunk_distribution == "triangle":
ts = T.arange(1, t_end - t_start + 1)
ts_rev = ts[::-1]
tri = T.cast(T.minimum(ts, ts_rev), dtype="float32").dimshuffle(0, 'x') # time,batch
l_index_f32 = l_index_f32 * tri
elif chunk_distribution == "hamming": # https://en.wikipedia.org/wiki/Window_function#Hamming_window
ts = T.arange(0, t_end - t_start)
alpha = 0.53836
w = alpha - (1.0 - alpha) * T.cos(2.0 * numpy.pi * ts / (ts.shape[0] - 1)) # always >0
w_bc = T.cast(w, dtype="float32").dimshuffle(0, 'x') # time,batch
l_index_f32 = l_index_f32 * w_bc
elif chunk_distribution.startswith("gauss("): # https://en.wikipedia.org/wiki/Window_function#Gaussian_window
modeend = chunk_distribution.find(")")
assert modeend >= 0
sigma = float(chunk_distribution[len("gauss("):modeend])
ts = T.arange(0, t_end - t_start)
N = ts.shape[0] - 1
w = T.exp(-0.5 * ((ts - N / 2.0) / (sigma * N / 2.0)) ** 2) # always >0
w_bc = T.cast(w, dtype="float32").dimshuffle(0, 'x') # time,batch
l_index_f32 = l_index_f32 * w_bc
else:
assert False, "unknown chunk distribution %r" % chunk_distribution
assert l_index_f32.ndim == 2
output = T.inc_subtensor(output[t_start:t_end], l_output * l_index_f32.dimshuffle(0, 1, 'x'))
output_index_sum = T.inc_subtensor(output_index_sum[t_start:t_end], l_index_f32)
return [output, output_index_sum]
(output, output_index_sum), _ = theano.reduce(
step, sequences=[t_range],
non_sequences=[source, index],
outputs_info=[output, output_index_sum])
self.scan_output = output
self.scan_output_index_sum = output_index_sum
self.index = T.gt(output_index_sum, 0)
assert output.ndim == 3
if normalize_output:
output_index_sum = T.maximum(output_index_sum, numpy.float32(1.0))
assert output_index_sum.ndim == 2
output = output / output_index_sum.dimshuffle(0, 1, 'x') # renormalize
self.make_output(output)
assert self.sublayer
if trainable:
self.params.update({"sublayer." + name: param for (name, param) in self.sublayer.params.items()})
def cost(self):
if not self.trainable:
return super(ChunkingSublayer, self).cost()
cost, known_grads = self.sublayer.cost()
if cost is None:
return None, None
return cost * self.sublayer.cost_scale(), known_grads
def make_constraints(self):
if not self.trainable:
return super(ChunkingSublayer, self).make_constraints()
return self.sublayer.make_constraints()
class TimeChunkingLayer(_NoOpLayer):
layer_class = "time_chunking"
def __init__(self, n_out, chunk_size, chunk_step, **kwargs):
super(TimeChunkingLayer, self).__init__(**kwargs)
self.set_attr("n_out", n_out)
self.set_attr("chunk_size", chunk_size)
self.set_attr("chunk_step", chunk_step)
x, n_in = concat_sources(self.sources, masks=self.masks, mass=self.mass, unsparse=True)
self.source_index = self.index
from NativeOp import chunk
self.output, self.index = chunk(x, index=self.source_index, chunk_size=chunk_size, chunk_step=chunk_step)
class TimeUnChunkingLayer(_NoOpLayer):
layer_class = "time_unchunking"
def __init__(self, n_out, chunking_layer, **kwargs):
super(TimeUnChunkingLayer, self).__init__(**kwargs)
self.set_attr("n_out", n_out)
self.set_attr("chunking_layer", chunking_layer)
x, n_in = concat_sources(self.sources, masks=self.masks, mass=self.mass, unsparse=True)
self.source_index = self.index
chunking_layer_o = self.network.get_layer(chunking_layer)
assert isinstance(chunking_layer_o, TimeChunkingLayer)
chunk_size = chunking_layer_o.attrs["chunk_size"]
chunk_step = chunking_layer_o.attrs["chunk_step"]
n_time = chunking_layer_o.source_index.shape[0]
n_batch = chunking_layer_o.source_index.shape[1]
from NativeOp import unchunk
self.output, self.index, _ = unchunk(
x, index=chunking_layer_o.index, chunk_size=chunk_size, chunk_step=chunk_step, n_time=n_time, n_batch=n_batch)
class TimeFlatLayer(_NoOpLayer):
layer_class = "time_flat"
def __init__(self, chunk_size, chunk_step, **kwargs):
super(TimeFlatLayer, self).__init__(**kwargs)
self.set_attr("chunk_size", chunk_size)
self.set_attr("chunk_step", chunk_step)
x, n_in = concat_sources(self.sources, masks=self.masks, mass=self.mass, unsparse=True)
self.set_attr("n_out", n_in)
self.source_index = self.index