trivial_layers.py
25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
# Copyright 2016 Johns Hopkins University (Dan Povey)
# 2016 Vijayaditya Peddinti
# 2017 Google Inc. (vpeddinti@google.com)
# 2017 Vimal Manohar
# Apache 2.0.
""" This module contains layers that just map to a single component.
"""
from __future__ import print_function
import math
import re
import sys
from libs.nnet3.xconfig.basic_layers import XconfigLayerBase
class XconfigRenormComponent(XconfigLayerBase):
"""This class is for parsing lines like
'renorm-component name=renorm1 input=Append(-3,0,3)'
which will produce just a single component, of type NormalizeComponent.
Parameters of the class, and their defaults:
input='[-1]' [Descriptor giving the input of the layer.]
target-rms=1.0 [The target RMS of the NormalizeComponent]
"""
def __init__(self, first_token, key_to_value, prev_names=None):
XconfigLayerBase.__init__(self, first_token, key_to_value, prev_names)
def set_default_configs(self):
self.config = {'input': '[-1]',
'target-rms': 1.0 }
def check_configs(self):
assert self.config['target-rms'] > 0.0
def output_name(self, auxiliary_output=None):
assert auxiliary_output is None
return self.name
def output_dim(self, auxiliary_output=None):
assert auxiliary_output is None
input_dim = self.descriptors['input']['dim']
return input_dim
def get_full_config(self):
ans = []
config_lines = self._generate_config()
for line in config_lines:
for config_name in ['ref', 'final']:
# we do not support user specified matrices in this layer
# so 'ref' and 'final' configs are the same.
ans.append((config_name, line))
return ans
def _generate_config(self):
# by 'descriptor_final_string' we mean a string that can appear in
# config-files, i.e. it contains the 'final' names of nodes.
input_desc = self.descriptors['input']['final-string']
input_dim = self.descriptors['input']['dim']
target_rms = self.config['target-rms']
configs = []
line = ('component name={0} type=NormalizeComponent dim={1} target-rms={2}'.format(
self.name, input_dim, target_rms))
configs.append(line)
line = ('component-node name={0} component={0} input={1}'.format(
self.name, input_desc))
configs.append(line)
return configs
class XconfigBatchnormComponent(XconfigLayerBase):
"""This class is for parsing lines like
'batchnorm-component name=batchnorm input=Append(-3,0,3)'
which will produce just a single component, of type BatchNormComponent.
Parameters of the class, and their defaults:
input='[-1]' [Descriptor giving the input of the layer.]
target-rms=1.0 [The target RMS of the BatchNormComponent]
include-in-init=false [You should set this to true if this precedes a
`fixed-affine-layer` that is to be initialized
via LDA]
"""
def __init__(self, first_token, key_to_value, prev_names=None):
XconfigLayerBase.__init__(self, first_token, key_to_value, prev_names)
def set_default_configs(self):
self.config = {'input': '[-1]',
'target-rms': 1.0,
'include-in-init': False}
def check_configs(self):
assert self.config['target-rms'] > 0.0
def output_name(self, auxiliary_output=None):
assert auxiliary_output is None
return self.name
def output_dim(self, auxiliary_output=None):
assert auxiliary_output is None
input_dim = self.descriptors['input']['dim']
return input_dim
def get_full_config(self):
ans = []
config_lines = self._generate_config()
for line in config_lines:
for config_name in ['ref', 'final']:
# we do not support user specified matrices in this layer
# so 'ref' and 'final' configs are the same.
ans.append((config_name, line))
if self.config['include-in-init']:
ans.append(('init', line))
return ans
def _generate_config(self):
# by 'descriptor_final_string' we mean a string that can appear in
# config-files, i.e. it contains the 'final' names of nodes.
input_desc = self.descriptors['input']['final-string']
input_dim = self.descriptors['input']['dim']
target_rms = self.config['target-rms']
configs = []
line = ('component name={0} type=BatchNormComponent dim={1} target-rms={2}'.format(
self.name, input_dim, target_rms))
configs.append(line)
line = ('component-node name={0} component={0} input={1}'.format(
self.name, input_desc))
configs.append(line)
return configs
class XconfigNoOpComponent(XconfigLayerBase):
"""This class is for parsing lines like
'no-op-component name=noop1 input=Append(-3,0,3)'
which will produce just a single component, of type NoOpComponent.
Parameters of the class, and their defaults:
input='[-1]' [Descriptor giving the input of the layer.]
"""
def __init__(self, first_token, key_to_value, prev_names=None):
XconfigLayerBase.__init__(self, first_token, key_to_value, prev_names)
def set_default_configs(self):
self.config = {'input': '[-1]' }
def check_configs(self):
pass
def output_name(self, auxiliary_output=None):
assert auxiliary_output is None
return self.name
def output_dim(self, auxiliary_output=None):
assert auxiliary_output is None
input_dim = self.descriptors['input']['dim']
return input_dim
def get_full_config(self):
ans = []
config_lines = self._generate_config()
for line in config_lines:
for config_name in ['ref', 'final']:
# we do not support user specified matrices in this layer
# so 'ref' and 'final' configs are the same.
ans.append((config_name, line))
return ans
def _generate_config(self):
# by 'descriptor_final_string' we mean a string that can appear in
# config-files, i.e. it contains the 'final' names of nodes.
input_desc = self.descriptors['input']['final-string']
input_dim = self.descriptors['input']['dim']
configs = []
line = ('component name={0} type=NoOpComponent dim={1}'.format(
self.name, input_dim))
configs.append(line)
line = ('component-node name={0} component={0} input={1}'.format(
self.name, input_desc))
configs.append(line)
return configs
class XconfigLinearComponent(XconfigLayerBase):
"""This class is for parsing lines like
'linear-component name=linear1 dim=1024 input=Append(-3,0,3)'
which will produce just a single component, of type LinearComponent, with
output-dim 1024 in this case, and input-dim determined by the dimension
of the input .
Parameters of the class, and their defaults:
input='[-1]' [Descriptor giving the input of the layer.]
dim=-1 [Dimension of the output]
The following (shown with their effective defaults) are just passed through
to the component's config line.
orthonormal-constraint=0.0
max-change=0.75
l2-regularize=0.0
"""
def __init__(self, first_token, key_to_value, prev_names=None):
XconfigLayerBase.__init__(self, first_token, key_to_value, prev_names)
def set_default_configs(self):
self.config = {'input': '[-1]',
'dim': -1,
'orthonormal-constraint': '',
'max-change': 0.75,
'l2-regularize': '',
'param-stddev': '',
'learning-rate-factor': '' }
def check_configs(self):
if self.config['dim'] <= 0:
raise RuntimeError("'dim' must be specified and > 0.")
def output_name(self, auxiliary_output=None):
assert auxiliary_output is None
return self.name
def output_dim(self, auxiliary_output=None):
assert auxiliary_output is None
assert self.config['dim'] > 0
return self.config['dim']
def get_full_config(self):
ans = []
config_lines = self._generate_config()
for line in config_lines:
for config_name in ['ref', 'final']:
# we do not support user specified matrices in this layer
# so 'ref' and 'final' configs are the same.
ans.append((config_name, line))
return ans
def _generate_config(self):
# by 'descriptor_final_string' we mean a string that can appear in
# config-files, i.e. it contains the 'final' names of nodes.
input_desc = self.descriptors['input']['final-string']
input_dim = self.descriptors['input']['dim']
output_dim = self.config['dim']
opts = ''
for opt_name in ['orthonormal-constraint', 'max-change', 'l2-regularize',
'param-stddev', 'learning-rate-factor' ]:
value = self.config[opt_name]
if value != '':
opts += ' {0}={1}'.format(opt_name, value)
configs = []
line = ('component name={0} type=LinearComponent input-dim={1} output-dim={2} '
'{3}'.format(self.name, input_dim, output_dim, opts))
configs.append(line)
line = ('component-node name={0} component={0} input={1}'.format(
self.name, input_desc))
configs.append(line)
return configs
class XconfigCombineFeatureMapsLayer(XconfigLayerBase):
"""This class is for parsing lines like
'combine-feature-maps-layer name=combine_features1 height=40 num-filters1=1 num-filters2=4'
or
'combine-feature-maps-layer name=combine_features1 height=40 num-filters1=1 num-filters2=4 num-filters3=2'
It produces a PermuteComponent. It expects its input to be two or three things
appended together, where the first is of dimension height * num-filters1 and
the second is of dimension height * num-filters2 (and the third, if present is
of dimension height * num-filters2; it interpolates the filters
so the output can be interpreted as a single feature map with the same height
as the input and the sum of the num-filters.
This is to be used in convolutional setups as part of how we combine the
filterbank inputs with ivectors.
"""
def __init__(self, first_token, key_to_value, prev_names=None):
XconfigLayerBase.__init__(self, first_token, key_to_value, prev_names)
def set_default_configs(self):
self.config = { 'input': '[-1]',
'num-filters1': -1,
'num-filters2': -1,
'num-filters3': 0,
'height': -1 }
def check_configs(self):
input_dim = self.descriptors['input']['dim']
if (self.config['num-filters1'] <= 0 or
self.config['num-filters2'] <= 0 or
self.config['num-filters3'] < 0 or
self.config['height'] <= 0):
raise RuntimeError("invalid values of num-filters1, num-filters2 and/or height")
f1 = self.config['num-filters1']
f2 = self.config['num-filters2']
f3 = self.config['num-filters3']
h = self.config['height']
if input_dim != (f1 + f2 + f3) * h:
raise RuntimeError("Expected input-dim={0} based on num-filters1={1}, num-filters2={2}, "
"num-filters3={3} and height={4}, but got input-dim={5}".format(
(f1 + f2 + f3) * h, f1, f2, f3, h, input_dim))
def output_name(self, auxiliary_output=None):
assert auxiliary_output is None
return self.name
def output_dim(self, auxiliary_output=None):
assert auxiliary_output is None
input_dim = self.descriptors['input']['dim']
return input_dim
def get_full_config(self):
ans = []
config_lines = self._generate_config()
for line in config_lines:
for config_name in ['ref', 'final']:
# we do not support user specified matrices in this layer
# so 'ref' and 'final' configs are the same.
ans.append((config_name, line))
return ans
def _generate_config(self):
# by 'descriptor_final_string' we mean a string that can appear in
# config-files, i.e. it contains the 'final' names of nodes.
input_desc = self.descriptors['input']['final-string']
dim = self.descriptors['input']['dim']
num_filters1 = self.config['num-filters1']
num_filters2 = self.config['num-filters2']
num_filters3 = self.config['num-filters3'] # normally 0.
height = self.config['height']
assert dim == (num_filters1 + num_filters2 + num_filters3) * height
column_map = []
for h in range(height):
for f in range(num_filters1):
column_map.append(h * num_filters1 + f)
for f in range(num_filters2):
column_map.append(height * num_filters1 + h * num_filters2 + f)
for f in range(num_filters3):
column_map.append(height * (num_filters1 + num_filters2) + h * num_filters3 + f)
configs = []
line = ('component name={0} type=PermuteComponent column-map={1} '.format(
self.name, ','.join([str(x) for x in column_map])))
configs.append(line)
line = ('component-node name={0} component={0} input={1}'.format(
self.name, input_desc))
configs.append(line)
return configs
class XconfigAffineComponent(XconfigLayerBase):
"""This class is for parsing lines like
'affine-component name=linear1 dim=1024 input=Append(-3,0,3)'
which will produce just a single component, of type NaturalGradientAffineComponent,
with output-dim 1024 in this case, and input-dim determined by the dimension
of the input .
Parameters of the class, and their defaults:
input='[-1]' [Descriptor giving the input of the layer.]
dim=-1 [Dimension of the output]
The following (shown with their effective defaults) are just passed through
to the component's config line.
orthonormal-constraint=0.0
max-change=0.75
l2-regularize=0.0
"""
def __init__(self, first_token, key_to_value, prev_names=None):
XconfigLayerBase.__init__(self, first_token, key_to_value, prev_names)
def set_default_configs(self):
self.config = {'input': '[-1]',
'dim': -1,
'orthonormal-constraint': '',
'max-change': 0.75,
'param-stddev': '',
'bias-stddev': '',
'l2-regularize': '' }
def check_configs(self):
if self.config['dim'] <= 0:
raise RuntimeError("'dim' must be specified and > 0.")
def output_name(self, auxiliary_output=None):
assert auxiliary_output is None
return self.name
def output_dim(self, auxiliary_output=None):
assert auxiliary_output is None
assert self.config['dim'] > 0
return self.config['dim']
def get_full_config(self):
ans = []
config_lines = self._generate_config()
for line in config_lines:
for config_name in ['ref', 'final']:
# we do not support user specified matrices in this layer
# so 'ref' and 'final' configs are the same.
ans.append((config_name, line))
return ans
def _generate_config(self):
# by 'descriptor_final_string' we mean a string that can appear in
# config-files, i.e. it contains the 'final' names of nodes.
input_desc = self.descriptors['input']['final-string']
input_dim = self.descriptors['input']['dim']
output_dim = self.config['dim']
opts = ''
for opt_name in ['orthonormal-constraint', 'max-change', 'l2-regularize',
'param-stddev', 'bias-stddev']:
value = self.config[opt_name]
if value != '':
opts += ' {0}={1}'.format(opt_name, value)
configs = []
line = ('component name={0} type=NaturalGradientAffineComponent input-dim={1} output-dim={2} '
'{3}'.format(self.name, input_dim, output_dim, opts))
configs.append(line)
line = ('component-node name={0} component={0} input={1}'.format(
self.name, input_desc))
configs.append(line)
return configs
class XconfigPerElementScaleComponent(XconfigLayerBase):
"""This class is for parsing lines like
'scale-component name=scale1 input=Append(-3,0,3)'
which will produce just a single component, of type NaturalGradientPerElementScaleComponent, with
output-dim 1024 in this case, and input-dim determined by the dimension of the input .
Parameters of the class, and their defaults:
input='[-1]' [Descriptor giving the input of the layer.]
The following (shown with their effective defaults) are just passed through
to the component's config line. (These defaults are mostly set in the
code).
max-change=0.75
l2-regularize=0.0
param-mean=1.0 # affects initialization
param-stddev=0.0 # affects initialization
learning-rate-factor=1.0
"""
def __init__(self, first_token, key_to_value, prev_names=None):
XconfigLayerBase.__init__(self, first_token, key_to_value, prev_names)
def set_default_configs(self):
self.config = {'input': '[-1]',
'l2-regularize': '',
'max-change': 0.75,
'param-mean': '',
'param-stddev': '',
'learning-rate-factor': '' }
def check_configs(self):
pass
def output_name(self, auxiliary_output=None):
assert auxiliary_output is None
return self.name
def output_dim(self, auxiliary_output=None):
assert auxiliary_output is None
return self.descriptors['input']['dim']
def get_full_config(self):
ans = []
config_lines = self._generate_config()
for line in config_lines:
for config_name in ['ref', 'final']:
# we do not support user specified matrices in this layer
# so 'ref' and 'final' configs are the same.
ans.append((config_name, line))
return ans
def _generate_config(self):
# by 'descriptor_final_string' we mean a string that can appear in
# config-files, i.e. it contains the 'final' names of nodes.
input_desc = self.descriptors['input']['final-string']
dim = self.descriptors['input']['dim']
opts = ''
for opt_name in ['learning-rate-factor', 'max-change', 'l2-regularize', 'param-mean',
'param-stddev' ]:
value = self.config[opt_name]
if value != '':
opts += ' {0}={1}'.format(opt_name, value)
configs = []
line = ('component name={0} type=NaturalGradientPerElementScaleComponent dim={1} {2} '
''.format(self.name, dim, opts))
configs.append(line)
line = ('component-node name={0} component={0} input={1}'.format(
self.name, input_desc))
configs.append(line)
return configs
class XconfigPerElementOffsetComponent(XconfigLayerBase):
"""This class is for parsing lines like
'offset-component name=offset1 input=Append(-3,0,3)'
which will produce just a single component, of type PerElementOffsetComponent, with
output-dim 1024 in this case, and input-dim determined by the dimension of the input .
Parameters of the class, and their defaults:
input='[-1]' [Descriptor giving the input of the layer.]
The following (shown with their effective defaults) are just passed through
to the component's config line. (These defaults are mostly set in the
code).
max-change=0.75
l2-regularize=0.0
param-mean=0.0 # affects initialization
param-stddev=0.0 # affects initialization
learning-rate-factor=1.0
"""
def __init__(self, first_token, key_to_value, prev_names=None):
XconfigLayerBase.__init__(self, first_token, key_to_value, prev_names)
def set_default_configs(self):
self.config = {'input': '[-1]',
'l2-regularize': '',
'max-change': 0.75,
'param-mean': '',
'param-stddev': '',
'learning-rate-factor': '' }
def check_configs(self):
pass
def output_name(self, auxiliary_output=None):
assert auxiliary_output is None
return self.name
def output_dim(self, auxiliary_output=None):
assert auxiliary_output is None
return self.descriptors['input']['dim']
def get_full_config(self):
ans = []
config_lines = self._generate_config()
for line in config_lines:
for config_name in ['ref', 'final']:
# we do not support user specified matrices in this layer
# so 'ref' and 'final' configs are the same.
ans.append((config_name, line))
return ans
def _generate_config(self):
# by 'descriptor_final_string' we mean a string that can appear in
# config-files, i.e. it contains the 'final' names of nodes.
input_desc = self.descriptors['input']['final-string']
dim = self.descriptors['input']['dim']
opts = ''
for opt_name in ['learning-rate-factor', 'max-change', 'l2-regularize', 'param-mean',
'param-stddev' ]:
value = self.config[opt_name]
if value != '':
opts += ' {0}={1}'.format(opt_name, value)
configs = []
line = ('component name={0} type=PerElementOffsetComponent dim={1} {2} '
''.format(self.name, dim, opts))
configs.append(line)
line = ('component-node name={0} component={0} input={1}'.format(
self.name, input_desc))
configs.append(line)
return configs
class XconfigDimRangeComponent(XconfigLayerBase):
"""This class is for parsing lines like
'dim-range-component name=feature1 input=Append(-3,0,3) dim=40 dim-offset=0'
which will produce just a single component, of part of the input.
Parameters of the class, and their defaults:
input='[-1]' [Descriptor giving the input of the layer.]
dim=-1 [Dimension of the output.]
dim-offset=0 [Dimension offset of the input.]
"""
def __init__(self, first_token, key_to_value, prev_names=None):
XconfigLayerBase.__init__(self, first_token, key_to_value, prev_names)
def set_default_configs(self):
self.config = {'input': '[-1]',
'dim': -1,
'dim-offset': 0 }
def check_configs(self):
input_dim = self.descriptors['input']['dim']
if self.config['dim'] <= 0:
raise RuntimeError("'dim' must be specified and > 0.")
elif self.config['dim'] > input_dim:
raise RuntimeError("'dim' must be specified and lower than the input dim.")
if self.config['dim-offset'] < 0 :
raise RuntimeError("'dim-offset' must be specified and >= 0.")
elif self.config['dim-offset'] + self.config['dim'] > input_dim:
raise RuntimeError("'dim-offset' plus output dim must be lower than the input dim.")
def output_name(self, auxiliary_output=None):
assert auxiliary_output is None
return self.name
def output_dim(self, auxiliary_output=None):
assert auxiliary_output is None
output_dim = self.config['dim']
if output_dim <= 0:
self.config['dim'] = self.descriptors['input']['dim']
return output_dim
def get_full_config(self):
ans = []
config_lines = self._generate_config()
for line in config_lines:
for config_name in ['ref', 'final']:
# we do not support user specified matrices in this layer
# so 'ref' and 'final' configs are the same.
ans.append((config_name, line))
return ans
def _generate_config(self):
# by 'descriptor_final_string' we mean a string that can appear in
# config-files, i.e. it contains the 'final' names of nodes.
input_node = self.descriptors['input']['final-string']
output_dim = self.config['dim']
dim_offset = self.config['dim-offset']
configs = []
line = ('dim-range-node name={0} input-node={1} dim={2} dim-offset={3}'.format(
self.name, input_node, output_dim, dim_offset))
configs.append(line)
return configs