Blame view

src/nnet3/nnet-simple-component.cc 181 KB
8dcb6dfcb   Yannick Estève   first commit
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
  // nnet3/nnet-simple-component.cc
  
  // Copyright 2015-2017  Johns Hopkins University (author: Daniel Povey)
  //                2015  Xiaohui Zhang
  //                2015  Guoguo Chen
  //                2015  Daniel Galvez
  //                2016  Yiming Wang
  
  // See ../../COPYING for clarification regarding multiple authors
  //
  // 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
  //
  // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  // MERCHANTABLITY OR NON-INFRINGEMENT.
  // See the Apache 2 License for the specific language governing permissions and
  // limitations under the License.
  
  #include <iterator>
  #include <sstream>
  #include <algorithm>
  #include <iomanip>
  #include "nnet3/nnet-simple-component.h"
  #include "nnet3/nnet-parse.h"
  #include "cudamatrix/cu-math.h"
  
  namespace kaldi {
  namespace nnet3 {
  
  void PnormComponent::Init(int32 input_dim, int32 output_dim)  {
    input_dim_ = input_dim;
    output_dim_ = output_dim;
    KALDI_ASSERT(input_dim_ > 0 && output_dim_ > 0 &&
                 input_dim_ % output_dim_ == 0);
  }
  
  void PnormComponent::InitFromConfig(ConfigLine *cfl) {
    int32 input_dim = 0;
    int32 output_dim = 0;
    bool ok = cfl->GetValue("output-dim", &output_dim) &&
        cfl->GetValue("input-dim", &input_dim);
    if (!ok || cfl->HasUnusedValues() || output_dim <= 0)
      KALDI_ERR << "Invalid initializer for layer of type "
                << Type() << ": \"" << cfl->WholeLine() << "\"";
    Init(input_dim, output_dim);
  }
  
  
  void* PnormComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
                                 const CuMatrixBase<BaseFloat> &in,
                                 CuMatrixBase<BaseFloat> *out) const {
    BaseFloat p = 2.0;
    out->GroupPnorm(in, p);
    return NULL;
  }
  
  void PnormComponent::Backprop(const std::string &debug_info,
                                const ComponentPrecomputedIndexes *indexes,
                                const CuMatrixBase<BaseFloat> &in_value,
                                const CuMatrixBase<BaseFloat> &out_value,
                                const CuMatrixBase<BaseFloat> &out_deriv,
                                void *memo,
                                Component *to_update,
                                CuMatrixBase<BaseFloat> *in_deriv) const {
    if (!in_deriv)
      return;
    BaseFloat p = 2.0;
    in_deriv->DiffGroupPnorm(in_value, out_value, out_deriv, p);
  }
  
  void PnormComponent::Read(std::istream &is, bool binary) {
    ExpectOneOrTwoTokens(is, binary, "<PnormComponent>", "<InputDim>");
    ReadBasicType(is, binary, &input_dim_);
    ExpectToken(is, binary, "<OutputDim>");
    ReadBasicType(is, binary, &output_dim_);
    ExpectToken(is, binary, "</PnormComponent>");
  }
  
  void PnormComponent::Write(std::ostream &os, bool binary) const {
    WriteToken(os, binary, "<PnormComponent>");
    WriteToken(os, binary, "<InputDim>");
    WriteBasicType(os, binary, input_dim_);
    WriteToken(os, binary, "<OutputDim>");
    WriteBasicType(os, binary, output_dim_);
    WriteToken(os, binary, "</PnormComponent>");
  }
  
  DropoutComponent::DropoutComponent(const DropoutComponent &other):
      RandomComponent(other),
      dim_(other.dim_),
      dropout_proportion_(other.dropout_proportion_),
      dropout_per_frame_(other.dropout_per_frame_) { }
  
  Component* DropoutComponent::Copy() const {
    DropoutComponent *ans = new DropoutComponent(*this);
    return ans;
  }
  
  void DropoutComponent::Init(int32 dim, BaseFloat dropout_proportion,
                              bool dropout_per_frame) {
    dropout_proportion_ = dropout_proportion;
    dropout_per_frame_ = dropout_per_frame;
    dim_ = dim;
  }
  
  void DropoutComponent::InitFromConfig(ConfigLine *cfl) {
    int32 dim = 0;
    BaseFloat dropout_proportion = 0.0;
    bool dropout_per_frame = false;
    test_mode_ = false;
    bool ok = cfl->GetValue("dim", &dim) &&
      cfl->GetValue("dropout-proportion", &dropout_proportion);
    cfl->GetValue("dropout-per-frame", &dropout_per_frame);
    // It only makes sense to set test-mode in the config for testing purposes.
    cfl->GetValue("test-mode", &test_mode_);
      // for this stage, dropout is hard coded in
      // normal mode if not declared in config
    if (!ok || cfl->HasUnusedValues() || dim <= 0 ||
        dropout_proportion < 0.0 || dropout_proportion > 1.0)
         KALDI_ERR << "Invalid initializer for layer of type "
                   << Type() << ": \"" << cfl->WholeLine() << "\"";
    Init(dim, dropout_proportion, dropout_per_frame);
  }
  
  std::string DropoutComponent::Info() const {
    std::ostringstream stream;
    stream << Type() << ", dim=" << dim_
           << ", dropout-proportion=" << dropout_proportion_
           << ", dropout-per-frame=" << (dropout_per_frame_ ? "true" : "false");
    return stream.str();
  }
  
  void* DropoutComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
                                   const CuMatrixBase<BaseFloat> &in,
                                   CuMatrixBase<BaseFloat> *out) const {
    KALDI_ASSERT(out->NumRows() == in.NumRows() && out->NumCols() == in.NumCols()
                 && in.NumCols() == dim_);
  
    BaseFloat dropout = dropout_proportion_;
    KALDI_ASSERT(dropout >= 0.0 && dropout <= 1.0);
    if (test_mode_) {
      out->CopyFromMat(in);
      out->Scale(1.0 - dropout);
      return NULL;
    }
    if (!dropout_per_frame_) {
      // This const_cast is only safe assuming you don't attempt
      // to use multi-threaded code with the GPU.
      const_cast<CuRand<BaseFloat>&>(random_generator_).RandUniform(out);
  
      out->Add(-dropout);  // now, a proportion "dropout" will be <0.0
      // apply the function (x>0?1:0).  Now, a proportion
      // "dropout" will be zero and (1 - dropout) will be 1.0.
      out->ApplyHeaviside();
  
      out->MulElements(in);
    } else {
      // randomize the dropout matrix by row,
      // i.e. [[1,1,1,1],[0,0,0,0],[0,0,0,0],[1,1,1,1],[0,0,0,0]]
      CuMatrix<BaseFloat> tmp(1, out->NumRows(), kUndefined);
      // This const_cast is only safe assuming you don't attempt
      // to use multi-threaded code with the GPU.
      const_cast<CuRand<BaseFloat>&>(random_generator_).RandUniform(&tmp);
      tmp.Add(-dropout);
      tmp.ApplyHeaviside();
      out->CopyColsFromVec(tmp.Row(0));
      out->MulElements(in);
    }
    return NULL;
  }
  
  
  void DropoutComponent::Backprop(const std::string &debug_info,
                                  const ComponentPrecomputedIndexes *indexes,
                                  const CuMatrixBase<BaseFloat> &in_value,
                                  const CuMatrixBase<BaseFloat> &out_value,
                                  const CuMatrixBase<BaseFloat> &out_deriv,
                                  void *memo,
                                  Component *to_update,
                                  CuMatrixBase<BaseFloat> *in_deriv) const {
    KALDI_ASSERT(in_value.NumRows() == out_value.NumRows() &&
                 in_value.NumCols() == out_value.NumCols());
  
    KALDI_ASSERT(in_value.NumRows() == out_deriv.NumRows() &&
                 in_value.NumCols() == out_deriv.NumCols());
    in_deriv->SetMatMatDivMat(out_deriv, out_value, in_value);
  }
  
  
  
  void DropoutComponent::Read(std::istream &is, bool binary) {
    std::string token;
    ReadToken(is, binary, &token);
    if (token == "<DropoutComponent>") {
      ReadToken(is, binary, &token);
    }
    KALDI_ASSERT(token == "<Dim>");
    ReadBasicType(is, binary, &dim_);  // read dimension.
    ReadToken(is, binary, &token);
    KALDI_ASSERT(token == "<DropoutProportion>");
    ReadBasicType(is, binary, &dropout_proportion_);  // read dropout rate
    ReadToken(is, binary, &token);
    if (token == "<DropoutPerFrame>") {
      ReadBasicType(is, binary, &dropout_per_frame_);  // read dropout mode
      ReadToken(is, binary, &token);
    } else {
      dropout_per_frame_ = false;
    }
    if (token == "<TestMode>") {
      ReadBasicType(is, binary, &test_mode_);  // read test mode
      ExpectToken(is, binary, "</DropoutComponent>");
    } else {
      test_mode_ = false;
      KALDI_ASSERT(token == "</DropoutComponent>");
    }
  }
  
  void DropoutComponent::Write(std::ostream &os, bool binary) const {
    WriteToken(os, binary, "<DropoutComponent>");
    WriteToken(os, binary, "<Dim>");
    WriteBasicType(os, binary, dim_);
    WriteToken(os, binary, "<DropoutProportion>");
    WriteBasicType(os, binary, dropout_proportion_);
    WriteToken(os, binary, "<DropoutPerFrame>");
    WriteBasicType(os, binary, dropout_per_frame_);
    WriteToken(os, binary, "<TestMode>");
    WriteBasicType(os, binary, test_mode_);
    WriteToken(os, binary, "</DropoutComponent>");
  }
  
  void ElementwiseProductComponent::Init(int32 input_dim, int32 output_dim)  {
    input_dim_ = input_dim;
    output_dim_ = output_dim;
    KALDI_ASSERT(input_dim_ > 0 && output_dim_ >= 0);
    KALDI_ASSERT(input_dim_ > output_dim_);
    KALDI_ASSERT(input_dim_ % output_dim_ == 0);
  }
  
  void ElementwiseProductComponent::InitFromConfig(ConfigLine *cfl) {
    int32 input_dim = 0;
    int32 output_dim = 0;
    bool ok = cfl->GetValue("output-dim", &output_dim) &&
        cfl->GetValue("input-dim", &input_dim);
    if (!ok || cfl->HasUnusedValues() || output_dim <= 0)
      KALDI_ERR << "Invalid initializer for layer of type "
                << Type() << ": \"" << cfl->WholeLine() << "\"";
    Init(input_dim, output_dim);
  }
  
  void* ElementwiseProductComponent::Propagate(
      const ComponentPrecomputedIndexes *indexes,
      const CuMatrixBase<BaseFloat> &in,
      CuMatrixBase<BaseFloat> *out) const {
    KALDI_ASSERT(in.NumCols() == input_dim_);
    int32 num_inputs = input_dim_ / output_dim_;
    for (int32 i = 0; i < num_inputs; i++)  {
      CuSubMatrix<BaseFloat> current_in(in, 0, in.NumRows(),
                                        i * output_dim_, output_dim_);
      if (i == 0) {
        out->CopyFromMat(current_in);
      } else  {
        out->MulElements(current_in);
      }
    }
    return NULL;
  }
  
  void ElementwiseProductComponent::Backprop(const std::string &debug_info,
                                const ComponentPrecomputedIndexes *indexes,
                                const CuMatrixBase<BaseFloat> &in_value,
                                const CuMatrixBase<BaseFloat> &out_value,
                                const CuMatrixBase<BaseFloat> &out_deriv,
                                void *memo,
                                Component *to_update,
                                CuMatrixBase<BaseFloat> *in_deriv) const {
    if (!in_deriv)  return;
    int32 num_inputs = input_dim_ / output_dim_;
    for (int32 i = 0; i < num_inputs; i++)  {
      CuSubMatrix<BaseFloat> current_in_deriv(*in_deriv, 0, in_deriv->NumRows(),
                                              i * output_dim_,
                                              output_dim_);
      current_in_deriv.CopyFromMat(out_deriv);
      for (int32 j = 0; j < num_inputs; j++)  {
        if (i == j)
          continue;
        CuSubMatrix<BaseFloat> in_value_partition(in_value, 0,
                                                  in_value.NumRows(),
                                                  j * output_dim_,
                                                  output_dim_);
        current_in_deriv.MulElements(in_value_partition);
      }
    }
  }
  
  void ElementwiseProductComponent::Read(std::istream &is, bool binary) {
    ExpectOneOrTwoTokens(is, binary, "<ElementwiseProductComponent>",
                         "<InputDim>");
    ReadBasicType(is, binary, &input_dim_);
    ExpectToken(is, binary, "<OutputDim>");
    ReadBasicType(is, binary, &output_dim_);
    ExpectToken(is, binary, "</ElementwiseProductComponent>");
  }
  
  void ElementwiseProductComponent::Write(std::ostream &os, bool binary) const {
    WriteToken(os, binary, "<ElementwiseProductComponent>");
    WriteToken(os, binary, "<InputDim>");
    WriteBasicType(os, binary, input_dim_);
    WriteToken(os, binary, "<OutputDim>");
    WriteBasicType(os, binary, output_dim_);
    WriteToken(os, binary, "</ElementwiseProductComponent>");
  }
  
  void* SigmoidComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
                                   const CuMatrixBase<BaseFloat> &in,
                                   CuMatrixBase<BaseFloat> *out) const {
    out->Sigmoid(in);
    return NULL;
  }
  
  void SigmoidComponent::Backprop(const std::string &debug_info,
                                  const ComponentPrecomputedIndexes *indexes,
                                  const CuMatrixBase<BaseFloat> &,
                                  const CuMatrixBase<BaseFloat> &out_value,
                                  const CuMatrixBase<BaseFloat> &out_deriv,
                                  void *memo,
                                  Component *to_update_in,
                                  CuMatrixBase<BaseFloat> *in_deriv) const {
    if (in_deriv != NULL) {
      in_deriv->DiffSigmoid(out_value, out_deriv);
      SigmoidComponent *to_update = dynamic_cast<SigmoidComponent*>(to_update_in);
      if (to_update != NULL) {
        RepairGradients(out_value, in_deriv, to_update);
        to_update->StoreBackpropStats(out_deriv);
      }
    }
  }
  
  void SigmoidComponent::RepairGradients(
      const CuMatrixBase<BaseFloat> &out_value,
      CuMatrixBase<BaseFloat> *in_deriv,
      SigmoidComponent *to_update) const {
    KALDI_ASSERT(to_update != NULL);
    // maximum possible derivative of SigmoidComponent is 0.25.
    // the default lower-threshold on the derivative, below which we
    // add a term to the derivative to encourage the inputs to the sigmoid
    // to be closer to zero, is 0.05, which means the derivative is on average
    // 5 times smaller than its maximum possible value.
    BaseFloat default_lower_threshold = 0.05;
  
    // we use this 'repair_probability' (hardcoded for now) to limit
    // this code to running on about half of the minibatches.
    BaseFloat repair_probability = 0.5;
  
    to_update->num_dims_processed_ += dim_;
  
    if (self_repair_scale_ == 0.0 || count_ == 0.0 || deriv_sum_.Dim() != dim_ ||
        RandUniform() > repair_probability)
      return;
  
    // check that the self-repair scale is in a reasonable range.
    KALDI_ASSERT(self_repair_scale_ > 0.0 && self_repair_scale_ < 0.1);
    BaseFloat unset = kUnsetThreshold; // -1000.0
    BaseFloat lower_threshold = (self_repair_lower_threshold_ == unset ?
                                 default_lower_threshold :
                                 self_repair_lower_threshold_) *
        count_;
    if (self_repair_upper_threshold_ != unset) {
      KALDI_ERR << "Do not set the self-repair-upper-threshold for sigmoid "
                << "components, it does nothing.";
    }
  
    // thresholds_vec is actually a 1-row matrix.  (the ApplyHeaviside
    // function isn't defined for vectors).
    CuMatrix<BaseFloat> thresholds(1, dim_);
    CuSubVector<BaseFloat> thresholds_vec(thresholds, 0);
    thresholds_vec.AddVec(-1.0, deriv_sum_);
    thresholds_vec.Add(lower_threshold);
    thresholds.ApplyHeaviside();
    to_update->num_dims_self_repaired_ += thresholds_vec.Sum();
  
    // At this point, 'thresholds_vec' contains a 1 for each dimension of
    // the output that is 'problematic', i.e. for which the avg-deriv
    // is less than the self-repair lower threshold, and a 0 for
    // each dimension that is not problematic.
  
    // what we want to do is to add
    // -self_repair_scale_ / repair_probability times (2 * output-valiue - 1.0)
    // to the input derivative for each problematic dimension.
  
    // Here, 2 * output - 1.0 is a version of the sigmoid that goes from -1.0 to
    // 1.0, like a tanh.  the negative sign is so that for inputs <0, we push them
    // up towards 0, and for inputs >0, we push them down towards 0.
    // Our use of this sigmoid-type function here is just a convenience since
    // we have it available.  We could use just about any function that is positive
    // for inputs < 0 and negative for inputs > 0.
  
    // We can rearrange the above as: for only the problematic columns,
    //   input-deriv -= 2 * self-repair-scale / repair-probabilty * output
    //   input-deriv +=  self-repair-scale / repair-probabilty
    // which we can write as:
    //   input-deriv -= 2 * self-repair-scale / repair-probabilty * output * thresholds-vec
    //   input-deriv +=  self-repair-scale / repair-probabilty * thresholds-vec
  
    in_deriv->AddMatDiagVec(-2.0 * self_repair_scale_ / repair_probability,
                            out_value, kNoTrans, thresholds_vec);
    in_deriv->AddVecToRows(self_repair_scale_ / repair_probability,
                           thresholds_vec);
  }
  
  
  
  void SigmoidComponent::StoreStats(const CuMatrixBase<BaseFloat> &in_value,
                                    const CuMatrixBase<BaseFloat> &out_value,
                                    void *memo) {
    // Only store stats about every other minibatch (but on the first minibatch,
    // always store it, which is necessary for the ConsolidateMemory() operation
    // to work correctly.
    if (RandInt(0, 1) == 0 && count_ != 0)
      return;
    // derivative of the nonlinearity is out_value * (1.0 - out_value);
    CuMatrix<BaseFloat> temp_deriv(out_value.NumRows(), out_value.NumCols(),
                                   kUndefined);
    temp_deriv.Set(1.0);
    temp_deriv.AddMat(-1.0, out_value);
    temp_deriv.MulElements(out_value);
    StoreStatsInternal(out_value, &temp_deriv);
  }
  
  
  
  void* NoOpComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
                                const CuMatrixBase<BaseFloat> &in,
                                CuMatrixBase<BaseFloat> *out) const {
    out->CopyFromMat(in);
    return NULL;
  }
  
  void NoOpComponent::Backprop(const std::string &debug_info,
                               const ComponentPrecomputedIndexes *indexes,
                               const CuMatrixBase<BaseFloat> &,
                               const CuMatrixBase<BaseFloat> &,
                               const CuMatrixBase<BaseFloat> &out_deriv,
                               void *memo,
                               Component *to_update, // may be NULL; may be identical
                               // to "this" or different.
                               CuMatrixBase<BaseFloat> *in_deriv) const {
    in_deriv->CopyFromMat(out_deriv);
    if (backprop_scale_ != 1.0)
      in_deriv->Scale(backprop_scale_);
  }
  
  void NoOpComponent::InitFromConfig(ConfigLine *cfl) {
    backprop_scale_ = 1.0;
    cfl->GetValue("backprop-scale", &backprop_scale_);
    if (!cfl->GetValue("dim", &dim_) ||
        dim_ <= 0 || cfl->HasUnusedValues()) {
      KALDI_ERR << "Invalid initializer for layer of type "
                << Type() << ": \"" << cfl->WholeLine() << "\"";
    }
  }
  
  std::string NoOpComponent::Info() const {
    std::ostringstream stream;
    stream << Type() << ", dim=" << dim_;
    if (backprop_scale_ != 1.0)
      stream << ", backprop-scale=" << backprop_scale_;
    return stream.str();
  }
  
  void NoOpComponent::Write(std::ostream &os, bool binary) const {
    WriteToken(os, binary, "<NoOpComponent>");
    WriteToken(os, binary, "<Dim>");
    WriteBasicType(os, binary, dim_);
    WriteToken(os, binary, "<BackpropScale>");
    WriteBasicType(os, binary, backprop_scale_);
    WriteToken(os, binary, "</NoOpComponent>");
  }
  
  void NoOpComponent::Read(std::istream &is, bool binary) {
    ExpectOneOrTwoTokens(is, binary, "<NoOpComponent>", "<Dim>");
    ReadBasicType(is, binary, &dim_);
  
    if (PeekToken(is, binary) == 'V') {
      // This is the old format, from when NoOpComponent inherited from
      // NonlinearComponent.
      backprop_scale_ = 1.0;
      ExpectToken(is, binary, "<ValueAvg>");
      CuVector<BaseFloat> temp_vec;
      temp_vec.Read(is, binary);
      ExpectToken(is, binary, "<DerivAvg>");
      temp_vec.Read(is, binary);
      ExpectToken(is, binary, "<Count>");
      BaseFloat temp_float;
      ReadBasicType(is, binary, &temp_float);
      if (PeekToken(is, binary) == 'O') {
        ExpectToken(is, binary, "<OderivRms>");
        temp_vec.Read(is, binary);
        ExpectToken(is, binary, "<OderivCount>");
        ReadBasicType(is, binary, &temp_float);
      }
      std::string token;
      ReadToken(is, binary, &token);
      if (token[0] != '<') {
        // this should happen only rarely, in case we couldn't push back the
        // '<' to the stream in PeekToken().
        token = '<' + token;
      }
      if (token == "<NumDimsSelfRepaired>") {
        ReadBasicType(is, binary, &temp_float);
        ReadToken(is, binary, &token);
      }
      if (token == "<NumDimsProcessed>") {
        ReadBasicType(is, binary, &temp_float);
        ReadToken(is, binary, &token);
      }
      KALDI_ASSERT(token == "</NoOpComponent>");
      return;
    } else {
      ExpectToken(is, binary, "<BackpropScale>");
      ReadBasicType(is, binary, &backprop_scale_);
      ExpectToken(is, binary, "</NoOpComponent>");
    }
  }
  
  
  void ClipGradientComponent::Read(std::istream &is, bool binary) {
    // might not see the "<NaturalGradientAffineComponent>" part because
    // of how ReadNew() works.
    ExpectOneOrTwoTokens(is, binary, "<ClipGradientComponent>",
                         "<Dim>");
    ReadBasicType(is, binary, &dim_);
    ExpectToken(is, binary, "<ClippingThreshold>");
    ReadBasicType(is, binary, &clipping_threshold_);
    ExpectToken(is, binary, "<NormBasedClipping>");
    ReadBasicType(is, binary, &norm_based_clipping_);
    std::string token;
    ReadToken(is, binary, &token);
    if (token == "<SelfRepairClippedProportionThreshold>") {
      ReadBasicType(is, binary, &self_repair_clipped_proportion_threshold_);
      ExpectToken(is, binary, "<SelfRepairTarget>");
      ReadBasicType(is, binary, &self_repair_target_);
      ExpectToken(is, binary, "<SelfRepairScale>");
      ReadBasicType(is, binary, &self_repair_scale_);
      ExpectToken(is, binary, "<NumElementsClipped>");
    } else {
      self_repair_clipped_proportion_threshold_ = 1.0;
      self_repair_target_ = 0.0;
      self_repair_scale_ = 0.0;
      KALDI_ASSERT(token == "<NumElementsClipped>");
    }
    ReadBasicType(is, binary, &num_clipped_);
    ExpectToken(is, binary, "<NumElementsProcessed>");
    ReadBasicType(is, binary, &count_);
    ReadToken(is, binary, &token);
    if (token == "<NumSelfRepaired>") {
      ReadBasicType(is, binary, &num_self_repaired_);
      ExpectToken(is, binary, "<NumBackpropped>");
      ReadBasicType(is, binary, &num_backpropped_);
      ExpectToken(is, binary, "</ClipGradientComponent>");
    } else {
      num_self_repaired_ = 0;
      num_backpropped_ = 0;
      KALDI_ASSERT(token == "</ClipGradientComponent>");
    }
  }
  
  void ClipGradientComponent::Write(std::ostream &os, bool binary) const {
    WriteToken(os, binary, "<ClipGradientComponent>");
    WriteToken(os, binary, "<Dim>");
    WriteBasicType(os, binary, dim_);
    WriteToken(os, binary, "<ClippingThreshold>");
    WriteBasicType(os, binary, clipping_threshold_);
    WriteToken(os, binary, "<NormBasedClipping>");
    WriteBasicType(os, binary, norm_based_clipping_);
    WriteToken(os, binary, "<SelfRepairClippedProportionThreshold>");
    WriteBasicType(os, binary, self_repair_clipped_proportion_threshold_);
    WriteToken(os, binary, "<SelfRepairTarget>");
    WriteBasicType(os, binary, self_repair_target_);
    WriteToken(os, binary, "<SelfRepairScale>");
    WriteBasicType(os, binary, self_repair_scale_);
    WriteToken(os, binary, "<NumElementsClipped>");
    WriteBasicType(os, binary, num_clipped_);
    WriteToken(os, binary, "<NumElementsProcessed>");
    WriteBasicType(os, binary, count_);
    WriteToken(os, binary, "<NumSelfRepaired>");
    WriteBasicType(os, binary, num_self_repaired_);
    WriteToken(os, binary, "<NumBackpropped>");
    WriteBasicType(os, binary, num_backpropped_);
    WriteToken(os, binary, "</ClipGradientComponent>");
  }
  
  std::string ClipGradientComponent::Info() const {
    std::ostringstream stream;
    stream << Type() << ", dim=" << dim_
           << ", norm-based-clipping="
           << (norm_based_clipping_ ? "true" : "false")
           << ", clipping-threshold=" << clipping_threshold_
           << ", clipped-proportion="
           << (count_ > 0 ? static_cast<BaseFloat>(num_clipped_)/count_ : 0);
    if (self_repair_scale_ != 0.0)
      stream << ", self-repair-clipped-proportion-threshold="
             << self_repair_clipped_proportion_threshold_
             << ", self-repair-target=" << self_repair_target_
             << ", self-repair-scale=" << self_repair_scale_;
    return stream.str();
  }
  
  void ClipGradientComponent::Init(int32 dim,
                                   BaseFloat clipping_threshold,
                                   bool norm_based_clipping,
                                   BaseFloat self_repair_clipped_proportion_threshold,
                                   BaseFloat self_repair_target,
                                   BaseFloat self_repair_scale,
                                   int32 num_clipped,
                                   int32 count,
                                   int32 num_self_repaired,
                                   int32 num_backpropped)  {
    KALDI_ASSERT(clipping_threshold >= 0 && dim > 0 &&
        self_repair_clipped_proportion_threshold >= 0.0 &&
        self_repair_target >= 0.0 && self_repair_scale >= 0.0);
    dim_ = dim;
    norm_based_clipping_ = norm_based_clipping;
    clipping_threshold_ = clipping_threshold;
    self_repair_clipped_proportion_threshold_ =
        self_repair_clipped_proportion_threshold;
    self_repair_target_ = self_repair_target;
    self_repair_scale_ = self_repair_scale;
    num_clipped_ = num_clipped;
    count_ = count;
    num_self_repaired_ = num_self_repaired;
    num_backpropped_ = num_backpropped;
  }
  
  void ClipGradientComponent::InitFromConfig(ConfigLine *cfl) {
    int32 dim = 0;
    bool ok = cfl->GetValue("dim", &dim);
    bool norm_based_clipping = false;
    BaseFloat clipping_threshold = 15.0;
    BaseFloat self_repair_clipped_proportion_threshold = 0.01;
    BaseFloat self_repair_target = 0.0;
    BaseFloat self_repair_scale = 1.0;
    cfl->GetValue("clipping-threshold", &clipping_threshold);
    cfl->GetValue("norm-based-clipping", &norm_based_clipping);
    cfl->GetValue("self-repair-clipped-proportion-threshold",
                  &self_repair_clipped_proportion_threshold);
    cfl->GetValue("self-repair-target",
                  &self_repair_target);
    cfl->GetValue("self-repair-scale", &self_repair_scale);
    if (!ok || cfl->HasUnusedValues() ||
        clipping_threshold < 0 || dim <= 0 ||
        self_repair_clipped_proportion_threshold < 0.0 ||
        self_repair_target < 0.0 || self_repair_scale < 0.0)
      KALDI_ERR << "Invalid initializer for layer of type "
                << Type() << ": \"" << cfl->WholeLine() << "\"";
    Init(dim, clipping_threshold, norm_based_clipping,
         self_repair_clipped_proportion_threshold,
         self_repair_target,
         self_repair_scale, 0, 0, 0, 0);
  }
  
  void* ClipGradientComponent::Propagate(
                                   const ComponentPrecomputedIndexes *indexes,
                                   const CuMatrixBase<BaseFloat> &in,
                                   CuMatrixBase<BaseFloat> *out) const {
    out->CopyFromMat(in);
    return NULL;
  }
  
  
  void ClipGradientComponent::Backprop(const std::string &debug_info,
                               const ComponentPrecomputedIndexes *indexes,
                               const CuMatrixBase<BaseFloat> &in_value,
                               const CuMatrixBase<BaseFloat> &,
                               const CuMatrixBase<BaseFloat> &out_deriv,
                               void *memo,
                               Component *to_update_in, // may be NULL; may be identical
                               // to "this" or different.
                               CuMatrixBase<BaseFloat> *in_deriv) const {
    // the following statement will do nothing if in_deriv and out_deriv have same
    // memory.
    in_deriv->CopyFromMat(out_deriv);
  
    ClipGradientComponent *to_update =
        dynamic_cast<ClipGradientComponent*>(to_update_in);
  
    if (clipping_threshold_ > 0) {
      if (norm_based_clipping_) {
        // each row in the derivative matrix, which corresponds to one sample in
        // the mini-batch, is scaled to have a max-norm of clipping_threshold_
        CuVector<BaseFloat> clipping_scales(in_deriv->NumRows());
        clipping_scales.AddDiagMat2(pow(clipping_threshold_, -2), *in_deriv,
                                    kNoTrans, 0.0);
       // now clipping_scales contains the squared (norm of each row divided by
       //  clipping_threshold)
        int32 num_not_scaled;
        clipping_scales.ApplyFloor(1.0, &num_not_scaled);
       // now clipping_scales contains min(1,
       //    squared-(norm/clipping_threshold))
        if (num_not_scaled != clipping_scales.Dim()) {
          clipping_scales.ApplyPow(-0.5);
          // now clipping_scales contains max(1,
          //       clipping_threshold/vector_norm)
          in_deriv->MulRowsVec(clipping_scales);
          if (to_update != NULL)
            to_update->num_clipped_ += (clipping_scales.Dim() - num_not_scaled);
         }
        if (to_update != NULL)
          to_update->count_ += clipping_scales.Dim();
      } else {
        // each element of the derivative matrix, is clipped to be below the
        // clipping_threshold_
        in_deriv->ApplyCeiling(clipping_threshold_);
        in_deriv->ApplyFloor(-1 * clipping_threshold_);
      }
  
      if (to_update != NULL) {
        to_update->num_backpropped_ += 1;
        RepairGradients(debug_info, in_value, in_deriv, to_update);
      }
    } else if (clipping_threshold_ == 0.0) {
      in_deriv->SetZero();
    }
  }
  
  // This function will add a self-repair term to in-deriv, attempting to shrink
  // the magnitude of the input towards self_repair_target_.
  // This term is proportional to [-(input vector - self_repair_target_)].
  // The avarage magnitude of this term is equal to
  // [self_repair_scale_ * clipped_proportion * average norm of input derivative].
  // We use norm of input derivative when computing the magnitude so that it is
  // comparable to the magnitude of input derivative, especially when the gradient
  // explosion is actually happening.
  void ClipGradientComponent::RepairGradients(
      const std::string &debug_info,
      const CuMatrixBase<BaseFloat> &in_value,
      CuMatrixBase<BaseFloat> *in_deriv, ClipGradientComponent *to_update) const {
    KALDI_ASSERT(to_update != NULL);
  
    // we use this 'repair_probability' (hardcoded for now) to limit
    // this code to running on about half of the minibatches.
    BaseFloat repair_probability = 0.5;
    if (self_repair_clipped_proportion_threshold_ >= 1.0 ||
        self_repair_scale_ == 0.0 || count_ == 0 ||
        RandUniform() > repair_probability)
      return;
  
    KALDI_ASSERT(self_repair_target_ >= 0.0 && self_repair_scale_ > 0.0);
  
    BaseFloat clipped_proportion =
      (count_ > 0 ? static_cast<BaseFloat>(num_clipped_) / count_ : 0);
    // in-deriv would be modified only when clipped_proportion exceeds the
    // threshold
    if (clipped_proportion <= self_repair_clipped_proportion_threshold_)
      return;
  
    to_update->num_self_repaired_ += 1;
    if (to_update->debug_info_ == "") // get the component-node name
      to_update->debug_info_ = debug_info;
    if (to_update->num_self_repaired_ == 1)
      KALDI_LOG << "ClipGradientComponent(node_name=" << debug_info
                << ")'s self-repair was activated as the first time at the "
                << to_update->num_backpropped_
                << "-th call of Backprop() in this training job.";
  
    // sign_mat = sign(in_value), i.e.,
    // An element in sign_mat is 1 if its corresponding element in in_value > 0,
    // or -1 otherwise
    CuMatrix<BaseFloat> sign_mat(in_value);
    sign_mat.ApplyHeaviside();
    sign_mat.Scale(2.0);
    sign_mat.Add(-1.0);
  
    // repair_mat =
    // floor(abs(in_value) - self_repair_target_, 0) .* sign(in_value)
    CuMatrix<BaseFloat> repair_mat(in_value);
    repair_mat.ApplyPowAbs(1.0);
    repair_mat.Add(-self_repair_target_);
    repair_mat.ApplyFloor(0.0);
    repair_mat.MulElements(sign_mat);
  
    // magnitude =
    // self_repair_scale_ * clipped_proportion * average norm of in-deriv
    CuVector<BaseFloat> in_deriv_norm_vec(in_deriv->NumRows());
    in_deriv_norm_vec.AddDiagMat2(1.0, *in_deriv, kNoTrans, 0.0);
    in_deriv_norm_vec.ApplyPow(0.5);
    double in_deriv_norm_sum = in_deriv_norm_vec.Sum();
    BaseFloat magnitude = self_repair_scale_ * clipped_proportion *
                          (in_deriv_norm_sum / in_deriv_norm_vec.Dim());
  
    CuVector<BaseFloat> repair_mat_norm_vec(repair_mat.NumRows());
    repair_mat_norm_vec.AddDiagMat2(1.0, repair_mat, kNoTrans, 0.0);
    repair_mat_norm_vec.ApplyPow(0.5);
    double repair_mat_norm_sum = repair_mat_norm_vec.Sum();
    double scale = 0.0;
    if (repair_mat_norm_sum != 0.0)
      scale = magnitude / (repair_mat_norm_sum / repair_mat_norm_vec.Dim());
    // repair_mat is scaled so that on average the rows have the norm
    // (magnitude / repair_probability). This will give higher magnitude of
    // self-repair to input vectors that have larger absolute value, which tend to
    // be those that are diverging.
    in_deriv->AddMat(-scale / repair_probability, repair_mat);
    CuVector<BaseFloat> in_deriv_repaired_norm_vec(in_deriv->NumRows());
    in_deriv_repaired_norm_vec.AddDiagMat2(1.0, *in_deriv, kNoTrans, 0.0);
    in_deriv_repaired_norm_vec.ApplyPow(0.5);
    // scale in_deriv to have the same norm as that before adding the self-repair
    // term, in order to avoid increase of the norm caused by self-repair,
    // which may incur more clip of gradient and thus more self-repair
    double in_deriv_repaired_norm_sum = in_deriv_repaired_norm_vec.Sum();
    if (in_deriv_repaired_norm_sum != 0.0)
      in_deriv->Scale(in_deriv_norm_sum / in_deriv_repaired_norm_sum);
  }
  
  void ClipGradientComponent::ZeroStats()  {
    count_ = 0.0;
    num_clipped_ = 0.0;
    num_self_repaired_ = 0;
    num_backpropped_ = 0;
  }
  
  void ClipGradientComponent::Scale(BaseFloat scale) {
    count_ *= scale;
    num_clipped_ *= scale;
  }
  
  void ClipGradientComponent::Add(BaseFloat alpha, const Component &other_in) {
    const ClipGradientComponent *other =
        dynamic_cast<const ClipGradientComponent*>(&other_in);
    KALDI_ASSERT(other != NULL);
    count_ += alpha * other->count_;
    num_clipped_ += alpha * other->num_clipped_;
  }
  
  void* TanhComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
                                const CuMatrixBase<BaseFloat> &in,
                                CuMatrixBase<BaseFloat> *out) const {
    // Apply tanh function to each element of the output...
    // the tanh function may be written as -1 + ( 2 / (1 + e^{-2 x})),
    // which is a scaled and shifted sigmoid.
    out->Tanh(in);
    return NULL;
  }
  
  
  void TanhComponent::RepairGradients(
      const CuMatrixBase<BaseFloat> &out_value,
      CuMatrixBase<BaseFloat> *in_deriv,
      TanhComponent *to_update) const {
    KALDI_ASSERT(to_update != NULL);
    // maximum possible derivative of SigmoidComponent is 1.0
    // the default lower-threshold on the derivative, below which we
    // add a term to the derivative to encourage the inputs to the sigmoid
    // to be closer to zero, is 0.2, which means the derivative is on average
    // 5 times smaller than its maximum possible value.
    BaseFloat default_lower_threshold = 0.2;
  
    // we use this 'repair_probability' (hardcoded for now) to limit
    // this code to running on about half of the minibatches.
    BaseFloat repair_probability = 0.5;
  
    to_update->num_dims_processed_ += dim_;
  
    if (self_repair_scale_ == 0.0 || count_ == 0.0 || deriv_sum_.Dim() != dim_ ||
        RandUniform() > repair_probability)
      return;
  
    // check that the self-repair scale is in a reasonable range.
    KALDI_ASSERT(self_repair_scale_ > 0.0 && self_repair_scale_ < 0.1);
    BaseFloat unset = kUnsetThreshold; // -1000.0
    BaseFloat lower_threshold = (self_repair_lower_threshold_ == unset ?
                                 default_lower_threshold :
                                 self_repair_lower_threshold_) *
        count_;
    if (self_repair_upper_threshold_ != unset) {
      KALDI_ERR << "Do not set the self-repair-upper-threshold for sigmoid "
                << "components, it does nothing.";
    }
  
    // thresholds_vec is actually a 1-row matrix.  (the ApplyHeaviside
    // function isn't defined for vectors).
    CuMatrix<BaseFloat> thresholds(1, dim_);
    CuSubVector<BaseFloat> thresholds_vec(thresholds, 0);
    thresholds_vec.AddVec(-1.0, deriv_sum_);
    thresholds_vec.Add(lower_threshold);
    thresholds.ApplyHeaviside();
    to_update->num_dims_self_repaired_ += thresholds_vec.Sum();
  
    // At this point, 'thresholds_vec' contains a 1 for each dimension of
    // the output that is 'problematic', i.e. for which the avg-deriv
    // is less than the self-repair lower threshold, and a 0 for
    // each dimension that is not problematic.
  
    // what we want to do is to add -self_repair_scale_ / repair_probability times
    // output-valiue) to the input derivative for each problematic dimension.
    // note that for the tanh, the output-value goes from -1.0 when the input is
    // -inf to +1.0 when the input is +inf.  The negative sign is so that for
    // inputs <0, we push them up towards 0, and for inputs >0, we push them down
    // towards 0.  Our use of the tanh here is just a convenience since we have it
    // available.  We could use just about any function that is positive for
    // inputs < 0 and negative for inputs > 0.
  
    // We can rearrange the above as: for only the problematic columns,
    //   input-deriv -= self-repair-scale / repair-probabilty * output
    // which we can write as:
    //   input-deriv -=  self-repair-scale / repair-probabilty * output * thresholds-vec
  
    in_deriv->AddMatDiagVec(-self_repair_scale_ / repair_probability,
                            out_value, kNoTrans, thresholds_vec);
  }
  
  void TanhComponent::Backprop(const std::string &debug_info,
                               const ComponentPrecomputedIndexes *indexes,
                               const CuMatrixBase<BaseFloat> &,
                               const CuMatrixBase<BaseFloat> &out_value,
                               const CuMatrixBase<BaseFloat> &out_deriv,
                               void *memo,
                               Component *to_update_in, // may be NULL; may be identical
                               // to "this" or different.
                               CuMatrixBase<BaseFloat> *in_deriv) const {
    if (in_deriv != NULL) {
      in_deriv->DiffTanh(out_value, out_deriv);
      TanhComponent *to_update = dynamic_cast<TanhComponent*>(to_update_in);
      if (to_update != NULL) {
        RepairGradients(out_value, in_deriv, to_update);
        to_update->StoreBackpropStats(out_deriv);
      }
    }
  }
  
  /*
    Note on the derivative of the tanh function:
    tanh'(x) = sech^2(x) = -(tanh(x)+1) (tanh(x)-1) = 1 - tanh^2(x)
  
    The element by element equation of what we're doing would be:
    in_deriv = out_deriv * (1.0 - out_value^2).
    We can accomplish this via calls to the matrix library. */
  void TanhComponent::StoreStats(const CuMatrixBase<BaseFloat> &in_value,
                                 const CuMatrixBase<BaseFloat> &out_value,
                                 void *memo) {
    // Only store stats about every other minibatch (but on the first minibatch,
    // always store it, which is necessary for the ConsolidateMemory() operation
    // to work correctly.
    if (RandInt(0, 1) == 0 && count_ != 0)
      return;
    // derivative of the onlinearity is out_value * (1.0 - out_value);
    CuMatrix<BaseFloat> temp_deriv(out_value);
    temp_deriv.ApplyPow(2.0);
    temp_deriv.Scale(-1.0);
    temp_deriv.Add(1.0);
    StoreStatsInternal(out_value, &temp_deriv);
  }
  
  void* RectifiedLinearComponent::Propagate(
      const ComponentPrecomputedIndexes *indexes,
      const CuMatrixBase<BaseFloat> &in,
      CuMatrixBase<BaseFloat> *out) const {
    // Apply rectified linear function (x >= 0 ? 1.0 : 0.0)
    out->CopyFromMat(in);
    out->ApplyFloor(0.0);
    return NULL;
  }
  
  void RectifiedLinearComponent::Backprop(
      const std::string &debug_info,
      const ComponentPrecomputedIndexes *indexes,
      const CuMatrixBase<BaseFloat> &, //in_value
      const CuMatrixBase<BaseFloat> &out_value,
      const CuMatrixBase<BaseFloat> &out_deriv,
      void *memo,
      Component *to_update_in,
      CuMatrixBase<BaseFloat> *in_deriv) const {
    if (in_deriv != NULL) {
      in_deriv->Heaviside(out_value);
      in_deriv->MulElements(out_deriv);
      RectifiedLinearComponent *to_update =
          dynamic_cast<RectifiedLinearComponent*>(to_update_in);
      if (to_update != NULL) {
        RepairGradients(in_deriv, to_update);
        to_update->StoreBackpropStats(out_deriv);
      }
    }
  }
  
  
  void RectifiedLinearComponent::RepairGradients(
      CuMatrixBase<BaseFloat> *in_deriv,
      RectifiedLinearComponent *to_update) const {
    KALDI_ASSERT(to_update != NULL);
    int32 dim = dim_, block_dim = block_dim_;
    BaseFloat default_lower_threshold = 0.05,
        default_upper_threshold = 0.95;
    // we use this 'repair_probability' (hardcoded for now) to limit
    // this code to running on about half of the minibatches.
    BaseFloat repair_probability = 0.5;
    KALDI_ASSERT(in_deriv->NumCols() == dim || in_deriv->NumCols() == block_dim);
    if (self_repair_scale_ == 0.0 || count_ == 0.0 ||
        deriv_sum_.Dim() != dim)
      return;
  
    if (in_deriv->NumCols() != block_dim) {
      KALDI_ASSERT(in_deriv->NumCols() == in_deriv->Stride());
      int32 dim_multiple = dim / block_dim;
      CuSubMatrix<BaseFloat> in_deriv_reshaped(in_deriv->Data(),
                                               in_deriv->NumRows() * dim_multiple,
                                               block_dim, block_dim);
      RepairGradients(&in_deriv_reshaped, to_update);
      return;
    }
  
    // By now we know that in_deriv->NumCols() == block_dim.
  
    if (RandUniform() > repair_probability)
      return;
  
    to_update->num_dims_processed_ += block_dim;
  
    // check that the self-repair scale is in a reasonable range.
    KALDI_ASSERT(self_repair_scale_ > 0.0 && self_repair_scale_ < 0.1);
    BaseFloat unset = kUnsetThreshold; // -1000.0
    BaseFloat count = count_,
        lower_threshold = (self_repair_lower_threshold_ == unset ?
                           default_lower_threshold :
                           self_repair_lower_threshold_) * count,
        upper_threshold = (self_repair_upper_threshold_ == unset ?
                           default_upper_threshold :
                           self_repair_upper_threshold_) * count;
  
    CuMatrix<BaseFloat> storage(2, block_dim + 2, kUndefined);
    CuSubVector<BaseFloat> thresholds_vec(storage.RowData(0) + block_dim, 2);
    CuSubMatrix<BaseFloat> stats_mat(storage, 0, 2, 0, block_dim);
    thresholds_vec(0) = -lower_threshold;
    thresholds_vec(1) = -upper_threshold;
    CuSubVector<BaseFloat> row0(stats_mat, 0);
    CuSubVector<BaseFloat> row1(stats_mat, 1);
  
    if (block_dim == dim) {
      row0.CopyFromVec(deriv_sum_);
    } else {
      CuSubMatrix<double> deriv_sum_mat(deriv_sum_.Data(),
                                        dim / block_dim,
                                        block_dim, block_dim);
      CuVector<double> deriv_sum_dbl(block_dim);
      // get the average of the deriv-sums over the blocks.
      deriv_sum_dbl.AddRowSumMat(block_dim * 1.0 / dim, deriv_sum_mat);
      row0.CopyFromVec(deriv_sum_dbl);
    }
    row1.CopyFromVec(row0);
    stats_mat.AddVecToCols(1.0, thresholds_vec, 1.0);
    // now row0 equals stats - lower_threshold, and
    //     row1 equals stats - upper_threshold.
    stats_mat.ApplyHeaviside();
    // now row0 equals (stats > lower_threshold ? 1 : 0), and
    //     row1 equals (stats > upper_threshold ? 1 : 0).
    // what we want is:
    // self_repair_scale * ((stats <= lower_threshold ? 1 : 0) +
    //                         (stats > upper_threshold ? -1 : 0)).
    //
    // we can get these in stats_mat.Row(0) by computing:
    // -self_repair_scale * (stats_mat.Row(1)  + stats_mat.Row(0) - 1).
    row0.AddVec(1.0, row1, 1.0);
    row0.Add(-1.0);
    CuVector<BaseFloat> temp(row0);
    temp.ApplyPow(2.0);
    to_update->num_dims_self_repaired_ += temp.Sum();
    // [actually we need to divide by repair_probability also, to
    //  correct for the fact that we only do this on some frames.]
    row0.Scale(-self_repair_scale_ / repair_probability);
    in_deriv->AddVecToRows(1.0, row0, 1.0);
  }
  
  
  void RectifiedLinearComponent::StoreStats(
      const CuMatrixBase<BaseFloat> &in_value,
      const CuMatrixBase<BaseFloat> &out_value,
      void *memo) {
    // Only store stats about every other minibatch (but on the first minibatch,
    // always store it, which is necessary for the ConsolidateMemory() operation
    // to work correctly.
    if (RandInt(0, 1) == 0 && count_ != 0)
      return;
    CuMatrix<BaseFloat> temp_deriv(out_value.NumRows(),
                                   out_value.NumCols(),
                                   kUndefined);
    temp_deriv.Heaviside(out_value);
    StoreStatsInternal(out_value, &temp_deriv);
  }
  
  void AffineComponent::Scale(BaseFloat scale) {
    if (scale == 0.0) {
      // If scale == 0.0 we call SetZero() which will get rid of NaN's and inf's.
      linear_params_.SetZero();
      bias_params_.SetZero();
    } else {
      linear_params_.Scale(scale);
      bias_params_.Scale(scale);
    }
  }
  
  void AffineComponent::Resize(int32 input_dim, int32 output_dim) {
    KALDI_ASSERT(input_dim > 0 && output_dim > 0);
    bias_params_.Resize(output_dim);
    linear_params_.Resize(output_dim, input_dim);
  }
  
  void AffineComponent::Add(BaseFloat alpha, const Component &other_in) {
    const AffineComponent *other =
        dynamic_cast<const AffineComponent*>(&other_in);
    KALDI_ASSERT(other != NULL);
    linear_params_.AddMat(alpha, other->linear_params_);
    bias_params_.AddVec(alpha, other->bias_params_);
  }
  
  AffineComponent::AffineComponent(const AffineComponent &component):
      UpdatableComponent(component),
      linear_params_(component.linear_params_),
      bias_params_(component.bias_params_),
      orthonormal_constraint_(component.orthonormal_constraint_) { }
  
  AffineComponent::AffineComponent(const CuMatrixBase<BaseFloat> &linear_params,
                                   const CuVectorBase<BaseFloat> &bias_params,
                                   BaseFloat learning_rate):
      linear_params_(linear_params),
      bias_params_(bias_params),
      orthonormal_constraint_(0.0) {
    SetUnderlyingLearningRate(learning_rate);
    KALDI_ASSERT(linear_params.NumRows() == bias_params.Dim()&&
                 bias_params.Dim() != 0);
  }
  
  void AffineComponent::SetParams(const CuVectorBase<BaseFloat> &bias,
                                  const CuMatrixBase<BaseFloat> &linear) {
    bias_params_ = bias;
    linear_params_ = linear;
    KALDI_ASSERT(bias_params_.Dim() == linear_params_.NumRows());
  }
  
  void AffineComponent::PerturbParams(BaseFloat stddev) {
    CuMatrix<BaseFloat> temp_linear_params(linear_params_);
    temp_linear_params.SetRandn();
    linear_params_.AddMat(stddev, temp_linear_params);
  
    CuVector<BaseFloat> temp_bias_params(bias_params_);
    temp_bias_params.SetRandn();
    bias_params_.AddVec(stddev, temp_bias_params);
  }
  
  std::string AffineComponent::Info() const {
    std::ostringstream stream;
    stream << UpdatableComponent::Info();
    if (orthonormal_constraint_ != 0.0)
      stream << ", orthonormal-constraint=" << orthonormal_constraint_;
    PrintParameterStats(stream, "linear-params", linear_params_,
                        false, // include_mean
                        true, // include_row_norms
                        true, // include_column_norms
                        GetVerboseLevel() >= 2); // include_singular_values
    PrintParameterStats(stream, "bias", bias_params_, true);
    return stream.str();
  }
  
  Component* AffineComponent::Copy() const {
    AffineComponent *ans = new AffineComponent(*this);
    return ans;
  }
  
  BaseFloat AffineComponent::DotProduct(const UpdatableComponent &other_in) const {
    const AffineComponent *other =
        dynamic_cast<const AffineComponent*>(&other_in);
    return TraceMatMat(linear_params_, other->linear_params_, kTrans)
        + VecVec(bias_params_, other->bias_params_);
  }
  
  void AffineComponent::Init(int32 input_dim, int32 output_dim,
                             BaseFloat param_stddev, BaseFloat bias_stddev) {
    linear_params_.Resize(output_dim, input_dim);
    bias_params_.Resize(output_dim);
    KALDI_ASSERT(output_dim > 0 && input_dim > 0 && param_stddev >= 0.0);
    linear_params_.SetRandn(); // sets to random normally distributed noise.
    linear_params_.Scale(param_stddev);
    bias_params_.SetRandn();
    bias_params_.Scale(bias_stddev);
  }
  
  void AffineComponent::Init(std::string matrix_filename) {
    CuMatrix<BaseFloat> mat;
    ReadKaldiObject(matrix_filename, &mat); // will abort on failure.
    KALDI_ASSERT(mat.NumCols() >= 2);
    int32 input_dim = mat.NumCols() - 1, output_dim = mat.NumRows();
    linear_params_.Resize(output_dim, input_dim);
    bias_params_.Resize(output_dim);
    linear_params_.CopyFromMat(mat.Range(0, output_dim, 0, input_dim));
    bias_params_.CopyColFromMat(mat, input_dim);
  }
  
  void AffineComponent::InitFromConfig(ConfigLine *cfl) {
    bool ok = true;
    std::string matrix_filename;
    int32 input_dim = -1, output_dim = -1;
    InitLearningRatesFromConfig(cfl);
    if (cfl->GetValue("matrix", &matrix_filename)) {
      Init(matrix_filename);
      if (cfl->GetValue("input-dim", &input_dim))
        KALDI_ASSERT(input_dim == InputDim() &&
                     "input-dim mismatch vs. matrix.");
      if (cfl->GetValue("output-dim", &output_dim))
        KALDI_ASSERT(output_dim == OutputDim() &&
                     "output-dim mismatch vs. matrix.");
    } else {
      ok = ok && cfl->GetValue("input-dim", &input_dim);
      ok = ok && cfl->GetValue("output-dim", &output_dim);
      BaseFloat param_stddev = 1.0 / std::sqrt(input_dim),
          bias_stddev = 1.0;
      cfl->GetValue("param-stddev", &param_stddev);
      cfl->GetValue("bias-stddev", &bias_stddev);
      Init(input_dim, output_dim,
           param_stddev, bias_stddev);
    }
    cfl->GetValue("orthonormal-constraint", &orthonormal_constraint_);
  
    if (cfl->HasUnusedValues())
      KALDI_ERR << "Could not process these elements in initializer: "
                << cfl->UnusedValues();
    if (!ok)
      KALDI_ERR << "Bad initializer " << cfl->WholeLine();
  }
  
  
  
  
  void* AffineComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
                                  const CuMatrixBase<BaseFloat> &in,
                                   CuMatrixBase<BaseFloat> *out) const {
  
    // No need for asserts as they'll happen within the matrix operations.
    out->CopyRowsFromVec(bias_params_); // copies bias_params_ to each row
    // of *out.
    out->AddMatMat(1.0, in, kNoTrans, linear_params_, kTrans, 1.0);
    return NULL;
  }
  
  void AffineComponent::UpdateSimple(const CuMatrixBase<BaseFloat> &in_value,
                                     const CuMatrixBase<BaseFloat> &out_deriv) {
    bias_params_.AddRowSumMat(learning_rate_, out_deriv, 1.0);
    linear_params_.AddMatMat(learning_rate_, out_deriv, kTrans,
                             in_value, kNoTrans, 1.0);
  }
  
  void AffineComponent::Backprop(const std::string &debug_info,
                                 const ComponentPrecomputedIndexes *indexes,
                                 const CuMatrixBase<BaseFloat> &in_value,
                                 const CuMatrixBase<BaseFloat> &, // out_value
                                 const CuMatrixBase<BaseFloat> &out_deriv,
                                 void *memo,
                                 Component *to_update_in,
                                 CuMatrixBase<BaseFloat> *in_deriv) const {
    AffineComponent *to_update = dynamic_cast<AffineComponent*>(to_update_in);
  
    // Propagate the derivative back to the input.
    // add with coefficient 1.0 since property kBackpropAdds is true.
    // If we wanted to add with coefficient 0.0 we'd need to zero the
    // in_deriv, in case of infinities.
    if (in_deriv)
      in_deriv->AddMatMat(1.0, out_deriv, kNoTrans, linear_params_, kNoTrans,
                          1.0);
  
    if (to_update != NULL) {
      // Next update the model (must do this 2nd so the derivatives we propagate
      // are accurate, in case this == to_update_in.)
      if (to_update->is_gradient_)
        to_update->UpdateSimple(in_value, out_deriv);
      else  // the call below is to a virtual function that may be re-implemented
        to_update->Update(debug_info, in_value, out_deriv);  // by child classes.
    }
  }
  
  void AffineComponent::Read(std::istream &is, bool binary) {
    ReadUpdatableCommon(is, binary);  // read opening tag and learning rate.
    ExpectToken(is, binary, "<LinearParams>");
    linear_params_.Read(is, binary);
    ExpectToken(is, binary, "<BiasParams>");
    bias_params_.Read(is, binary);
    if (PeekToken(is, binary) == 'I') {
      // for back compatibility; we don't write this here any
      // more as it's written and read in Write/ReadUpdatableCommon
      ExpectToken(is, binary, "<IsGradient>");
      ReadBasicType(is, binary, &is_gradient_);
    }
    if (PeekToken(is, binary) == 'O') {
      ExpectToken(is, binary, "<OrthonormalConstraint>");
      ReadBasicType(is, binary, &orthonormal_constraint_);
    } else {
      orthonormal_constraint_ = 0.0;
    }
    ExpectToken(is, binary, "</AffineComponent>");
  }
  
  void AffineComponent::Write(std::ostream &os, bool binary) const {
    WriteUpdatableCommon(os, binary);  // Write opening tag and learning rate
    WriteToken(os, binary, "<LinearParams>");
    linear_params_.Write(os, binary);
    WriteToken(os, binary, "<BiasParams>");
    bias_params_.Write(os, binary);
    if (orthonormal_constraint_ != 0.0) {
      WriteToken(os, binary, "<OrthonormalConstraint>");
      WriteBasicType(os, binary, orthonormal_constraint_);
    }
    WriteToken(os, binary, "</AffineComponent>");
  }
  
  int32 AffineComponent::NumParameters() const {
    return (InputDim() + 1) * OutputDim();
  }
  void AffineComponent::Vectorize(VectorBase<BaseFloat> *params) const {
    KALDI_ASSERT(params->Dim() == this->NumParameters());
    params->Range(0, InputDim() * OutputDim()).CopyRowsFromMat(linear_params_);
    params->Range(InputDim() * OutputDim(),
                  OutputDim()).CopyFromVec(bias_params_);
  }
  void AffineComponent::UnVectorize(const VectorBase<BaseFloat> &params) {
    KALDI_ASSERT(params.Dim() == this->NumParameters());
    linear_params_.CopyRowsFromVec(params.Range(0, InputDim() * OutputDim()));
    bias_params_.CopyFromVec(params.Range(InputDim() * OutputDim(),
                                          OutputDim()));
  }
  
  RepeatedAffineComponent::RepeatedAffineComponent(const RepeatedAffineComponent & component) :
      UpdatableComponent(component),
      linear_params_(component.linear_params_),
      bias_params_(component.bias_params_),
      num_repeats_(component.num_repeats_) {}
  
  
  void RepeatedAffineComponent::Scale(BaseFloat scale) {
    if (scale == 0.0) {
      linear_params_.SetZero();
      bias_params_.SetZero();
    } else {
      linear_params_.Scale(scale);
      bias_params_.Scale(scale);
    }
  }
  
  void RepeatedAffineComponent::Add(BaseFloat alpha, const Component &other_in) {
    const RepeatedAffineComponent *other =
        dynamic_cast<const RepeatedAffineComponent *>(&other_in);
    KALDI_ASSERT(other != NULL);
    linear_params_.AddMat(alpha, other->linear_params_);
    bias_params_.AddVec(alpha, other->bias_params_);
  }
  
  void RepeatedAffineComponent::PerturbParams(BaseFloat stddev){
    CuMatrix<BaseFloat> temp_linear_params(linear_params_);
    temp_linear_params.SetRandn();
    linear_params_.AddMat(stddev, temp_linear_params);
    CuVector<BaseFloat> temp_bias_params(bias_params_);
    temp_bias_params.SetRandn();
    bias_params_.AddVec(stddev, temp_bias_params);
  }
  
  std::string RepeatedAffineComponent::Info() const {
    std::ostringstream stream;
    stream << UpdatableComponent::Info()
           << ", num-repeats=" << num_repeats_;
    PrintParameterStats(stream, "linear-params", linear_params_);
    PrintParameterStats(stream, "bias", bias_params_, true);
    return stream.str();
  }
  
  Component* RepeatedAffineComponent::Copy() const {
    RepeatedAffineComponent *ans = new RepeatedAffineComponent(*this);
    return ans;
  }
  
  BaseFloat RepeatedAffineComponent::DotProduct(const UpdatableComponent &other_in) const {
    const RepeatedAffineComponent *other =
        dynamic_cast<const RepeatedAffineComponent*>(&other_in);
    return TraceMatMat(linear_params_, other->linear_params_, kTrans)
                       + VecVec(bias_params_, other->bias_params_);
  }
  
  void RepeatedAffineComponent::Init(int32 input_dim, int32 output_dim, int32 num_repeats,
                                     BaseFloat param_stddev, BaseFloat bias_mean,
                                     BaseFloat bias_stddev) {
    KALDI_ASSERT(input_dim % num_repeats == 0 && output_dim % num_repeats == 0);
    linear_params_.Resize(output_dim / num_repeats, input_dim / num_repeats);
    bias_params_.Resize(output_dim / num_repeats);
    num_repeats_ = num_repeats;
    KALDI_ASSERT(output_dim > 0 && input_dim > 0 && param_stddev >= 0.0);
    linear_params_.SetRandn(); // sets to random normally distributed noise.
    linear_params_.Scale(param_stddev);
    bias_params_.SetRandn();
    bias_params_.Scale(bias_stddev);
    bias_params_.Add(bias_mean);
    SetNaturalGradientConfigs();
  }
  
  
  void RepeatedAffineComponent::InitFromConfig(ConfigLine *cfl) {
    bool ok = true;
    int32 num_repeats = num_repeats_;
    int32 input_dim = -1, output_dim = -1;
    InitLearningRatesFromConfig(cfl);
    ok = cfl->GetValue("num-repeats", &num_repeats) && ok;
    ok = cfl->GetValue("input-dim", &input_dim) && ok;
    ok = cfl->GetValue("output-dim", &output_dim) && ok;
    KALDI_ASSERT(input_dim % num_repeats == 0 &&
                 "num-repeats must divide input-dim");
    KALDI_ASSERT(output_dim % num_repeats == 0 &&
                 "num-repeats must divide output-dim");
    BaseFloat param_stddev = 1.0 / std::sqrt(input_dim / num_repeats),
        bias_mean = 0.0, bias_stddev = 0.0;
    cfl->GetValue("param-stddev", &param_stddev);
    cfl->GetValue("bias-mean", &bias_mean);
    cfl->GetValue("bias-stddev", &bias_stddev);
    Init(input_dim, output_dim,
         num_repeats, param_stddev, bias_mean, bias_stddev);
    if (cfl->HasUnusedValues())
      KALDI_ERR << "Could not process these elements in initializer: "
                << cfl->UnusedValues();
    if (!ok)
      KALDI_ERR << "Bad initializer " << cfl->WholeLine();
  }
  
  void* RepeatedAffineComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
                                          const CuMatrixBase<BaseFloat> &in,
                                          CuMatrixBase<BaseFloat> *out) const {
    // we gave the kInputContiguous and kOutputContiguous flags-- check that they
    // are honored.
    KALDI_ASSERT(in.NumCols() == in.Stride() &&
                 out->NumCols() == out->Stride() &&
                 out->NumRows() == in.NumRows());
  
    int32 num_repeats = num_repeats_,
        num_rows = in.NumRows(),
        block_dim_out = linear_params_.NumRows(),
        block_dim_in = linear_params_.NumCols();
  
    CuSubMatrix<BaseFloat> in_reshaped(in.Data(), num_rows * num_repeats,
                                       block_dim_in, block_dim_in),
        out_reshaped(out->Data(), num_rows * num_repeats,
                     block_dim_out, block_dim_out);
  
    out_reshaped.CopyRowsFromVec(bias_params_);
  
    out_reshaped.AddMatMat(1.0, in_reshaped, kNoTrans,
                           linear_params_, kTrans, 1.0);
    return NULL;
  }
  
  void RepeatedAffineComponent::Backprop(const std::string &debug_info,
                                         const ComponentPrecomputedIndexes *indexes,
                                         const CuMatrixBase<BaseFloat> &in_value,
                                         const CuMatrixBase<BaseFloat> &, // out_value
                                         const CuMatrixBase<BaseFloat> &out_deriv,
                                         void *memo,
                                         Component *to_update_in,
                                         CuMatrixBase<BaseFloat> *in_deriv) const {
    KALDI_ASSERT(out_deriv.NumCols() == out_deriv.Stride() &&
         (in_value.NumCols() == 0 || in_value.NumCols() == in_value.Stride()) &&
                 (!in_deriv || in_deriv->NumCols() == in_deriv->Stride()));
  
    RepeatedAffineComponent *to_update = dynamic_cast<RepeatedAffineComponent*>(
        to_update_in);
  
    // Propagate the derivative back to the input.
    // add with coefficient 1.0 since property kBackpropAdds is true.
    // If we wanted to add with coefficient 0.0 we'd need to zero the
    // in_deriv, in case of infinities.
    if (in_deriv) {
      int32 num_repeats = num_repeats_,
          num_rows = out_deriv.NumRows(),
          block_dim_out = linear_params_.NumRows(),
          block_dim_in = linear_params_.NumCols();
  
      CuSubMatrix<BaseFloat> in_deriv_reshaped(in_deriv->Data(),
                                               num_rows * num_repeats,
                                               block_dim_in, block_dim_in),
          out_deriv_reshaped(out_deriv.Data(),
                             num_rows * num_repeats,
                             block_dim_out, block_dim_out);
      in_deriv_reshaped.AddMatMat(1.0, out_deriv_reshaped, kNoTrans,
                                  linear_params_, kNoTrans, 1.0);
    }
  
    // Next update the model (must do this 2nd so the derivatives we propagate are
    // accurate, in case this == to_update_in.)
    if (to_update != NULL)
      to_update->Update(in_value, out_deriv);
  }
  
  void RepeatedAffineComponent::Update(const CuMatrixBase<BaseFloat> &in_value,
                                       const CuMatrixBase<BaseFloat> &out_deriv) {
    KALDI_ASSERT(out_deriv.NumCols() == out_deriv.Stride() &&
                 in_value.NumCols() == in_value.Stride() &&
                 in_value.NumRows() == out_deriv.NumRows());
  
  
      int32 num_repeats = num_repeats_,
          num_rows = in_value.NumRows(),
          block_dim_out = linear_params_.NumRows(),
          block_dim_in = linear_params_.NumCols();
  
      CuSubMatrix<BaseFloat> in_value_reshaped(in_value.Data(),
                                               num_rows * num_repeats,
                                               block_dim_in, block_dim_in),
          out_deriv_reshaped(out_deriv.Data(),
                             num_rows * num_repeats,
                             block_dim_out, block_dim_out);
  
  
    linear_params_.AddMatMat(learning_rate_, out_deriv_reshaped, kTrans,
                             in_value_reshaped, kNoTrans, 1.0);
    bias_params_.AddRowSumMat(learning_rate_,
                              out_deriv_reshaped);
  }
  
  void RepeatedAffineComponent::Read(std::istream &is, bool binary) {
    // This Read function also works for NaturalGradientRepeatedAffineComponent.
    ReadUpdatableCommon(is, binary);  // read opening tag and learning rate.
    ExpectToken(is, binary, "<NumRepeats>");
    ReadBasicType(is, binary, &num_repeats_);
    ExpectToken(is, binary, "<LinearParams>");
    linear_params_.Read(is, binary);
    ExpectToken(is, binary, "<BiasParams>");
    bias_params_.Read(is, binary);
    if (PeekToken(is, binary) == 'I') {
      // for back compatibility; we don't write this here any
      // more as it's written and read in Write/ReadUpdatableCommon
      ExpectToken(is, binary, "<IsGradient>");
      ReadBasicType(is, binary, &is_gradient_);
    }
    ExpectToken(is, binary, std::string("</") + Type() + std::string(">"));
    SetNaturalGradientConfigs();
  }
  
  void RepeatedAffineComponent::Write(std::ostream &os, bool binary) const {
    // This Write function also works for NaturalGradientRepeatedAffineComponent.
    WriteUpdatableCommon(os, binary);  // Write opening tag and learning rate
    WriteToken(os, binary, "<NumRepeats>");
    WriteBasicType(os, binary, num_repeats_);
    WriteToken(os, binary, "<LinearParams>");
    linear_params_.Write(os, binary);
    WriteToken(os, binary, "<BiasParams>");
    bias_params_.Write(os, binary);
    // write closing token.
    WriteToken(os, binary, std::string("</") + Type() + std::string(">"));
  }
  
  int32 RepeatedAffineComponent::NumParameters() const {
    // Note: unlike AffineComponent, InputDim() & OutputDim() are not used here and below,
    // for they are multipled by num_repeats_.
    return linear_params_.NumCols() * linear_params_.NumRows() + bias_params_.Dim();
  }
  
  void RepeatedAffineComponent::Vectorize(VectorBase<BaseFloat> *params) const {
    KALDI_ASSERT(params->Dim() == this->NumParameters());
    params->Range(0, linear_params_.NumCols() * linear_params_.NumRows()).CopyRowsFromMat(linear_params_);
    params->Range(linear_params_.NumCols() * linear_params_.NumRows(),
                  bias_params_.Dim()).CopyFromVec(bias_params_);
  }
  
  void RepeatedAffineComponent::UnVectorize(const VectorBase<BaseFloat> &params) {
    KALDI_ASSERT(params.Dim() == this->NumParameters());
    linear_params_.CopyRowsFromVec(params.Range(0, linear_params_.NumCols() * linear_params_.NumRows()));
    bias_params_.CopyFromVec(params.Range(linear_params_.NumCols() * linear_params_.NumRows(),
                                          bias_params_.Dim()));
  }
  
  void NaturalGradientRepeatedAffineComponent::SetNaturalGradientConfigs() {
    int32 rank_in = 40;
    int32 input_dim = linear_params_.NumCols();
    if (rank_in > input_dim / 2)
      rank_in = input_dim / 2;
    if (rank_in < 1)
      rank_in = 1;
    preconditioner_in_.SetRank(rank_in);
    preconditioner_in_.SetUpdatePeriod(4);
  }
  
  NaturalGradientRepeatedAffineComponent::NaturalGradientRepeatedAffineComponent(
      const NaturalGradientRepeatedAffineComponent &other):
      RepeatedAffineComponent(other),
      preconditioner_in_(other.preconditioner_in_) { }
  
  // virtual
  Component* NaturalGradientRepeatedAffineComponent::Copy() const {
    return new NaturalGradientRepeatedAffineComponent(*this);
  }
  
  void NaturalGradientRepeatedAffineComponent::Update(
      const CuMatrixBase<BaseFloat> &in_value,
      const CuMatrixBase<BaseFloat> &out_deriv) {
    KALDI_ASSERT(out_deriv.NumCols() == out_deriv.Stride() &&
                 in_value.NumCols() == in_value.Stride() &&
                 in_value.NumRows() == out_deriv.NumRows());
  
    int32 num_repeats = num_repeats_,
        num_rows = in_value.NumRows(),
        block_dim_out = linear_params_.NumRows(),
        block_dim_in = linear_params_.NumCols();
  
    CuSubMatrix<BaseFloat> in_value_reshaped(in_value.Data(),
                                             num_rows * num_repeats,
                                             block_dim_in, block_dim_in),
          out_deriv_reshaped(out_deriv.Data(),
                             num_rows * num_repeats,
                             block_dim_out, block_dim_out);
  
    CuVector<BaseFloat> bias_deriv(block_dim_out);
    bias_deriv.AddRowSumMat(1.0, out_deriv_reshaped);
  
    CuMatrix<BaseFloat> deriv(block_dim_out,
                              block_dim_in + 1);
    deriv.ColRange(0, block_dim_in).AddMatMat(
        1.0, out_deriv_reshaped, kTrans,
        in_value_reshaped, kNoTrans, 1.0);
    deriv.CopyColFromVec(bias_deriv, block_dim_in);
  
    BaseFloat scale = 1.0;
    if (!is_gradient_) {
      try {
        // Only apply the preconditioning/natural-gradient if we're not computing
        // the exact gradient.
        preconditioner_in_.PreconditionDirections(&deriv, &scale);
      } catch (...) {
        int32 num_bad_rows = 0;
        for (int32 i = 0; i < out_deriv.NumRows(); i++) {
          BaseFloat f = out_deriv.Row(i).Sum();
          if (!(f - f == 0)) num_bad_rows++;
        }
        KALDI_ERR << "Preonditioning failed, in_value sum is "
                  << in_value.Sum() << ", out_deriv sum is " << out_deriv.Sum()
                  << ", out_deriv has " << num_bad_rows << " bad rows.";
      }
    }
    linear_params_.AddMat(learning_rate_ * scale,
                          deriv.ColRange(0, block_dim_in));
    bias_deriv.CopyColFromMat(deriv, block_dim_in);
    bias_params_.AddVec(learning_rate_ * scale, bias_deriv);
  }
  
  void NaturalGradientRepeatedAffineComponent::ConsolidateMemory() {
    OnlineNaturalGradient temp(preconditioner_in_);
    preconditioner_in_.Swap(&temp);
  }
  
  
  BlockAffineComponent::BlockAffineComponent(const BlockAffineComponent &other) :
    UpdatableComponent(other),
    linear_params_(other.linear_params_),
    bias_params_(other.bias_params_),
    num_blocks_(other.num_blocks_) {}
  
  BlockAffineComponent::BlockAffineComponent(const RepeatedAffineComponent &rac) :
    UpdatableComponent(rac),
    linear_params_(rac.num_repeats_ * rac.linear_params_.NumRows(),
                   rac.linear_params_.NumCols(), kUndefined),
    bias_params_(rac.num_repeats_ * rac.linear_params_.NumRows(), kUndefined),
    num_blocks_(rac.num_repeats_) {
    // copy rac's linear_params_ and bias_params_ to this.
    int32 num_rows_in_block = rac.linear_params_.NumRows();
    for(int32 block_counter = 0; block_counter < num_blocks_; block_counter++) {
      int32 row_offset = block_counter * num_rows_in_block;
      CuSubMatrix<BaseFloat> block = this->linear_params_.RowRange(row_offset,
                                                                   num_rows_in_block);
      block.CopyFromMat(rac.linear_params_);
      CuSubVector<BaseFloat> block_bias = this->bias_params_.Range(row_offset,
                                                                   num_rows_in_block);
      block_bias.CopyFromVec(rac.bias_params_);
    }
  }
  
  Component* BlockAffineComponent::Copy() const {
    BlockAffineComponent *ans = new BlockAffineComponent(*this);
    return ans;
  }
  
  std::string BlockAffineComponent::Info() const {
    std::ostringstream stream;
    stream << UpdatableComponent::Info()
           << ", num-blocks=" << num_blocks_;
    PrintParameterStats(stream, "linear-params", linear_params_);
    PrintParameterStats(stream, "bias", bias_params_, true);
    return stream.str();
  }
  
  void BlockAffineComponent::Init(int32 input_dim,
                                  int32 output_dim, int32 num_blocks,
                                  BaseFloat param_stddev, BaseFloat bias_mean,
                                  BaseFloat bias_stddev) {
    KALDI_ASSERT(input_dim > 0 && output_dim > 0 && num_blocks >= 1);
    KALDI_ASSERT(output_dim % num_blocks == 0 && input_dim % num_blocks == 0);
    const int32 num_columns_per_block = input_dim / num_blocks;
    linear_params_.Resize(output_dim, num_columns_per_block);
    bias_params_.Resize(output_dim);
    KALDI_ASSERT(param_stddev >= 0.0 && bias_stddev >= 0.0);
    linear_params_.SetRandn();
    linear_params_.Scale(param_stddev);
    bias_params_.SetRandn();
    bias_params_.Scale(bias_stddev);
    bias_params_.Add(bias_mean);
    num_blocks_ = num_blocks;
  }
  
  void BlockAffineComponent::InitFromConfig(ConfigLine *cfl) {
    int32 input_dim = -1, output_dim = -1, num_blocks = -1;
    if(!cfl->GetValue("input-dim", &input_dim) ||
       !cfl->GetValue("output-dim", &output_dim) ||
       !cfl->GetValue("num-blocks", &num_blocks))
      KALDI_ERR << "Invalid initializer for layer of type "
                << Type() << ": \"" << cfl->WholeLine() << "\"";
    InitLearningRatesFromConfig(cfl);
    BaseFloat param_stddev = 1.0 / std::sqrt(input_dim / num_blocks),
        bias_mean = 0.0, bias_stddev = 1.0;
    cfl->GetValue("param-stddev", &param_stddev);
    cfl->GetValue("bias-stddev", &bias_stddev);
    cfl->GetValue("bias-mean", &bias_mean);
  
    if (cfl->HasUnusedValues())
      KALDI_ERR << "Invalid initializer for layer of type "
                << Type() << ": \"" << cfl->WholeLine() << "\"";
  
    Init(input_dim, output_dim, num_blocks,
         param_stddev, bias_mean, bias_stddev);
  }
  
  void* BlockAffineComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
                                       const CuMatrixBase<BaseFloat> &in,
                                       CuMatrixBase<BaseFloat> *out) const {
    out->CopyRowsFromVec(bias_params_);
    // block_dimension is both the number of columns, and the number of rows,
    // of a block.
    int32 num_rows_in_block = linear_params_.NumRows() / num_blocks_;
    int32 num_cols_in_block = linear_params_.NumCols();
    std::vector<CuSubMatrix<BaseFloat> *> in_batch, out_batch,
      linear_params_batch;
    for(int block_counter = 0; block_counter < num_blocks_; block_counter++) {
      CuSubMatrix<BaseFloat> *in_block =
        new CuSubMatrix<BaseFloat>(in.ColRange(block_counter * num_cols_in_block,
                                     num_cols_in_block));
      in_batch.push_back(in_block);
  
      CuSubMatrix<BaseFloat> *out_block =
        new CuSubMatrix<BaseFloat>(out->ColRange(block_counter * num_rows_in_block,
                                      num_rows_in_block));
      out_batch.push_back(out_block);
  
      CuSubMatrix<BaseFloat> *linear_params_block =
        new CuSubMatrix<BaseFloat>(linear_params_.RowRange(block_counter * num_rows_in_block,
                                                num_rows_in_block));
      linear_params_batch.push_back(linear_params_block);
    }
    AddMatMatBatched<BaseFloat>(1.0, out_batch, in_batch, kNoTrans,
                                linear_params_batch, kTrans, 1.0);
  
    DeletePointers(&in_batch);
    DeletePointers(&out_batch);
    DeletePointers(&linear_params_batch);
    return NULL;
  }
  
  void BlockAffineComponent::Backprop(const std::string &debug_info,
                                      const ComponentPrecomputedIndexes *indexes,
                                      const CuMatrixBase<BaseFloat> &in_value,
                                      const CuMatrixBase<BaseFloat> &, // out_value
                                      const CuMatrixBase<BaseFloat> &out_deriv,
                                      void *memo,
                                      Component *to_update_in,
                                      CuMatrixBase<BaseFloat> *in_deriv) const {
    BlockAffineComponent *to_update = dynamic_cast<BlockAffineComponent*>(to_update_in);
  
    const int32 num_rows_in_block = linear_params_.NumRows() / num_blocks_;
    const int32 num_cols_in_block = linear_params_.NumCols();
  
    // Propagate the derivative back to the input.
    // add with coefficient 1.0 since property kBackpropAdds is true.
    // If we wanted to add with coefficient 0.0 we'd need to zero the
    // in_deriv, in case of infinities.
    if (in_deriv) {
      std::vector<CuSubMatrix<BaseFloat> *> in_deriv_batch, out_deriv_batch, linear_params_batch;
  
      for(int block_counter = 0; block_counter < num_blocks_; block_counter++) {
        CuSubMatrix<BaseFloat> *in_deriv_block =
          new CuSubMatrix<BaseFloat>(in_deriv->ColRange(block_counter * num_cols_in_block,
                                                        num_cols_in_block));
        in_deriv_batch.push_back(in_deriv_block);
  
        CuSubMatrix<BaseFloat> *out_deriv_block =
          new CuSubMatrix<BaseFloat>(out_deriv.ColRange(block_counter * num_rows_in_block,
                                                         num_rows_in_block));
        out_deriv_batch.push_back(out_deriv_block);
  
        CuSubMatrix<BaseFloat> *linear_params_block =
          new CuSubMatrix<BaseFloat>(linear_params_.RowRange(block_counter * num_rows_in_block,
                                                            num_rows_in_block));
        linear_params_batch.push_back(linear_params_block);
      }
  
      AddMatMatBatched<BaseFloat>(1.0, in_deriv_batch, out_deriv_batch, kNoTrans,
                                  linear_params_batch, kNoTrans, 1.0);
  
      DeletePointers(&in_deriv_batch);
      DeletePointers(&out_deriv_batch);
      DeletePointers(&linear_params_batch);
    }
  
    if (to_update != NULL) {
  
      { // linear params update
  
        std::vector<CuSubMatrix<BaseFloat> *> in_value_batch,
          out_deriv_batch, linear_params_batch;
  
        for (int block_counter = 0; block_counter < num_blocks_; block_counter++) {
          CuSubMatrix<BaseFloat> *in_value_block =
            new CuSubMatrix<BaseFloat>(in_value.ColRange(block_counter * num_cols_in_block,
                                                         num_cols_in_block));
          in_value_batch.push_back(in_value_block);
  
          CuSubMatrix<BaseFloat> *out_deriv_block =
            new CuSubMatrix<BaseFloat>(out_deriv.ColRange(block_counter * num_rows_in_block,
                                                          num_rows_in_block));
          out_deriv_batch.push_back(out_deriv_block);
  
          CuSubMatrix<BaseFloat> *linear_params_block =
            new CuSubMatrix<BaseFloat>(to_update->linear_params_.RowRange(block_counter * num_rows_in_block,
                                                                          num_rows_in_block));
          linear_params_batch.push_back(linear_params_block);
        }
  
        AddMatMatBatched<BaseFloat>(to_update->learning_rate_,
                                    linear_params_batch,
                                    out_deriv_batch, kTrans,
                                    in_value_batch, kNoTrans, 1.0);
  
        DeletePointers(&in_value_batch);
        DeletePointers(&out_deriv_batch);
        DeletePointers(&linear_params_batch);
      } // end linear params update
  
      { // bias update
        to_update->bias_params_.AddRowSumMat(to_update->learning_rate_,
                                             out_deriv, 1.0);
      } // end bias update
    }
  }
  
  void BlockAffineComponent::Scale(BaseFloat scale) {
    if (scale == 0.0) {
      linear_params_.SetZero();
      bias_params_.SetZero();
    } else {
      linear_params_.Scale(scale);
      bias_params_.Scale(scale);
    }
  }
  
  void BlockAffineComponent::Add(BaseFloat alpha, const Component &other_in) {
    const BlockAffineComponent *other =
      dynamic_cast<const BlockAffineComponent *>(&other_in);
    KALDI_ASSERT(other != NULL);
    linear_params_.AddMat(alpha, other->linear_params_);
    bias_params_.AddVec(alpha, other->bias_params_);
  }
  
  void BlockAffineComponent::PerturbParams(BaseFloat stddev) {
    CuMatrix<BaseFloat> temp_linear_params(linear_params_);
    temp_linear_params.SetRandn();
    linear_params_.AddMat(stddev, temp_linear_params);
  
    CuVector<BaseFloat> temp_bias_params(bias_params_);
    temp_bias_params.SetRandn();
    bias_params_.AddVec(stddev, temp_bias_params);
  }
  
  BaseFloat BlockAffineComponent::DotProduct(const UpdatableComponent &other_in) const {
    const BlockAffineComponent *other =
      dynamic_cast<const BlockAffineComponent*>(&other_in);
    return TraceMatMat(linear_params_, other->linear_params_, kTrans) +
      VecVec(bias_params_, other->bias_params_);
  }
  
  void BlockAffineComponent::Read(std::istream &is, bool binary) {
    ReadUpdatableCommon(is, binary);  // read opening tag and learning rate.
    ExpectToken(is, binary, "<NumBlocks>");
    ReadBasicType(is, binary, &num_blocks_);
    ExpectToken(is, binary, "<LinearParams>");
    linear_params_.Read(is, binary);
    ExpectToken(is, binary, "<BiasParams>");
    bias_params_.Read(is, binary);
    if (PeekToken(is, binary) == 'I') {
      // for back compatibility; we don't write this here any
      // more as it's written and read in Write/ReadUpdatableCommon
      ExpectToken(is, binary, "<IsGradient>");
      ReadBasicType(is, binary, &is_gradient_);
    }
    ExpectToken(is, binary, "</BlockAffineComponent>");
  }
  
  void BlockAffineComponent::Write(std::ostream &os, bool binary) const {
    WriteUpdatableCommon(os, binary);  // Write opening tag and learning rate
    WriteToken(os, binary, "<NumBlocks>");
    WriteBasicType(os, binary, num_blocks_);
    WriteToken(os, binary, "<LinearParams>");
    linear_params_.Write(os, binary);
    WriteToken(os, binary, "<BiasParams>");
    bias_params_.Write(os, binary);
    WriteToken(os, binary, "</BlockAffineComponent>");
  }
  
  int32 BlockAffineComponent::NumParameters() const {
    return linear_params_.NumCols() * linear_params_.NumRows() + bias_params_.Dim();
  }
  
  void BlockAffineComponent::Vectorize(VectorBase<BaseFloat> *params) const {
    KALDI_ASSERT(params->Dim() == this->NumParameters());
    int32 num_linear_params = linear_params_.NumCols() * linear_params_.NumRows();
    int32 num_bias_params = bias_params_.Dim();
    params->Range(0, num_linear_params).CopyRowsFromMat(linear_params_);
    params->Range(num_linear_params, num_bias_params).CopyFromVec(bias_params_);
  }
  
  void BlockAffineComponent::UnVectorize(const VectorBase<BaseFloat> &params) {
    KALDI_ASSERT(params.Dim() == this->NumParameters());
    int32 num_linear_params = linear_params_.NumCols() * linear_params_.NumRows();
    int32 num_bias_params = bias_params_.Dim();
    linear_params_.CopyRowsFromVec(params.Range(0, num_linear_params));
    bias_params_.CopyFromVec(params.Range(num_linear_params, num_bias_params));
  }
  
  void PerElementScaleComponent::Scale(BaseFloat scale) {
    if (scale == 0.0) {
      scales_.SetZero();
    } else {
      scales_.Scale(scale);
    }
  }
  
  void PerElementScaleComponent::Add(BaseFloat alpha,
                                     const Component &other_in) {
    const PerElementScaleComponent *other =
        dynamic_cast<const PerElementScaleComponent*>(&other_in);
    KALDI_ASSERT(other != NULL);
    scales_.AddVec(alpha, other->scales_);
  }
  
  PerElementScaleComponent::PerElementScaleComponent(
      const PerElementScaleComponent &component):
      UpdatableComponent(component),
      scales_(component.scales_) { }
  
  void PerElementScaleComponent::PerturbParams(BaseFloat stddev) {
    CuVector<BaseFloat> temp_scales(scales_.Dim(), kUndefined);
    temp_scales.SetRandn();
    scales_.AddVec(stddev, temp_scales);
  }
  
  std::string PerElementScaleComponent::Info() const {
    std::ostringstream stream;
    stream << UpdatableComponent::Info()
           << ", scales-min=" << scales_.Min()
           << ", scales-max=" << scales_.Max();
    PrintParameterStats(stream, "scales", scales_, true);
    return stream.str();
  }
  
  Component* PerElementScaleComponent::Copy() const {
    return new PerElementScaleComponent(*this);
  }
  
  BaseFloat PerElementScaleComponent::DotProduct(
      const UpdatableComponent &other_in) const {
    const PerElementScaleComponent *other =
        dynamic_cast<const PerElementScaleComponent*>(&other_in);
    return VecVec(scales_, other->scales_);
  }
  
  void PerElementScaleComponent::Init(int32 dim,
                                      BaseFloat param_mean,
                                      BaseFloat param_stddev) {
    KALDI_ASSERT(dim > 0 && param_stddev >= 0.0);
    scales_.Resize(dim);
    scales_.SetRandn();
    scales_.Scale(param_stddev);
    scales_.Add(param_mean);
  }
  
  void PerElementScaleComponent::Init(std::string vector_filename) {
    CuVector<BaseFloat> vec;
    ReadKaldiObject(vector_filename, &vec); // will abort on failure.
    scales_.Resize(vec.Dim());
    scales_.CopyFromVec(vec);
  }
  
  void PerElementScaleComponent::InitFromConfig(ConfigLine *cfl) {
    std::string vector_filename;
    int32 dim = -1;
    InitLearningRatesFromConfig(cfl);
    if (cfl->GetValue("vector", &vector_filename)) {
      Init(vector_filename);
      if (cfl->GetValue("dim", &dim))
        KALDI_ASSERT(dim == InputDim() &&
                     "input-dim mismatch vs. vector.");
    } else {
      if(!cfl->GetValue("dim", &dim))
        KALDI_ERR << "'dim' not provided in the config line.";
      BaseFloat param_mean = 1.0, param_stddev = 0.0;
      cfl->GetValue("param-mean", &param_mean);
      cfl->GetValue("param-stddev", &param_stddev);
      Init(dim, param_mean, param_stddev);
    }
    if (cfl->HasUnusedValues())
      KALDI_ERR << "Could not process these elements in initializer: "
                << cfl->UnusedValues();
  }
  
  void* PerElementScaleComponent::Propagate(
      const ComponentPrecomputedIndexes *indexes,
      const CuMatrixBase<BaseFloat> &in,
      CuMatrixBase<BaseFloat> *out) const {
    out->CopyFromMat(in);
    out->MulColsVec(scales_);
    return NULL;
  }
  
  void PerElementScaleComponent::UpdateSimple(
      const CuMatrixBase<BaseFloat> &in_value,
      const CuMatrixBase<BaseFloat> &out_deriv) {
    scales_.AddDiagMatMat(learning_rate_, out_deriv, kTrans,
                          in_value, kNoTrans, 1.0);
  }
  
  void PerElementScaleComponent::Backprop(
      const std::string &debug_info,
      const ComponentPrecomputedIndexes *indexes,
      const CuMatrixBase<BaseFloat> &in_value,
      const CuMatrixBase<BaseFloat> &, // out_value
      const CuMatrixBase<BaseFloat> &out_deriv,
      void *memo,
      Component *to_update_in,
      CuMatrixBase<BaseFloat> *in_deriv) const {
    PerElementScaleComponent *to_update =
        dynamic_cast<PerElementScaleComponent*>(to_update_in);
  
    if (to_update != NULL) {
      // Next update the model (must do this 2nd so the derivatives we propagate
      // are accurate, in case this == to_update_in.)
      if (to_update->is_gradient_)
        to_update->UpdateSimple(in_value, out_deriv);
      else  // the call below is to a virtual function that may be re-implemented
        to_update->Update(debug_info, in_value, out_deriv);  // by child classes.
    }
  
    if (in_deriv) {
      // Propagate the derivative back to the input.
      if (in_deriv->Data() != out_deriv.Data())
        in_deriv->CopyFromMat(out_deriv);
      in_deriv->MulColsVec(scales_);
    }
  }
  
  void PerElementScaleComponent::Read(std::istream &is, bool binary) {
    ReadUpdatableCommon(is, binary);  // Read opening tag and learning rate.
    ExpectToken(is, binary, "<Params>");
    scales_.Read(is, binary);
    if (PeekToken(is, binary) == 'I') {
      // for back compatibility; we don't write this here any
      // more as it's written and read in Write/ReadUpdatableCommon
      ExpectToken(is, binary, "<IsGradient>");
      ReadBasicType(is, binary, &is_gradient_);
    }
    ExpectToken(is, binary, "</PerElementScaleComponent>");
  }
  
  void PerElementScaleComponent::Write(std::ostream &os, bool binary) const {
    WriteUpdatableCommon(os, binary);  // Write opening tag and learning rate.
    WriteToken(os, binary, "<Params>");
    scales_.Write(os, binary);
    WriteToken(os, binary, "</PerElementScaleComponent>");
  }
  
  int32 PerElementScaleComponent::NumParameters() const {
    return InputDim();
  }
  
  void PerElementScaleComponent::Vectorize(VectorBase<BaseFloat> *params) const {
    params->CopyFromVec(scales_);
  }
  
  void PerElementScaleComponent::UnVectorize(
      const VectorBase<BaseFloat> &params) {
    scales_.CopyFromVec(params);
  }
  
  void PerElementOffsetComponent::Scale(BaseFloat scale) {
    if (scale == 0.0) {
      offsets_.SetZero();
    } else {
      offsets_.Scale(scale);
    }
  }
  
  
  void PerElementOffsetComponent::Add(BaseFloat alpha,
                                     const Component &other_in) {
    const PerElementOffsetComponent *other =
        dynamic_cast<const PerElementOffsetComponent*>(&other_in);
    KALDI_ASSERT(other != NULL);
    offsets_.AddVec(alpha, other->offsets_);
  }
  
  PerElementOffsetComponent::PerElementOffsetComponent(
      const PerElementOffsetComponent &component):
      UpdatableComponent(component),
      offsets_(component.offsets_),
      dim_(component.dim_),
      use_natural_gradient_(component.use_natural_gradient_),
      preconditioner_(component.preconditioner_) { }
  
  void PerElementOffsetComponent::PerturbParams(BaseFloat stddev) {
    CuVector<BaseFloat> temp_offsets(offsets_.Dim(), kUndefined);
    temp_offsets.SetRandn();
    offsets_.AddVec(stddev, temp_offsets);
  }
  
  std::string PerElementOffsetComponent::Info() const {
    std::ostringstream stream;
    stream << UpdatableComponent::Info()
           << ", offsets-min=" << offsets_.Min()
           << ", offsets-max=" << offsets_.Max()
           << ", block-dim=" << offsets_.Dim()
           << ", use-natural-gradient="
           << (use_natural_gradient_ ? "true" : "false");
    PrintParameterStats(stream, "offsets", offsets_, true);
    return stream.str();
  }
  
  Component* PerElementOffsetComponent::Copy() const {
    return new PerElementOffsetComponent(*this);
  }
  
  BaseFloat PerElementOffsetComponent::DotProduct(
      const UpdatableComponent &other_in) const {
    const PerElementOffsetComponent *other =
        dynamic_cast<const PerElementOffsetComponent*>(&other_in);
    return VecVec(offsets_, other->offsets_);
  }
  
  
  void PerElementOffsetComponent::InitFromConfig(ConfigLine *cfl) {
    std::string vector_filename;
    InitLearningRatesFromConfig(cfl);
    if (cfl->GetValue("vector", &vector_filename)) {
      ReadKaldiObject(vector_filename, &offsets_);
      dim_ = offsets_.Dim();  // if dim is not supplied, it defaults to this.
      cfl->GetValue("dim", &dim_);
      if (dim_ <= 0 || offsets_.Dim() % dim_ != 0)
        KALDI_ERR << "Invalid dimension dim=" << dim_;
    } else {
      if(!cfl->GetValue("dim", &dim_))
        KALDI_ERR << "'dim' not provided in the config line.";
      if (dim_ <= 0)
        KALDI_ERR << "Invalid dimension dim=" << dim_;
      BaseFloat param_mean = 0.0, param_stddev = 0.0;
      cfl->GetValue("param-mean", &param_mean);
      cfl->GetValue("param-stddev", &param_stddev);
      int32 block_dim = dim_;
      cfl->GetValue("block-dim", &block_dim);
      if (block_dim <= 0 || dim_ % block_dim !=  0)
        KALDI_ERR << "Invalid value block-dim=" << block_dim;
      offsets_.Resize(block_dim);
      offsets_.SetRandn();
      offsets_.Scale(param_stddev);
      offsets_.Add(param_mean);
    }
    use_natural_gradient_ = true;
    cfl->GetValue("use-natural-gradient", &use_natural_gradient_);
    if (cfl->HasUnusedValues())
      KALDI_ERR << "Could not process these elements in initializer: "
                << cfl->UnusedValues();
    // For now you can't modify these defaults of the natural gradient.
    // This code must be kept in sync with the code in Read().
    preconditioner_.SetRank(20);
    preconditioner_.SetUpdatePeriod(4);
  }
  
  void* PerElementOffsetComponent::Propagate(
      const ComponentPrecomputedIndexes *indexes,
      const CuMatrixBase<BaseFloat> &in,
      CuMatrixBase<BaseFloat> *out) const {
    if (in.Data() != out->Data())
      out->CopyFromMat(in);
    if (dim_ == offsets_.Dim()) {
      out->AddVecToRows(1.0, offsets_);
    } else {
      KALDI_ASSERT(out->Stride() == out->NumCols());
      int32 block_dim = offsets_.Dim(), multiple = dim_ / block_dim,
          num_rows = out->NumRows() * multiple;
      CuSubMatrix<BaseFloat> out_rearranged(out->Data(), num_rows,
                                            block_dim, block_dim);
      out_rearranged.AddVecToRows(1.0, offsets_);
    }
    return NULL;
  }
  
  void PerElementOffsetComponent::Backprop(
      const std::string &debug_info,
      const ComponentPrecomputedIndexes *indexes,
      const CuMatrixBase<BaseFloat> &, // in_value
      const CuMatrixBase<BaseFloat> &, // out_value
      const CuMatrixBase<BaseFloat> &out_deriv,
      void *memo,
      Component *to_update_in,
      CuMatrixBase<BaseFloat> *in_deriv) const {
    PerElementOffsetComponent *to_update =
        dynamic_cast<PerElementOffsetComponent*>(to_update_in);
  
    if (in_deriv && in_deriv->Data() != out_deriv.Data()) {
      // Propagate the derivative back to the input.
      in_deriv->CopyFromMat(out_deriv);
    }
  
    if (to_update != NULL) {
      // we may have to reshape out_deriv, if "block-dim" was set
      // in the config file when initializing the object, leading
      // to dim_ being a multiple >1 of offset_.Dim().
      // To avoid having separate code paths we create a sub-matrix
      // in any case, but this may just be a copy of out_deriv.
      int32 block_dim = offsets_.Dim(), multiple = dim_ / block_dim,
          block_stride = (multiple == 1 ? out_deriv.Stride() : block_dim),
          num_rows = out_deriv.NumRows() * multiple;
      KALDI_ASSERT(multiple == 1 || out_deriv.Stride() == out_deriv.NumCols());
      CuSubMatrix<BaseFloat> out_deriv_reshaped(out_deriv.Data(), num_rows,
                                                block_dim, block_stride);
      if (!to_update->use_natural_gradient_ || to_update->is_gradient_) {
        KALDI_LOG << "Using non-NG update, lr = " << to_update->learning_rate_;
        to_update->offsets_.AddRowSumMat(to_update->learning_rate_,
                                         out_deriv_reshaped);
      } else {
        KALDI_LOG << "Using NG update, lr = " << to_update->learning_rate_;
        // make a copy as we don't want to modify the data of 'out_deriv', which
        // was const (even though CuSubMatrix does not respect const-ness in
        // this scenario)
        CuMatrix<BaseFloat> out_deriv_copy(out_deriv_reshaped);
        BaseFloat scale = 1.0;
        to_update->preconditioner_.PreconditionDirections(&out_deriv_copy,
                                                          &scale);
        to_update->offsets_.AddRowSumMat(scale * to_update->learning_rate_,
                                         out_deriv_copy);
      }
    }
  }
  
  void PerElementOffsetComponent::Read(std::istream &is, bool binary) {
    ReadUpdatableCommon(is, binary);  // Read opening tag and learning rate
    ExpectToken(is, binary, "<Offsets>");
    offsets_.Read(is, binary);
    if (PeekToken(is, binary) == 'I') {
      // for back compatibility; we don't write this here any
      // more as it's written and read in Write/ReadUpdatableCommon
      ExpectToken(is, binary, "<IsGradient>");
      ReadBasicType(is, binary, &is_gradient_);
    }
    if (PeekToken(is, binary) != '/') {
      ExpectToken(is, binary, "<Dim>");
      ReadBasicType(is, binary, &dim_);
      ExpectToken(is, binary, "<UseNaturalGradient>");
      ReadBasicType(is, binary, &use_natural_gradient_);
    } else {
      dim_ = offsets_.Dim();
      use_natural_gradient_ = true;
    }
    // For now you can't modify these defaults of the natural gradient.
    // This code must be kept in sync with the code in InitFromConfig().
    preconditioner_.SetRank(20);
    preconditioner_.SetUpdatePeriod(4);
    ExpectToken(is, binary, "</PerElementOffsetComponent>");
  }
  
  void PerElementOffsetComponent::Write(std::ostream &os, bool binary) const {
    WriteUpdatableCommon(os, binary);  // Write opening tag and learning rate
    WriteToken(os, binary, "<Offsets>");
    offsets_.Write(os, binary);
    WriteToken(os, binary, "<Dim>");
    WriteBasicType(os, binary, dim_);
    WriteToken(os, binary, "<UseNaturalGradient>");
    WriteBasicType(os, binary, use_natural_gradient_);
    WriteToken(os, binary, "</PerElementOffsetComponent>");
  }
  
  int32 PerElementOffsetComponent::NumParameters() const {
    return offsets_.Dim();
  }
  
  void PerElementOffsetComponent::Vectorize(VectorBase<BaseFloat> *params) const {
    params->CopyFromVec(offsets_);
  }
  
  void PerElementOffsetComponent::UnVectorize(
      const VectorBase<BaseFloat> &params) {
    offsets_.CopyFromVec(params);
  }
  
  std::string ScaleAndOffsetComponent::Info() const {
    std::ostringstream stream;
    stream << UpdatableComponent::Info()
           << ", rank=" << scale_preconditioner_.GetRank();
    if (dim_ != scales_.Dim())
      stream << ", block-size=" << scales_.Dim();
    PrintParameterStats(stream, "scales", scales_, true);
    PrintParameterStats(stream, "offsets", offsets_, true);
    return stream.str();
  }
  
  void ScaleAndOffsetComponent::InitFromConfig(ConfigLine *cfl) {
  
    InitLearningRatesFromConfig(cfl);
    if (!cfl->GetValue("dim", &dim_) || dim_ <= 0) {
      KALDI_ERR << "Dimension 'dim' must be specified and >0: "
                << cfl->WholeLine();
    }
    use_natural_gradient_ = true;
    cfl->GetValue("use-natural-gradient", &use_natural_gradient_);
    int32 block_dim = dim_,
        rank = 20;
    cfl->GetValue("block-dim", &block_dim);
    if (block_dim <= 0 || dim_ % block_dim != 0) {
      KALDI_ERR << "Invalid block-dim: " << cfl->WholeLine();
    }
    cfl->GetValue("rank", &rank);
    scales_.Resize(block_dim);
    scales_.Set(1.0);
    offsets_.Resize(block_dim);
    // offsets are all zero when initialized.
    if (cfl->HasUnusedValues())
      KALDI_ERR << "Could not process these elements in initializer: "
                << cfl->UnusedValues();
    offset_preconditioner_.SetRank(rank);
    scale_preconditioner_.SetRank(rank);
    // the update period can't be configured for now; we'll add an option if we
    // want to.
    offset_preconditioner_.SetUpdatePeriod(4);
    scale_preconditioner_.SetUpdatePeriod(4);
  }
  
  void ScaleAndOffsetComponent::Read(std::istream &is, bool binary) {
    ReadUpdatableCommon(is, binary);  // Read opening tag and learning rate
    ExpectToken(is, binary, "<Dim>");
    ReadBasicType(is, binary, &dim_);
    ExpectToken(is, binary, "<Scales>");
    scales_.Read(is, binary);
    ExpectToken(is, binary, "<Offsets>");
    offsets_.Read(is, binary);
    ExpectToken(is, binary, "<UseNaturalGradient>");
    ReadBasicType(is, binary, &use_natural_gradient_);
    int32 rank;
    ExpectToken(is, binary, "<Rank>");
    ReadBasicType(is, binary, &rank);
    scale_preconditioner_.SetRank(rank);
    offset_preconditioner_.SetRank(rank);
    ExpectToken(is, binary, "</ScaleAndOffsetComponent>");
  }
  
  void ScaleAndOffsetComponent::Write(std::ostream &os, bool binary) const {
    WriteUpdatableCommon(os, binary);  // Write opening tag and learning rate
    WriteToken(os, binary, "<Dim>");
    WriteBasicType(os, binary, dim_);
    WriteToken(os, binary, "<Scales>");
    scales_.Write(os, binary);
    WriteToken(os, binary, "<Offsets>");
    offsets_.Write(os, binary);
    WriteToken(os, binary, "<UseNaturalGradient>");
    WriteBasicType(os, binary, use_natural_gradient_);
    WriteToken(os, binary, "<Rank>");
    WriteBasicType(os, binary, scale_preconditioner_.GetRank());
    WriteToken(os, binary, "</ScaleAndOffsetComponent>");
  }
  
  void ScaleAndOffsetComponent::Scale(BaseFloat scale) {
    if (scale == 0.0) {
      scales_.SetZero();
      offsets_.SetZero();
    } else {
      scales_.Scale(scale);
      offsets_.Scale(scale);
    }
  }
  
  void ScaleAndOffsetComponent::Add(BaseFloat alpha,
                                    const Component &other_in) {
    const ScaleAndOffsetComponent *other =
        dynamic_cast<const ScaleAndOffsetComponent*>(&other_in);
    KALDI_ASSERT(other != NULL);
    scales_.AddVec(alpha, other->scales_);
    offsets_.AddVec(alpha, other->offsets_);
  }
  
  ScaleAndOffsetComponent::ScaleAndOffsetComponent(
      const ScaleAndOffsetComponent &component):
      UpdatableComponent(component),
      dim_(component.dim_),
      scales_(component.scales_),
      offsets_(component.offsets_),
      use_natural_gradient_(component.use_natural_gradient_),
      scale_preconditioner_(component.scale_preconditioner_),
      offset_preconditioner_(component.offset_preconditioner_) { }
  
  void ScaleAndOffsetComponent::PerturbParams(BaseFloat stddev) {
    CuVector<BaseFloat> temp(scales_.Dim(), kUndefined);
    temp.SetRandn();
    scales_.AddVec(stddev, temp);
    temp.SetRandn();
    offsets_.AddVec(stddev, temp);
  }
  
  BaseFloat ScaleAndOffsetComponent::DotProduct(
      const UpdatableComponent &other_in) const {
    const ScaleAndOffsetComponent *other =
        dynamic_cast<const ScaleAndOffsetComponent*>(&other_in);
    return VecVec(other->scales_, scales_) + VecVec(other->offsets_, offsets_);
  }
  
  void ScaleAndOffsetComponent::Vectorize(VectorBase<BaseFloat> *params) const {
    int32 dim = scales_.Dim();
    params->Range(0, dim).CopyFromVec(scales_);
    params->Range(dim, dim).CopyFromVec(offsets_);
  }
  
  void ScaleAndOffsetComponent::UnVectorize(
      const VectorBase<BaseFloat> &params) {
    int32 dim = scales_.Dim();
    scales_.CopyFromVec(params.Range(0, dim));
    offsets_.CopyFromVec(params.Range(dim, dim));
  }
  
  void* ScaleAndOffsetComponent::Propagate(
      const ComponentPrecomputedIndexes *indexes,
      const CuMatrixBase<BaseFloat> &in,
      CuMatrixBase<BaseFloat> *out) const {
    if (dim_ == scales_.Dim()) {
      PropagateInternal(in, out);
    } else {
      int32 multiple = dim_ / scales_.Dim(),
          num_rows = in.NumRows(), block_dim = scales_.Dim();
      KALDI_ASSERT(in.NumCols() == in.Stride() &&
                   SameDimAndStride(in, *out));
      // Reinterpret the data as matrices with more rows but fewer columns.
      CuSubMatrix<BaseFloat> in_rearranged(in.Data(), num_rows * multiple,
                                           block_dim, block_dim),
          out_rearranged(out->Data(), num_rows * multiple,
                         block_dim, block_dim);
      PropagateInternal(in_rearranged, &out_rearranged);
    }
    return NULL;
  }
  
  void ScaleAndOffsetComponent::PropagateInternal(
      const CuMatrixBase<BaseFloat> &in,
      CuMatrixBase<BaseFloat> *out) const {
    if (out->Data() != in.Data())
      out->CopyFromMat(in);
    BaseFloat epsilon = Epsilon();
    int32 dim = scales_.Dim();
    CuVector<BaseFloat> scales_nonzero(dim, kUndefined);
    cu::EnsureNonzero(scales_, epsilon, &scales_nonzero);
    out->MulColsVec(scales_nonzero);
    out->AddVecToRows(1.0, offsets_);
  }
  
  void ScaleAndOffsetComponent::Backprop(
      const std::string &debug_info,
      const ComponentPrecomputedIndexes *indexes,
      const CuMatrixBase<BaseFloat> &, // in_value
      const CuMatrixBase<BaseFloat> &out_value,
      const CuMatrixBase<BaseFloat> &out_deriv,
      void *memo,
      Component *to_update_in,
      CuMatrixBase<BaseFloat> *in_deriv) const {
    ScaleAndOffsetComponent *to_update =
        dynamic_cast<ScaleAndOffsetComponent*>(to_update_in);
  
    KALDI_ASSERT(SameDim(out_value, out_deriv));
  
    if (dim_ == scales_.Dim()) {
      BackpropInternal(debug_info, out_value, out_deriv,
                       to_update, in_deriv);
    } else {
      KALDI_ASSERT(out_value.NumCols() == out_value.Stride() &&
                   SameDimAndStride(out_value, out_deriv) &&
                   (!in_deriv || SameDimAndStride(out_value, *in_deriv)));
      int32 multiple = dim_ / scales_.Dim(),
          num_rows = out_value.NumRows(),
          block_dim = scales_.Dim();
      CuSubMatrix<BaseFloat> out_value_rearranged(out_value.Data(),
                                                  num_rows * multiple,
                                                  block_dim, block_dim),
          out_deriv_rearranged(out_deriv.Data(), num_rows * multiple,
                               block_dim, block_dim);
      if (in_deriv) {
        CuSubMatrix<BaseFloat> in_deriv_rearranged(in_deriv->Data(),
                                                   num_rows * multiple,
                                                   block_dim, block_dim);
        BackpropInternal(debug_info, out_value_rearranged,
                         out_deriv_rearranged, to_update,
                         &in_deriv_rearranged);
      } else {
        BackpropInternal(debug_info, out_value_rearranged,
                         out_deriv_rearranged, to_update,
                         NULL);
      }
    }
  }
  
  
    // Internal version of backprop, where the num-cols of the
    // argument matrices are equal to scales_.Dim().
  void ScaleAndOffsetComponent::BackpropInternal(
      const std::string &debug_info,
      const CuMatrixBase<BaseFloat> &out_value,
      const CuMatrixBase<BaseFloat> &out_deriv,
      ScaleAndOffsetComponent *to_update,
      CuMatrixBase<BaseFloat> *in_deriv) const {
    if (to_update) {
      if (!to_update->use_natural_gradient_ || to_update->is_gradient_) {
        to_update->offsets_.AddRowSumMat(to_update->learning_rate_,
                                         out_deriv);
      } else {
        BaseFloat scale = 1.0;
        CuMatrix<BaseFloat> out_deriv_copy(out_deriv);
        to_update->offset_preconditioner_.PreconditionDirections(
            &out_deriv_copy, &scale);
        to_update->offsets_.AddRowSumMat(scale * to_update->learning_rate_,
                                         out_deriv_copy);
      }
      // The backprop actually needs the input to the component, not the output;
      // but we make the output available because in the common topologies that
      // will already be required for backprop-- it's for memory efficiency.
      CuMatrix<BaseFloat> in_value_reconstructed(out_value);
      int32 dim = scales_.Dim();
      CuVector<BaseFloat> scales_nonzero(dim, kUndefined);
      BaseFloat epsilon = Epsilon();
      cu::EnsureNonzero(scales_, epsilon, &scales_nonzero);
      scales_nonzero.InvertElements();
      in_value_reconstructed.AddVecToRows(-1.0, offsets_);
      // Actually scales_nonzero are now the inverses of the scales.
      in_value_reconstructed.MulColsVec(scales_nonzero);
      // OK, at this point in_value_reconstructed is the input to the component.
      // Multiply its elements by 'out_deriv' to get the derivatives
      // (for each frame) w.r.t. the scales.
      in_value_reconstructed.MulElements(out_deriv);
      BaseFloat scale = 1.0;
      if (to_update->use_natural_gradient_ && !to_update->is_gradient_) {
        to_update->scale_preconditioner_.PreconditionDirections(
            &in_value_reconstructed, &scale);
      }
      to_update->scales_.AddRowSumMat(scale * to_update->learning_rate_,
                                      in_value_reconstructed);
    }
    if (in_deriv) {
      if (in_deriv->Data() != out_deriv.Data())
        in_deriv->CopyFromMat(out_deriv);
      in_deriv->MulColsVec(scales_);
    }
  }
  
  void ScaleAndOffsetComponent::ConsolidateMemory() {
    OnlineNaturalGradient temp_scale(scale_preconditioner_);
    scale_preconditioner_.Swap(&temp_scale);
    OnlineNaturalGradient temp_offset(offset_preconditioner_);
    offset_preconditioner_.Swap(&temp_offset);
  }
  
  
  std::string ConstantFunctionComponent::Info() const {
    std::ostringstream stream;
    stream << UpdatableComponent::Info()
           << ", " << Type() << ", input-dim=" << InputDim()
           << ", output-dim=" << OutputDim()
           << ", is-updatable=" << std::boolalpha << is_updatable_
           << ", use-natural-gradient=" << std::boolalpha
           << use_natural_gradient_;
    PrintParameterStats(stream, "output", output_, true);
    return stream.str();
  }
  
  ConstantFunctionComponent::ConstantFunctionComponent():
      UpdatableComponent(), input_dim_(-1), is_updatable_(true),
      use_natural_gradient_(true) { }
  
  ConstantFunctionComponent::ConstantFunctionComponent(
      const ConstantFunctionComponent &other):
      UpdatableComponent(other), input_dim_(other.input_dim_),
      output_(other.output_), is_updatable_(other.is_updatable_),
      use_natural_gradient_(other.use_natural_gradient_),
      preconditioner_(other.preconditioner_) { }
  
  void* ConstantFunctionComponent::Propagate(
      const ComponentPrecomputedIndexes *indexes,
      const CuMatrixBase<BaseFloat> &in,
      CuMatrixBase<BaseFloat> *out) const {
    out->CopyRowsFromVec(output_);
    return NULL;
  }
  
  void ConstantFunctionComponent::Backprop(
      const std::string &debug_info,
      const ComponentPrecomputedIndexes *indexes,
      const CuMatrixBase<BaseFloat> &, // in_value
      const CuMatrixBase<BaseFloat> &, // out_value
      const CuMatrixBase<BaseFloat> &out_deriv,
      void *memo,
      Component *to_update_in,
      CuMatrixBase<BaseFloat> *in_deriv) const {
    // we don't update in_deriv, since we set the flag
    // kBackpropAdds, and the output doesn't depend on the
    // input, so the input-derivative is zero.
    if (to_update_in) {
      ConstantFunctionComponent *to_update =
        dynamic_cast<ConstantFunctionComponent*>(to_update_in);
      if (to_update->is_updatable_) {
        // only do the update if the is_updatable_ flag is set.
        KALDI_ASSERT(to_update && to_update->is_updatable_);
        if (to_update->use_natural_gradient_ && !to_update->is_gradient_) {
          CuMatrix<BaseFloat> out_deriv_copy(out_deriv);
          BaseFloat scale = 1.0;
          to_update->preconditioner_.PreconditionDirections(&out_deriv_copy,
                                                            &scale);
          to_update->output_.AddRowSumMat(scale * to_update->learning_rate_,
                                          out_deriv_copy);
        } else {
          to_update->output_.AddRowSumMat(to_update->learning_rate_,
                                          out_deriv);
        }
      }
    }
  }
  
  void ConstantFunctionComponent::Read(std::istream &is, bool binary) {
    std::string token;
    ReadToken(is, binary, &token);
    if (token == "<ConstantFunctionComponent>") {
      ReadToken(is, binary, &token);
    }
    if (token == "<LearningRateFactor>") {
      ReadBasicType(is, binary, &learning_rate_factor_);
      ReadToken(is, binary, &token);
    } else {
      learning_rate_factor_ = 1.0;
    }
    if (token == "<IsGradient>") {
      ReadBasicType(is, binary, &is_gradient_);
      ReadToken(is, binary, &token);
    } else {
      is_gradient_ = false;
    }
    if (token == "<LearningRate>") {
      ReadBasicType(is, binary, &learning_rate_);
      ReadToken(is, binary, &token);
    } else {
      learning_rate_ = 0.001;
    }
    if (token == "<InputDim>") {
      ReadBasicType(is, binary, &input_dim_);
    } else {
      KALDI_ERR << "Expected token <InputDim>, got "
                << token;
    }
    ExpectToken(is, binary, "<Output>");
    output_.Read(is, binary);
    ExpectToken(is, binary, "<IsUpdatable>");
    ReadBasicType(is, binary, &is_updatable_);
    ExpectToken(is, binary, "<UseNaturalGradient>");
    ReadBasicType(is, binary, &use_natural_gradient_);
    ExpectToken(is, binary, "</ConstantFunctionComponent>");
  }
  
  void ConstantFunctionComponent::Write(std::ostream &os, bool binary) const {
    WriteUpdatableCommon(os, binary);  // Write the opening tag and learning rate
    WriteToken(os, binary, "<InputDim>");
    WriteBasicType(os, binary, input_dim_);
    WriteToken(os, binary, "<Output>");
    output_.Write(os, binary);
    WriteToken(os, binary, "<IsUpdatable>");
    WriteBasicType(os, binary, is_updatable_);
    WriteToken(os, binary, "<UseNaturalGradient>");
    WriteBasicType(os, binary, use_natural_gradient_);
    WriteToken(os, binary, "</ConstantFunctionComponent>");
  }
  
  Component* ConstantFunctionComponent::Copy() const {
    return new ConstantFunctionComponent(*this);
  }
  
  void ConstantFunctionComponent::Scale(BaseFloat scale) {
    if (is_updatable_) {
      if (scale == 0.0) {
        output_.SetZero();
      } else {
        output_.Scale(scale);
      }
    }
  }
  
  void ConstantFunctionComponent::Add(BaseFloat alpha, const Component &other_in) {
    if (is_updatable_) {
      const ConstantFunctionComponent *other =
          dynamic_cast<const ConstantFunctionComponent*>(&other_in);
      KALDI_ASSERT(other != NULL);
      output_.AddVec(alpha, other->output_);
    }
  }
  
  void ConstantFunctionComponent::PerturbParams(BaseFloat stddev) {
    CuVector<BaseFloat> temp_output(output_.Dim(), kUndefined);
    temp_output.SetRandn();
    output_.AddVec(stddev, temp_output);
  }
  
  BaseFloat ConstantFunctionComponent::DotProduct(
      const UpdatableComponent &other_in) const {
    KALDI_ASSERT(is_updatable_);
    const ConstantFunctionComponent *other =
        dynamic_cast<const ConstantFunctionComponent*>(&other_in);
    KALDI_ASSERT(other != NULL);
    return VecVec(output_, other->output_);
  }
  
  void ConstantFunctionComponent::InitFromConfig(ConfigLine *cfl) {
    int32 output_dim = 0;
    InitLearningRatesFromConfig(cfl);
    bool ok = cfl->GetValue("output-dim", &output_dim) &&
        cfl->GetValue("input-dim", &input_dim_);
    cfl->GetValue("is-updatable", &is_updatable_);
    cfl->GetValue("use-natural-gradient", &use_natural_gradient_);
    BaseFloat output_mean = 0.0, output_stddev = 0.0;
    cfl->GetValue("output-mean", &output_mean);
    cfl->GetValue("output-stddev", &output_stddev);
    if (!ok || cfl->HasUnusedValues() || input_dim_ <= 0 ||
        output_dim <= 0) {
      KALDI_ERR << "Bad initializer " << cfl->WholeLine();
    }
    Vector<BaseFloat> output(output_dim);
    output.SetRandn();
    output.Scale(output_stddev);
    output.Add(output_mean);
    output_ = output;
  }
  
  int32 ConstantFunctionComponent::NumParameters() const {
    KALDI_ASSERT(is_updatable_);
    return output_.Dim();
  }
  
  void ConstantFunctionComponent::Vectorize(VectorBase<BaseFloat> *params) const {
    params->CopyFromVec(output_);
  }
  
  void ConstantFunctionComponent::UnVectorize(const VectorBase<BaseFloat> &params) {
    output_.CopyFromVec(params);
  }
  
  void ConstantFunctionComponent::ConsolidateMemory() {
    OnlineNaturalGradient temp(preconditioner_);
    preconditioner_.Swap(&temp);
  }
  
  void NaturalGradientAffineComponent::Read(std::istream &is, bool binary) {
    ReadUpdatableCommon(is, binary);  // Read the opening tag and learning rate
    ExpectToken(is, binary, "<LinearParams>");
    linear_params_.Read(is, binary);
    ExpectToken(is, binary, "<BiasParams>");
    bias_params_.Read(is, binary);
  
    BaseFloat num_samples_history, alpha;
    int32 rank_in, rank_out, update_period;
  
    ExpectToken(is, binary, "<RankIn>");
    ReadBasicType(is, binary, &rank_in);
    ExpectToken(is, binary, "<RankOut>");
    ReadBasicType(is, binary, &rank_out);
    if (PeekToken(is, binary) == 'O') {
      ExpectToken(is, binary, "<OrthonormalConstraint>");
      ReadBasicType(is, binary, &orthonormal_constraint_);
    } else {
      orthonormal_constraint_ = 0.0;
    }
    ExpectToken(is, binary, "<UpdatePeriod>");
    ReadBasicType(is, binary, &update_period);
    ExpectToken(is, binary, "<NumSamplesHistory>");
    ReadBasicType(is, binary, &num_samples_history);
    ExpectToken(is, binary, "<Alpha>");
    ReadBasicType(is, binary, &alpha);
  
    preconditioner_in_.SetNumSamplesHistory(num_samples_history);
    preconditioner_out_.SetNumSamplesHistory(num_samples_history);
    preconditioner_in_.SetAlpha(alpha);
    preconditioner_out_.SetAlpha(alpha);
    preconditioner_in_.SetRank(rank_in);
    preconditioner_out_.SetRank(rank_out);
    preconditioner_in_.SetUpdatePeriod(update_period);
    preconditioner_out_.SetUpdatePeriod(update_period);
  
    if (PeekToken(is, binary) == 'M') {
      // MaxChangePerSample, long ago removed; back compatibility.
      ExpectToken(is, binary, "<MaxChangePerSample>");
      BaseFloat temp;
      ReadBasicType(is, binary, &temp);
    }
    if (PeekToken(is, binary) == 'I') {
      // for back compatibility; we don't write this here any
      // more as it's written and read in Write/ReadUpdatableCommon
      ExpectToken(is, binary, "<IsGradient>");
      ReadBasicType(is, binary, &is_gradient_);
    }
    if (PeekToken(is, binary) == 'U') {
      ExpectToken(is, binary, "<UpdateCount>");
      // back-compatibility branch (these configs were added and then removed).
      double temp;
      ReadBasicType(is, binary, &temp);
      ExpectToken(is, binary, "<ActiveScalingCount>");
      ReadBasicType(is, binary, &temp);
      ExpectToken(is, binary, "<MaxChangeScaleStats>");
      ReadBasicType(is, binary, &temp);
    }
    std::string token;
    ReadToken(is, binary, &token);
    // the following has to handle a couple variants of
    if (token.find("NaturalGradientAffineComponent>") == std::string::npos)
      KALDI_ERR << "Expected <NaturalGradientAffineComponent> or "
                << "</NaturalGradientAffineComponent>, got " << token;
  }
  
  
  NaturalGradientAffineComponent::NaturalGradientAffineComponent(
      const CuMatrixBase<BaseFloat> &linear_params,
      const CuVectorBase<BaseFloat> &bias_params):
      AffineComponent(linear_params, bias_params, 0.001) {
    KALDI_ASSERT(bias_params.Dim() == linear_params.NumRows() &&
                 bias_params.Dim() != 0);
  
    // set some default natural gradient configs.
    preconditioner_in_.SetRank(20);
    preconditioner_out_.SetRank(80);
    preconditioner_in_.SetUpdatePeriod(4);
    preconditioner_out_.SetUpdatePeriod(4);
  }
  
  void NaturalGradientAffineComponent::InitFromConfig(ConfigLine *cfl) {
    bool ok = true;
    std::string matrix_filename;
  
    is_gradient_ = false;  // not configurable; there's no reason you'd want this
  
    InitLearningRatesFromConfig(cfl);
  
    if (cfl->GetValue("matrix", &matrix_filename)) {
      CuMatrix<BaseFloat> mat;
      ReadKaldiObject(matrix_filename, &mat); // will abort on failure.
      KALDI_ASSERT(mat.NumCols() >= 2);
      int32 input_dim = mat.NumCols() - 1, output_dim = mat.NumRows();
      linear_params_.Resize(output_dim, input_dim);
      bias_params_.Resize(output_dim);
      linear_params_.CopyFromMat(mat.Range(0, output_dim, 0, input_dim));
      bias_params_.CopyColFromMat(mat, input_dim);
      if (cfl->GetValue("input-dim", &input_dim))
        KALDI_ASSERT(input_dim == InputDim() &&
                     "input-dim mismatch vs. matrix.");
      if (cfl->GetValue("output-dim", &output_dim))
        KALDI_ASSERT(output_dim == OutputDim() &&
                     "output-dim mismatch vs. matrix.");
    } else {
      int32 input_dim = -1, output_dim = -1;
  
      ok = ok && cfl->GetValue("input-dim", &input_dim);
      ok = ok && cfl->GetValue("output-dim", &output_dim);
      if (!ok)
        KALDI_ERR << "Bad initializer " << cfl->WholeLine();
      BaseFloat param_stddev = 1.0 / std::sqrt(input_dim),
          bias_stddev = 1.0, bias_mean = 0.0;
      cfl->GetValue("param-stddev", &param_stddev);
      cfl->GetValue("bias-stddev", &bias_stddev);
      cfl->GetValue("bias-mean", &bias_mean);
      linear_params_.Resize(output_dim, input_dim);
      bias_params_.Resize(output_dim);
      KALDI_ASSERT(output_dim > 0 && input_dim > 0 && param_stddev >= 0.0 &&
                   bias_stddev >= 0.0);
      linear_params_.SetRandn(); // sets to random normally distributed noise.
      linear_params_.Scale(param_stddev);
      bias_params_.SetRandn();
      bias_params_.Scale(bias_stddev);
      bias_params_.Add(bias_mean);
    }
  
    orthonormal_constraint_ = 0.0;
    cfl->GetValue("orthonormal-constraint", &orthonormal_constraint_);
  
    // Set natural-gradient configs.
    BaseFloat num_samples_history = 2000.0,
        alpha = 4.0;
    int32 rank_in = -1, rank_out = -1,
        update_period = 4;
    cfl->GetValue("num-samples-history", &num_samples_history);
    cfl->GetValue("alpha", &alpha);
    cfl->GetValue("rank-in", &rank_in);
    cfl->GetValue("rank-out", &rank_out);
    cfl->GetValue("update-period", &update_period);
  
    if (rank_in < 0)
      rank_in = std::min<int32>(20, (InputDim() + 1) / 2);
    if (rank_out < 0)
      rank_out = std::min<int32>(80, (OutputDim() + 1) / 2);
  
    preconditioner_in_.SetNumSamplesHistory(num_samples_history);
    preconditioner_out_.SetNumSamplesHistory(num_samples_history);
    preconditioner_in_.SetAlpha(alpha);
    preconditioner_out_.SetAlpha(alpha);
    preconditioner_in_.SetRank(rank_in);
    preconditioner_out_.SetRank(rank_out);
    preconditioner_in_.SetUpdatePeriod(update_period);
    preconditioner_out_.SetUpdatePeriod(update_period);
  
    if (cfl->HasUnusedValues())
      KALDI_ERR << "Could not process these elements in initializer: "
                << cfl->UnusedValues();
    if (!ok)
      KALDI_ERR << "Bad initializer " << cfl->WholeLine();
  }
  
  void NaturalGradientAffineComponent::Write(std::ostream &os,
                                             bool binary) const {
    WriteUpdatableCommon(os, binary);  // Write the opening tag and learning rate
    WriteToken(os, binary, "<LinearParams>");
    linear_params_.Write(os, binary);
    WriteToken(os, binary, "<BiasParams>");
    bias_params_.Write(os, binary);
    WriteToken(os, binary, "<RankIn>");
    WriteBasicType(os, binary, preconditioner_in_.GetRank());
    WriteToken(os, binary, "<RankOut>");
    WriteBasicType(os, binary, preconditioner_out_.GetRank());
    if (orthonormal_constraint_ != 0.0) {
      WriteToken(os, binary, "<OrthonormalConstraint>");
      WriteBasicType(os, binary, orthonormal_constraint_);
    }
    WriteToken(os, binary, "<UpdatePeriod>");
    WriteBasicType(os, binary, preconditioner_in_.GetUpdatePeriod());
    WriteToken(os, binary, "<NumSamplesHistory>");
    WriteBasicType(os, binary, preconditioner_in_.GetNumSamplesHistory());
    WriteToken(os, binary, "<Alpha>");
    WriteBasicType(os, binary, preconditioner_in_.GetAlpha());
    WriteToken(os, binary, "</NaturalGradientAffineComponent>");
  }
  
  std::string NaturalGradientAffineComponent::Info() const {
    std::ostringstream stream;
    stream << AffineComponent::Info();
    stream << ", rank-in=" << preconditioner_in_.GetRank()
           << ", rank-out=" << preconditioner_out_.GetRank()
           << ", num-samples-history=" << preconditioner_in_.GetNumSamplesHistory()
           << ", update-period=" << preconditioner_in_.GetUpdatePeriod()
           << ", alpha=" << preconditioner_in_.GetAlpha();
    return stream.str();
  }
  
  Component* NaturalGradientAffineComponent::Copy() const {
    return new NaturalGradientAffineComponent(*this);
  }
  
  NaturalGradientAffineComponent::NaturalGradientAffineComponent(
      const NaturalGradientAffineComponent &other):
      AffineComponent(other),
      preconditioner_in_(other.preconditioner_in_),
      preconditioner_out_(other.preconditioner_out_) { }
  
  void NaturalGradientAffineComponent::Update(
      const std::string &debug_info,
      const CuMatrixBase<BaseFloat> &in_value,
      const CuMatrixBase<BaseFloat> &out_deriv) {
    CuMatrix<BaseFloat> in_value_temp;
  
    in_value_temp.Resize(in_value.NumRows(),
                         in_value.NumCols() + 1, kUndefined);
    in_value_temp.Range(0, in_value.NumRows(),
                        0, in_value.NumCols()).CopyFromMat(in_value);
  
    // Add the 1.0 at the end of each row "in_value_temp"
    in_value_temp.Range(0, in_value.NumRows(),
                        in_value.NumCols(), 1).Set(1.0);
  
    CuMatrix<BaseFloat> out_deriv_temp(out_deriv);
  
    // These "scale" values get will get multiplied into the learning rate (faster
    // than having the matrices scaled inside the preconditioning code).
    BaseFloat in_scale, out_scale;
  
    preconditioner_in_.PreconditionDirections(&in_value_temp, &in_scale);
    preconditioner_out_.PreconditionDirections(&out_deriv_temp, &out_scale);
  
    // "scale" is a scaling factor coming from the PreconditionDirections calls
    // (it's faster to have them output a scaling factor than to have them scale
    // their outputs).
    BaseFloat scale = in_scale * out_scale;
  
    CuSubMatrix<BaseFloat> in_value_precon_part(in_value_temp,
                                                0, in_value_temp.NumRows(),
                                                0, in_value_temp.NumCols() - 1);
    // this "precon_ones" is what happens to the vector of 1's representing
    // offsets, after multiplication by the preconditioner.
    CuVector<BaseFloat> precon_ones(in_value_temp.NumRows());
  
    precon_ones.CopyColFromMat(in_value_temp, in_value_temp.NumCols() - 1);
  
    BaseFloat local_lrate = scale * learning_rate_;
  
    bias_params_.AddMatVec(local_lrate, out_deriv_temp, kTrans,
                           precon_ones, 1.0);
    linear_params_.AddMatMat(local_lrate, out_deriv_temp, kTrans,
                             in_value_precon_part, kNoTrans, 1.0);
  }
  
  void NaturalGradientAffineComponent::Scale(BaseFloat scale) {
    if (scale == 0.0) {
      linear_params_.SetZero();
      bias_params_.SetZero();
    } else {
      linear_params_.Scale(scale);
      bias_params_.Scale(scale);
    }
  }
  
  void NaturalGradientAffineComponent::Add(BaseFloat alpha, const Component &other_in) {
    const NaturalGradientAffineComponent *other =
        dynamic_cast<const NaturalGradientAffineComponent*>(&other_in);
    KALDI_ASSERT(other != NULL);
    linear_params_.AddMat(alpha, other->linear_params_);
    bias_params_.AddVec(alpha, other->bias_params_);
  }
  
  void NaturalGradientAffineComponent::FreezeNaturalGradient(bool freeze) {
    preconditioner_in_.Freeze(freeze);
    preconditioner_out_.Freeze(freeze);
  }
  
  void NaturalGradientAffineComponent::ConsolidateMemory() {
    OnlineNaturalGradient temp_in(preconditioner_in_);
    preconditioner_in_.Swap(&temp_in);
    OnlineNaturalGradient temp_out(preconditioner_out_);
    preconditioner_out_.Swap(&temp_out);
  }
  
  void LinearComponent::Read(std::istream &is, bool binary) {
    std::string token = ReadUpdatableCommon(is, binary);
    KALDI_ASSERT(token == "");
    ExpectToken(is, binary, "<Params>");
    params_.Read(is, binary);
    if (PeekToken(is, binary) == 'O') {
      ExpectToken(is, binary, "<OrthonormalConstraint>");
      ReadBasicType(is, binary, &orthonormal_constraint_);
    } else {
      orthonormal_constraint_ = 0.0;
    }
    ExpectToken(is, binary, "<UseNaturalGradient>");
    ReadBasicType(is, binary, &use_natural_gradient_);
  
    // Read various natural-gradient-related configs.
    int32 rank_in,  rank_out, update_period;
    BaseFloat alpha, num_samples_history;
    ExpectToken(is, binary, "<RankInOut>");
    ReadBasicType(is, binary, &rank_in);
    ReadBasicType(is, binary, &rank_out);
    ExpectToken(is, binary, "<Alpha>");
    ReadBasicType(is, binary, &alpha);
    ExpectToken(is, binary, "<NumSamplesHistory>");
    ReadBasicType(is, binary, &num_samples_history);
    ExpectToken(is, binary, "<UpdatePeriod>");
    ReadBasicType(is, binary, &update_period);
  
    preconditioner_in_.SetAlpha(alpha);
    preconditioner_out_.SetAlpha(alpha);
    preconditioner_in_.SetRank(rank_in);
    preconditioner_out_.SetRank(rank_out);
    preconditioner_in_.SetNumSamplesHistory(num_samples_history);
    preconditioner_out_.SetNumSamplesHistory(num_samples_history);
    preconditioner_in_.SetUpdatePeriod(update_period);
    preconditioner_out_.SetUpdatePeriod(update_period);
  
    ExpectToken(is, binary, "</LinearComponent>");
  }
  
  void LinearComponent::InitFromConfig(ConfigLine *cfl) {
    bool ok = true;
    std::string matrix_filename;
    is_gradient_ = false;  // not configurable; there's no reason you'd want this
  
    InitLearningRatesFromConfig(cfl);
  
    int32 input_dim = -1, output_dim = -1;
    if (cfl->GetValue("matrix", &matrix_filename)) {
      ReadKaldiObject(matrix_filename, &params_); // will abort on failure.
      KALDI_ASSERT(params_.NumRows() != 0);
      if (cfl->GetValue("input-dim", &input_dim))
        KALDI_ASSERT(input_dim == InputDim() &&
                     "input-dim mismatch vs. matrix.");
      if (cfl->GetValue("output-dim", &output_dim))
        KALDI_ASSERT(output_dim == OutputDim() &&
                     "output-dim mismatch vs. matrix.");
    } else {
      ok = ok && cfl->GetValue("input-dim", &input_dim);
      ok = ok && cfl->GetValue("output-dim", &output_dim);
      if (!ok)
        KALDI_ERR << "Bad initializer " << cfl->WholeLine();
      BaseFloat param_stddev = 1.0 / std::sqrt(input_dim);
      cfl->GetValue("param-stddev", &param_stddev);
      params_.Resize(output_dim, input_dim);
      KALDI_ASSERT(output_dim > 0 && input_dim > 0 && param_stddev >= 0.0);
      params_.SetRandn(); // sets to random normally distributed noise.
      params_.Scale(param_stddev);
    }
    // Read various natural-gradient-related configs.
    int32 rank_in = -1, rank_out = -1, update_period = 4;
    BaseFloat alpha = 4.0,
        num_samples_history = 2000.0;
  
    use_natural_gradient_ = true;
  
    cfl->GetValue("num-samples-history", &num_samples_history);
    cfl->GetValue("alpha", &alpha);
    cfl->GetValue("rank-in", &rank_in);
    cfl->GetValue("rank-out", &rank_out);
    cfl->GetValue("update-period", &update_period);
    cfl->GetValue("use-natural-gradient", &use_natural_gradient_);
  
    if (rank_in < 0)
      rank_in = std::min<int32>(20, (InputDim() + 1) / 2);
    if (rank_out < 0)
      rank_out = std::min<int32>(80, (OutputDim() + 1) / 2);
  
    preconditioner_in_.SetAlpha(alpha);
    preconditioner_out_.SetAlpha(alpha);
    preconditioner_in_.SetRank(rank_in);
    preconditioner_out_.SetRank(rank_out);
    preconditioner_in_.SetNumSamplesHistory(num_samples_history);
    preconditioner_out_.SetNumSamplesHistory(num_samples_history);
    preconditioner_in_.SetUpdatePeriod(update_period);
    preconditioner_out_.SetUpdatePeriod(update_period);
  
    orthonormal_constraint_ = 0.0;
    cfl->GetValue("orthonormal-constraint", &orthonormal_constraint_);
  
    if (cfl->HasUnusedValues())
      KALDI_ERR << "Could not process these elements in initializer: "
                << cfl->UnusedValues();
  }
  
  
  void LinearComponent::Write(std::ostream &os,
                              bool binary) const {
    WriteUpdatableCommon(os, binary);  // Write the opening tag and learning rate
    WriteToken(os, binary, "<Params>");
    params_.Write(os, binary);
    if (orthonormal_constraint_ != 0.0) {
      WriteToken(os, binary, "<OrthonormalConstraint>");
      WriteBasicType(os, binary, orthonormal_constraint_);
    }
    WriteToken(os, binary, "<UseNaturalGradient>");
    WriteBasicType(os, binary, use_natural_gradient_);
  
    int32 rank_in = preconditioner_in_.GetRank(),
        rank_out = preconditioner_out_.GetRank(),
        update_period = preconditioner_in_.GetUpdatePeriod();
    BaseFloat alpha = preconditioner_in_.GetAlpha(),
        num_samples_history = preconditioner_in_.GetNumSamplesHistory();
    WriteToken(os, binary, "<RankInOut>");
    WriteBasicType(os, binary, rank_in);
    WriteBasicType(os, binary, rank_out);
    WriteToken(os, binary, "<Alpha>");
    WriteBasicType(os, binary, alpha);
    WriteToken(os, binary, "<NumSamplesHistory>");
    WriteBasicType(os, binary, num_samples_history);
    WriteToken(os, binary, "<UpdatePeriod>");
    WriteBasicType(os, binary, update_period);
    WriteToken(os, binary, "</LinearComponent>");
  }
  
  std::string LinearComponent::Info() const {
    std::ostringstream stream;
    stream << UpdatableComponent::Info();
    PrintParameterStats(stream, "params", params_,
                        false, // include_mean
                        true, // include_row_norms
                        true, // include_column_norms
                        GetVerboseLevel() >= 2); // include_singular_values
    if (orthonormal_constraint_ != 0.0)
      stream << ", orthonormal-constraint=" << orthonormal_constraint_;
    stream << ", use-natural-gradient="
           << (use_natural_gradient_ ? "true" : "false")
           << ", rank-in=" << preconditioner_in_.GetRank()
           << ", rank-out=" << preconditioner_out_.GetRank()
           << ", num-samples-history="
           << preconditioner_in_.GetNumSamplesHistory()
           << ", update-period=" << preconditioner_in_.GetUpdatePeriod()
           << ", alpha=" << preconditioner_in_.GetAlpha();
    return stream.str();
  }
  
  void* LinearComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
                                   const CuMatrixBase<BaseFloat> &in,
                                   CuMatrixBase<BaseFloat> *out) const {
    out->AddMatMat(1.0, in, kNoTrans, params_, kTrans, 1.0);
    return NULL;
  }
  
  void LinearComponent::Backprop(const std::string &debug_info,
                                 const ComponentPrecomputedIndexes *indexes,
                                 const CuMatrixBase<BaseFloat> &in_value,
                                 const CuMatrixBase<BaseFloat> &, // out_value
                                 const CuMatrixBase<BaseFloat> &out_deriv,
                                 void *memo,
                                 Component *to_update_in,
                                 CuMatrixBase<BaseFloat> *in_deriv) const {
    LinearComponent *to_update = dynamic_cast<LinearComponent*>(to_update_in);
  
    // Propagate the derivative back to the input.  add with coefficient 1.0 since
    // property kBackpropAdds is true.  If we wanted to add with coefficient 0.0
    // we'd need to zero the in_deriv, in case of infinities.
    if (in_deriv)
      in_deriv->AddMatMat(1.0, out_deriv, kNoTrans, params_, kNoTrans, 1.0);
  
    if (to_update != NULL) {
      if (!to_update->is_gradient_) {
        CuMatrix<BaseFloat> in_value_temp(in_value), out_deriv_temp(out_deriv);
        // These "scale" values get will get multiplied into the learning rate (faster
        // than having the matrices scaled inside the preconditioning code).
        BaseFloat in_scale, out_scale;
        to_update->preconditioner_in_.PreconditionDirections(&in_value_temp,
                                                             &in_scale);
        to_update->preconditioner_out_.PreconditionDirections(&out_deriv_temp,
                                                              &out_scale);
        BaseFloat local_lrate = in_scale * out_scale * to_update->learning_rate_;
  
        to_update->params_.AddMatMat(local_lrate, out_deriv_temp, kTrans,
                                     in_value_temp, kNoTrans, 1.0);
      } else {
        to_update->params_.AddMatMat(to_update->learning_rate_,
                                     out_deriv, kTrans,
                                     in_value, kNoTrans, 1.0);
      }
    }
  }
  
  
  Component* LinearComponent::Copy() const {
    return new LinearComponent(*this);
  }
  
  LinearComponent::LinearComponent(
      const LinearComponent &other):
      UpdatableComponent(other),
      params_(other.params_),
      orthonormal_constraint_(other.orthonormal_constraint_),
      use_natural_gradient_(other.use_natural_gradient_),
      preconditioner_in_(other.preconditioner_in_),
      preconditioner_out_(other.preconditioner_out_) { }
  
  LinearComponent::LinearComponent(const CuMatrix<BaseFloat> &params):
      params_(params),
      orthonormal_constraint_(0.0),
      use_natural_gradient_(true) {
    // Set defaults for natural gradient.
    preconditioner_in_.SetRank(40);
    preconditioner_out_.SetRank(80);
    preconditioner_in_.SetUpdatePeriod(4);
    preconditioner_out_.SetUpdatePeriod(4);
    // the component-level defaults of alpha and num_samples_history, at 4.0 and
    // 2000.0, are the same as in the NaturalGradientOnline code, so there is no
    // need to set those here.
  }
  
  void LinearComponent::Scale(BaseFloat scale) {
    if (scale == 0.0) params_.SetZero();
    else params_.Scale(scale);
  }
  
  void LinearComponent::Add(BaseFloat alpha, const Component &other_in) {
    const LinearComponent *other =
        dynamic_cast<const LinearComponent*>(&other_in);
    KALDI_ASSERT(other != NULL);
    params_.AddMat(alpha, other->params_);
  }
  
  void LinearComponent::PerturbParams(BaseFloat stddev) {
    CuMatrix<BaseFloat> temp_params(params_);
    temp_params.SetRandn();
    params_.AddMat(stddev, temp_params);
  }
  int32 LinearComponent::NumParameters() const {
    return params_.NumRows() * params_.NumCols();
  }
  void LinearComponent::Vectorize(VectorBase<BaseFloat> *params) const {
    KALDI_ASSERT(params->Dim() == this->NumParameters());
    params->CopyRowsFromMat(params_);
  }
  void LinearComponent::UnVectorize(const VectorBase<BaseFloat> &params) {
    KALDI_ASSERT(params.Dim() == this->NumParameters());
    params_.CopyRowsFromVec(params);
  }
  BaseFloat LinearComponent::DotProduct(const UpdatableComponent &other_in) const {
    const LinearComponent *other =
        dynamic_cast<const LinearComponent*>(&other_in);
    return TraceMatMat(params_, other->params_, kTrans);
  }
  
  void LinearComponent::FreezeNaturalGradient(bool freeze) {
    preconditioner_in_.Freeze(freeze);
    preconditioner_out_.Freeze(freeze);
  }
  
  void LinearComponent::ConsolidateMemory() {
    OnlineNaturalGradient temp_in(preconditioner_in_);
    preconditioner_in_.Swap(&temp_in);
    OnlineNaturalGradient temp_out(preconditioner_out_);
    preconditioner_out_.Swap(&temp_out);
  }
  
  std::string FixedAffineComponent::Info() const {
    std::ostringstream stream;
    stream << Component::Info();
    PrintParameterStats(stream, "linear-params", linear_params_);
    PrintParameterStats(stream, "bias", bias_params_, true);
    return stream.str();
  }
  
  void FixedAffineComponent::Init(const CuMatrixBase<BaseFloat> &mat) {
    KALDI_ASSERT(mat.NumCols() > 1);
    linear_params_ = mat.Range(0, mat.NumRows(), 0, mat.NumCols() - 1);
    bias_params_.Resize(mat.NumRows());
    bias_params_.CopyColFromMat(mat, mat.NumCols() - 1);
  }
  
  void FixedAffineComponent::InitFromConfig(ConfigLine *cfl) {
    std::string filename;
    // Two forms allowed: "matrix=<rxfilename>", or "input-dim=x output-dim=y"
    // (for testing purposes only).
    if (cfl->GetValue("matrix", &filename)) {
      if (cfl->HasUnusedValues())
        KALDI_ERR << "Invalid initializer for layer of type "
                  << Type() << ": \"" << cfl->WholeLine() << "\"";
  
      bool binary;
      Input ki(filename, &binary);
      CuMatrix<BaseFloat> mat;
      mat.Read(ki.Stream(), binary);
      KALDI_ASSERT(mat.NumRows() != 0);
      Init(mat);
    } else {
      int32 input_dim = -1, output_dim = -1;
      if (!cfl->GetValue("input-dim", &input_dim) ||
          !cfl->GetValue("output-dim", &output_dim) || cfl->HasUnusedValues()) {
        KALDI_ERR << "Invalid initializer for layer of type "
                  << Type() << ": \"" << cfl->WholeLine() << "\"";
      }
      CuMatrix<BaseFloat> mat(output_dim, input_dim + 1);
      mat.SetRandn();
      Init(mat);
    }
  }
  
  
  FixedAffineComponent::FixedAffineComponent(const AffineComponent &c):
      linear_params_(c.LinearParams()),
      bias_params_(c.BiasParams()) { }
  
  void* FixedAffineComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
                                       const CuMatrixBase<BaseFloat> &in,
                                       CuMatrixBase<BaseFloat> *out) const  {
    out->CopyRowsFromVec(bias_params_); // Adds the bias term first.
    out->AddMatMat(1.0, in, kNoTrans, linear_params_, kTrans, 1.0);
    return NULL;
  }
  
  void FixedAffineComponent::Backprop(const std::string &debug_info,
                                      const ComponentPrecomputedIndexes *indexes,
                                      const CuMatrixBase<BaseFloat> &, //in_value
                                      const CuMatrixBase<BaseFloat> &, //out_value
                                      const CuMatrixBase<BaseFloat> &out_deriv,
                                      void *memo,
                                      Component *, //to_update
                                      CuMatrixBase<BaseFloat> *in_deriv) const {
    // kBackpropAdds is true. It's the user's responsibility to zero out
    // <in_deriv> if they need it to be so.
    if (in_deriv)
      in_deriv->AddMatMat(1.0, out_deriv, kNoTrans,
                          linear_params_, kNoTrans, 1.0);
  }
  
  Component* FixedAffineComponent::Copy() const {
    FixedAffineComponent *ans = new FixedAffineComponent();
    ans->linear_params_ = linear_params_;
    ans->bias_params_ = bias_params_;
    return ans;
  }
  
  void FixedAffineComponent::Write(std::ostream &os, bool binary) const {
    WriteToken(os, binary, "<FixedAffineComponent>");
    WriteToken(os, binary, "<LinearParams>");
    linear_params_.Write(os, binary);
    WriteToken(os, binary, "<BiasParams>");
    bias_params_.Write(os, binary);
    WriteToken(os, binary, "</FixedAffineComponent>");
  }
  
  void FixedAffineComponent::Read(std::istream &is, bool binary) {
    ExpectOneOrTwoTokens(is, binary, "<FixedAffineComponent>", "<LinearParams>");
    linear_params_.Read(is, binary);
    ExpectToken(is, binary, "<BiasParams>");
    bias_params_.Read(is, binary);
    ExpectToken(is, binary, "</FixedAffineComponent>");
  }
  
  void SumGroupComponent::Init(const std::vector<int32> &sizes) {
    KALDI_ASSERT(!sizes.empty());
    std::vector<Int32Pair> cpu_vec(sizes.size());
    std::vector<int32> reverse_cpu_vec;
    int32 cur_index = 0;
    for (size_t i = 0; i < sizes.size(); i++) {
      KALDI_ASSERT(sizes[i] > 0);
      cpu_vec[i].first = cur_index;
      cpu_vec[i].second = cur_index + sizes[i];
      cur_index += sizes[i];
      for (int32 j = cpu_vec[i].first; j < cpu_vec[i].second; j++)
        reverse_cpu_vec.push_back(i);
    }
    this->indexes_ = cpu_vec;
    this->reverse_indexes_ = reverse_cpu_vec;
    this->input_dim_ = cur_index;
    this->output_dim_ = sizes.size();
  }
  
  void SumGroupComponent::Init(int32 input_dim, int32 output_dim) {
    const int32 num_groups = output_dim;
    KALDI_ASSERT(input_dim % num_groups == 0);
    const int32 group_size = input_dim / num_groups;
  
    std::vector<Int32Pair> cpu_vec(num_groups);
    std::vector<int32> reverse_cpu_vec;
    int32 cur_index = 0;
    for (size_t i = 0; i < num_groups; i++) {
      cpu_vec[i].first = cur_index;
      cpu_vec[i].second = cur_index + group_size;
      cur_index += group_size;
      for (int32 j = cpu_vec[i].first; j < cpu_vec[i].second; j++)
        reverse_cpu_vec.push_back(i);
    }
    this->indexes_ = cpu_vec;
    this->reverse_indexes_ = reverse_cpu_vec;
    this->input_dim_ = input_dim;
    this->output_dim_ = num_groups;
  }
  
  void SumGroupComponent::InitFromConfig(ConfigLine *cfl) {
    std::vector<int32> sizes;
    bool has_sizes = cfl->GetValue("sizes", &sizes);
    if (has_sizes) {
      if (cfl->HasUnusedValues() || sizes.empty())
        KALDI_ERR << "Invalid initializer for layer of type "
                  << Type() << ": \"" << cfl->WholeLine() << "\"";
      this->Init(sizes);
    } else { // each group has the same size
      int32 input_dim = -1, output_dim = -1;
      if (!cfl->GetValue("input-dim", &input_dim) ||
          !cfl->GetValue("output-dim", &output_dim) || cfl->HasUnusedValues()) {
        KALDI_ERR << "Invalid initializer for layer of type "
                  << Type() << ": \"" << cfl->WholeLine() << "\"";
      }
      Init(input_dim, output_dim);
    }
  }
  
  Component* SumGroupComponent::Copy() const {
    SumGroupComponent *ans = new SumGroupComponent();
    ans->indexes_ = indexes_;
    ans->reverse_indexes_ = reverse_indexes_;
    ans->input_dim_ = input_dim_;
    ans->output_dim_ = output_dim_;
    return ans;
  }
  
  void SumGroupComponent::Read(std::istream &is, bool binary) {
    ExpectOneOrTwoTokens(is, binary, "<SumGroupComponent>", "<Sizes>");
    std::vector<int32> sizes;
    ReadIntegerVector(is, binary, &sizes);
  
    std::string token;
    ReadToken(is, binary, &token);
    if (!(token == "<SumGroupComponent>" ||
          token == "</SumGroupComponent>")) {
      KALDI_ERR << "Expected </SumGroupComponent>, got " << token;
    }
    this->Init(sizes);
  }
  
  void SumGroupComponent::GetSizes(std::vector<int32> *sizes) const {
    std::vector<Int32Pair> indexes;
    indexes_.CopyToVec(&indexes);
    sizes->resize(indexes.size());
    for (size_t i = 0; i < indexes.size(); i++) {
      (*sizes)[i] = indexes[i].second - indexes[i].first;
      if (i == 0) { KALDI_ASSERT(indexes[i].first == 0); }
      else { KALDI_ASSERT(indexes[i].first == indexes[i-1].second); }
      KALDI_ASSERT(indexes[i].second > indexes[i].first);
      (*sizes)[i] = indexes[i].second - indexes[i].first;
    }
  }
  
  void SumGroupComponent::Write(std::ostream &os, bool binary) const {
    WriteToken(os, binary, "<SumGroupComponent>");
    WriteToken(os, binary, "<Sizes>");
    std::vector<int32> sizes;
    this->GetSizes(&sizes);
    WriteIntegerVector(os, binary, sizes);
    WriteToken(os, binary, "</SumGroupComponent>");
  }
  
  void* SumGroupComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
                                    const CuMatrixBase<BaseFloat> &in,
                                    CuMatrixBase<BaseFloat> *out) const {
    out->SumColumnRanges(in, indexes_);
    return NULL;
  }
  
  void SumGroupComponent::Backprop(const std::string &debug_info,
                                   const ComponentPrecomputedIndexes *indexes,
                                   const CuMatrixBase<BaseFloat> &, // in_value,
                                   const CuMatrixBase<BaseFloat> &, // out_value
                                   const CuMatrixBase<BaseFloat> &out_deriv,
                                   void *memo,
                                   Component *to_update_in,
                                   CuMatrixBase<BaseFloat> *in_deriv) const {
    in_deriv->CopyCols(out_deriv, reverse_indexes_);
  }
  
  void* SoftmaxComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
                                   const CuMatrixBase<BaseFloat> &in,
                                   CuMatrixBase<BaseFloat> *out) const {
    // Apply softmax function to each row of the output...
    // for that row, we do
    // x_i = exp(x_i) / sum_j exp(x_j).
    out->SoftMaxPerRow(in);
  
    // This floor on the output helps us deal with
    // almost-zeros in a way that doesn't lead to overflow.
    out->ApplyFloor(1.0e-20);
  
    return NULL;
  }
  
  void SoftmaxComponent::Backprop(const std::string &debug_info,
                                  const ComponentPrecomputedIndexes *indexes,
                                  const CuMatrixBase<BaseFloat> &, // in_value,
                                  const CuMatrixBase<BaseFloat> &out_value,
                                  const CuMatrixBase<BaseFloat> &out_deriv,
                                  void *memo,
                                  Component *to_update_in,
                                  CuMatrixBase<BaseFloat> *in_deriv) const {
  
    if (to_update_in) {
      SoftmaxComponent *to_update =
          dynamic_cast<SoftmaxComponent*>(to_update_in);
      to_update->StoreBackpropStats(out_deriv);
    }
  
    if (in_deriv == NULL)
      return;
    /*
      Note on the derivative of the softmax function: let it be
      p_i = exp(x_i) / sum_i exp_i
      The [matrix-valued] Jacobian of this function is
      diag(p) - p p^T
      Let the derivative vector at the output be e, and at the input be
      d.  We have
      d = diag(p) e - p (p^T e).
      d_i = p_i e_i - p_i (p^T e).
    */
    in_deriv->DiffSoftmaxPerRow(out_value, out_deriv);
  }
  
  void SoftmaxComponent::StoreStats(const CuMatrixBase<BaseFloat> &in_value,
                                    const CuMatrixBase<BaseFloat> &out_value,
                                    void *memo) {
    // We don't store derivative stats for this component type, just activation
    // stats.
    StoreStatsInternal(out_value, NULL);
  }
  
  
  void* LogSoftmaxComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
                                      const CuMatrixBase<BaseFloat> &in,
                                      CuMatrixBase<BaseFloat> *out) const {
    // Applies log softmax function to each row of the output. For each row, we do
    // x_i = x_i - log(sum_j exp(x_j))
    out->LogSoftMaxPerRow(in);
    return NULL;
  }
  
  void LogSoftmaxComponent::Backprop(const std::string &debug_info,
                                     const ComponentPrecomputedIndexes *indexes,
                                     const CuMatrixBase<BaseFloat> &, // in_value
                                     const CuMatrixBase<BaseFloat> &out_value,
                                     const CuMatrixBase<BaseFloat> &out_deriv,
                                     void *memo,
                                     Component *to_update_in,
                                     CuMatrixBase<BaseFloat> *in_deriv) const {
    if (to_update_in) {
      LogSoftmaxComponent *to_update =
          dynamic_cast<LogSoftmaxComponent*>(to_update_in);
      to_update->StoreBackpropStats(out_deriv);
    }
    if (in_deriv == NULL)
      return;
    in_deriv->DiffLogSoftmaxPerRow(out_value, out_deriv);
  }
  
  
  void FixedScaleComponent::Init(const CuVectorBase<BaseFloat> &scales) {
    KALDI_ASSERT(scales.Dim() != 0);
    scales_ = scales;
  }
  
  
  void FixedScaleComponent::InitFromConfig(ConfigLine *cfl) {
    std::string filename;
    // Accepts "scales" config (for filename) or "dim" -> random init, for testing.
    if (cfl->GetValue("scales", &filename)) {
      if (cfl->HasUnusedValues())
        KALDI_ERR << "Invalid initializer for layer of type "
                  << Type() << ": \"" << cfl->WholeLine() << "\"";
      CuVector<BaseFloat> vec;
      ReadKaldiObject(filename, &vec);
      Init(vec);
    } else {
      int32 dim;
      BaseFloat scale = 1.0;
      bool scale_is_set = cfl->GetValue("scale", &scale);
      if (!cfl->GetValue("dim", &dim) || cfl->HasUnusedValues())
        KALDI_ERR << "Invalid initializer for layer of type "
                  << Type() << ": \"" << cfl->WholeLine() << "\"";
      KALDI_ASSERT(dim > 0);
      CuVector<BaseFloat> vec(dim);
      if (scale_is_set) {
        vec.Set(scale);
      } else {
        vec.SetRandn();
      }
      Init(vec);
    }
  }
  
  
  std::string FixedScaleComponent::Info() const {
    std::ostringstream stream;
    stream << Component::Info();
    PrintParameterStats(stream, "scales", scales_, true);
    return stream.str();
  }
  
  void* FixedScaleComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
                                       const CuMatrixBase<BaseFloat> &in,
                                       CuMatrixBase<BaseFloat> *out) const {
    out->CopyFromMat(in);  // does nothing if same matrix.
    out->MulColsVec(scales_);
    return NULL;
  }
  
  void FixedScaleComponent::Backprop(const std::string &debug_info,
                                     const ComponentPrecomputedIndexes *indexes,
                                     const CuMatrixBase<BaseFloat> &, // in_value
                                     const CuMatrixBase<BaseFloat> &, // out_value
                                     const CuMatrixBase<BaseFloat> &out_deriv,
                                     void *memo,
                                     Component *, // to_update
                                     CuMatrixBase<BaseFloat> *in_deriv) const {
    in_deriv->CopyFromMat(out_deriv);  // does nothing if same memory.
    in_deriv->MulColsVec(scales_);
  }
  
  Component* FixedScaleComponent::Copy() const {
    FixedScaleComponent *ans = new FixedScaleComponent();
    ans->scales_ = scales_;
    return ans;
  }
  
  
  void FixedScaleComponent::Write(std::ostream &os, bool binary) const {
    WriteToken(os, binary, "<FixedScaleComponent>");
    WriteToken(os, binary, "<Scales>");
    scales_.Write(os, binary);
    WriteToken(os, binary, "</FixedScaleComponent>");
  }
  
  void FixedScaleComponent::Read(std::istream &is, bool binary) {
    ExpectOneOrTwoTokens(is, binary, "<FixedScaleComponent>", "<Scales>");
    scales_.Read(is, binary);
    ExpectToken(is, binary, "</FixedScaleComponent>");
  }
  
  void FixedBiasComponent::Init(const CuVectorBase<BaseFloat> &bias) {
    KALDI_ASSERT(bias.Dim() != 0);
    bias_ = bias;
  }
  
  void FixedBiasComponent::InitFromConfig(ConfigLine *cfl) {
    std::string filename;
    // Accepts "bias" config (for filename) or "dim" -> random init, for testing.
    if (cfl->GetValue("bias", &filename)) {
      if (cfl->HasUnusedValues())
        KALDI_ERR << "Invalid initializer for layer of type "
                  << Type() << ": \"" << cfl->WholeLine() << "\"";
      CuVector<BaseFloat> vec;
      ReadKaldiObject(filename, &vec);
      Init(vec);
    } else {
      int32 dim;
      if (!cfl->GetValue("dim", &dim) || cfl->HasUnusedValues())
        KALDI_ERR << "Invalid initializer for layer of type "
                  << Type() << ": \"" << cfl->WholeLine() << "\"";
      KALDI_ASSERT(dim > 0);
      CuVector<BaseFloat> vec(dim);
      vec.SetRandn();
      Init(vec);
    }
  }
  
  std::string FixedBiasComponent::Info() const {
    std::ostringstream stream;
    stream << Component::Info();
    PrintParameterStats(stream, "bias", bias_, true);
    return stream.str();
  }
  
  void* FixedBiasComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
                                     const CuMatrixBase<BaseFloat> &in,
                                     CuMatrixBase<BaseFloat> *out) const {
    out->CopyFromMat(in);  // will do nothing if in and out have same memory.
    out->AddVecToRows(1.0, bias_, 1.0);
    return NULL;
  }
  
  void FixedBiasComponent::Backprop(const std::string &debug_info,
                                    const ComponentPrecomputedIndexes *indexes,
                                    const CuMatrixBase<BaseFloat> &, // in_value
                                    const CuMatrixBase<BaseFloat> &, // out_value
                                    const CuMatrixBase<BaseFloat> &out_deriv,
                                    void *memo,
                                    Component *, // to_update
                                    CuMatrixBase<BaseFloat> *in_deriv) const {
    // the following statement will do nothing if in_deriv and out_deriv have same
    // memory.
    in_deriv->CopyFromMat(out_deriv);
  }
  
  Component* FixedBiasComponent::Copy() const {
    FixedBiasComponent *ans = new FixedBiasComponent();
    ans->bias_ = bias_;
    return ans;
  }
  
  
  void FixedBiasComponent::Write(std::ostream &os, bool binary) const {
    WriteToken(os, binary, "<FixedBiasComponent>");
    WriteToken(os, binary, "<Bias>");
    bias_.Write(os, binary);
    WriteToken(os, binary, "</FixedBiasComponent>");
  }
  
  void FixedBiasComponent::Read(std::istream &is, bool binary) {
    ExpectOneOrTwoTokens(is, binary, "<FixedBiasComponent>", "<Bias>");
    bias_.Read(is, binary);
    ExpectToken(is, binary, "</FixedBiasComponent>");
  }
  
  
  void NaturalGradientPerElementScaleComponent::Read(
      std::istream &is, bool binary) {
    ReadUpdatableCommon(is, binary);  // Read the opening tag and learning rate
    ExpectToken(is, binary, "<Params>");
    scales_.Read(is, binary);
    ExpectToken(is, binary, "<IsGradient>");
    ReadBasicType(is, binary, &is_gradient_);
    int32 rank, update_period;
    ExpectToken(is, binary, "<Rank>");
    ReadBasicType(is, binary, &rank);
    preconditioner_.SetRank(rank);
    ExpectToken(is, binary, "<UpdatePeriod>");
    ReadBasicType(is, binary, &update_period);
    preconditioner_.SetUpdatePeriod(update_period);
    BaseFloat num_samples_history, alpha;
    ExpectToken(is, binary, "<NumSamplesHistory>");
    ReadBasicType(is, binary, &num_samples_history);
    preconditioner_.SetNumSamplesHistory(num_samples_history);
    ExpectToken(is, binary, "<Alpha>");
    ReadBasicType(is, binary, &alpha);
    preconditioner_.SetAlpha(alpha);
    std::string token;
    ReadToken(is, binary, &token);
    if (token == "<MaxChangePerMinibatch>") {
      // back compatibility; this was removed, it's now handled by the
      // 'max-change' config variable.
      BaseFloat temp;
      ReadBasicType(is, binary, &temp);
      ReadToken(is, binary, &token);
    }
    KALDI_ASSERT(token == "</NaturalGradientPerElementScaleComponent>");
  }
  
  void NaturalGradientPerElementScaleComponent::Write(std::ostream &os,
                                                      bool binary) const {
    WriteUpdatableCommon(os, binary);  // Write the opening tag and learning rate
    WriteToken(os, binary, "<Params>");
    scales_.Write(os, binary);
    WriteToken(os, binary, "<IsGradient>");
    WriteBasicType(os, binary, is_gradient_);
    WriteToken(os, binary, "<Rank>");
    WriteBasicType(os, binary, preconditioner_.GetRank());
    WriteToken(os, binary, "<UpdatePeriod>");
    WriteBasicType(os, binary, preconditioner_.GetUpdatePeriod());
    WriteToken(os, binary, "<NumSamplesHistory>");
    WriteBasicType(os, binary, preconditioner_.GetNumSamplesHistory());
    WriteToken(os, binary, "<Alpha>");
    WriteBasicType(os, binary, preconditioner_.GetAlpha());
    WriteToken(os, binary, "</NaturalGradientPerElementScaleComponent>");
  }
  
  std::string NaturalGradientPerElementScaleComponent::Info() const {
    std::ostringstream stream;
    stream << PerElementScaleComponent::Info()
           << ", rank=" << preconditioner_.GetRank()
           << ", update-period=" << preconditioner_.GetUpdatePeriod()
           << ", num-samples-history=" << preconditioner_.GetNumSamplesHistory()
           << ", alpha=" << preconditioner_.GetAlpha();
    return stream.str();
  }
  
  void NaturalGradientPerElementScaleComponent::InitFromConfig(ConfigLine *cfl) {
    // First set various configuration values that have defaults.
    int32 rank = 8,  // Use a small rank because in this case the amount of memory
                     // for the preconditioner actually exceeds the memory for the
                     // parameters (by "rank").
        update_period = 10;
    BaseFloat num_samples_history = 2000.0, alpha = 4.0;
    cfl->GetValue("rank", &rank);
    cfl->GetValue("update-period", &update_period);
    cfl->GetValue("num-samples-history", &num_samples_history);
    cfl->GetValue("alpha", &alpha);
    InitLearningRatesFromConfig(cfl);
    std::string filename;
    // Accepts "scales" config (for filename) or "dim" -> random init, for testing.
    if (cfl->GetValue("scales", &filename)) {
      if (cfl->HasUnusedValues())
        KALDI_ERR << "Invalid initializer for layer of type "
                  << Type() << ": \"" << cfl->WholeLine() << "\"";
      Init(filename, rank, update_period, num_samples_history, alpha);
  
    } else {
      BaseFloat param_mean = 1.0, param_stddev = 0.0;
      cfl->GetValue("param-mean", &param_mean);
      cfl->GetValue("param-stddev", &param_stddev);
  
      int32 dim;
      if (!cfl->GetValue("dim", &dim) || cfl->HasUnusedValues())
        KALDI_ERR << "Invalid initializer for layer of type "
                  << Type() << ": \"" << cfl->WholeLine() << "\"";
      KALDI_ASSERT(dim > 0);
  
      Init(dim, param_mean, param_stddev, rank, update_period,
           num_samples_history, alpha);
    }
  }
  
  void NaturalGradientPerElementScaleComponent::Init(
      int32 dim, BaseFloat param_mean,
      BaseFloat param_stddev, int32 rank, int32 update_period,
      BaseFloat num_samples_history, BaseFloat alpha) {
    PerElementScaleComponent::Init(dim, param_mean,
                                   param_stddev);
    preconditioner_.SetRank(rank);
    preconditioner_.SetUpdatePeriod(update_period);
    preconditioner_.SetNumSamplesHistory(num_samples_history);
    preconditioner_.SetAlpha(alpha);
  }
  
  void NaturalGradientPerElementScaleComponent::Init(
      std::string vector_filename,
      int32 rank, int32 update_period, BaseFloat num_samples_history,
      BaseFloat alpha) {
    PerElementScaleComponent::Init(vector_filename);
    preconditioner_.SetRank(rank);
    preconditioner_.SetUpdatePeriod(update_period);
    preconditioner_.SetNumSamplesHistory(num_samples_history);
    preconditioner_.SetAlpha(alpha);
  }
  
  
  NaturalGradientPerElementScaleComponent::NaturalGradientPerElementScaleComponent(
      const NaturalGradientPerElementScaleComponent &other):
      PerElementScaleComponent(other),
      preconditioner_(other.preconditioner_) { }
  
  
  
  
  Component* NaturalGradientPerElementScaleComponent::Copy() const {
    return new NaturalGradientPerElementScaleComponent(*this);
  }
  
  void NaturalGradientPerElementScaleComponent::Update(
      const std::string &debug_info,
      const CuMatrixBase<BaseFloat> &in_value,
      const CuMatrixBase<BaseFloat> &out_deriv) {
  
    CuMatrix<BaseFloat> derivs_per_frame(in_value);
    derivs_per_frame.MulElements(out_deriv);
    // the non-natural-gradient update would just do
    // scales_.AddRowSumMat(learning_rate_, derivs_per_frame).
  
    BaseFloat scale;
    preconditioner_.PreconditionDirections(&derivs_per_frame, &scale);
  
    CuVector<BaseFloat> delta_scales(scales_.Dim());
    delta_scales.AddRowSumMat(scale * learning_rate_, derivs_per_frame);
    scales_.AddVec(1.0, delta_scales);
  }
  
  void NaturalGradientPerElementScaleComponent::FreezeNaturalGradient(bool freeze) {
    preconditioner_.Freeze(freeze);
  }
  
  void NaturalGradientPerElementScaleComponent::ConsolidateMemory() {
    OnlineNaturalGradient temp(preconditioner_);
    preconditioner_.Swap(&temp);
  }
  
  void PermuteComponent::ComputeReverseColumnMap() {
    int32 dim = column_map_.Dim();
    KALDI_ASSERT(dim > 0);
    std::vector<int32> reverse_column_map_cpu(dim, -1),
        column_map_cpu(dim);
    column_map_.CopyToVec(&column_map_cpu);
    for (int32 i = 0; i < dim; i++) {
      int32 &dest = reverse_column_map_cpu[column_map_cpu[i]];
      if (dest != -1)
        KALDI_ERR << "Column map does not represent a permutation.";
      dest = i;
    }
    reverse_column_map_.Resize(dim);
    reverse_column_map_.CopyFromVec(reverse_column_map_cpu);
  }
  
  Component* PermuteComponent::Copy() const {
    PermuteComponent *ans = new PermuteComponent();
    ans->column_map_ = column_map_;
    ans->reverse_column_map_ = reverse_column_map_;
    return ans;
  }
  
  void* PermuteComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
                                   const CuMatrixBase<BaseFloat> &in,
                                   CuMatrixBase<BaseFloat> *out) const  {
    out->CopyCols(in, column_map_);
    return NULL;
  }
  void PermuteComponent::Backprop(const std::string &debug_info,
                                  const ComponentPrecomputedIndexes *indexes,
                                  const CuMatrixBase<BaseFloat> &, //in_value
                                  const CuMatrixBase<BaseFloat> &, // out_value,
                                  const CuMatrixBase<BaseFloat> &out_deriv,
                                  void *memo,
                                  Component *to_update,
                                  CuMatrixBase<BaseFloat> *in_deriv) const  {
    in_deriv->CopyCols(out_deriv, reverse_column_map_);
  }
  
  void PermuteComponent::InitFromConfig(ConfigLine *cfl) {
    bool ok = true;
    std::string column_map_str;
    ok = ok && cfl->GetValue("column-map", &column_map_str);
    std::vector<int32> column_map;
    if (!SplitStringToIntegers(column_map_str, ",", true, &column_map))
      KALDI_ERR << "Bad initializer in PermuteComponent: column-map="
                << column_map_str;
    if (cfl->HasUnusedValues())
      KALDI_ERR << "Could not process these elements in initializer: "
                << cfl->UnusedValues();
    if (!ok)
      KALDI_ERR << "Invalid initializer for layer of type "
                << Type() << ": \"" << cfl->WholeLine() << "\"";
    Init(column_map);
  }
  
  void PermuteComponent::Init(const std::vector<int32> &column_map) {
    KALDI_ASSERT(column_map.size() > 0);
    column_map_.CopyFromVec(column_map);
    ComputeReverseColumnMap();
  }
  
  void PermuteComponent::Read(std::istream &is, bool binary) {
    ExpectOneOrTwoTokens(is, binary, "<PermuteComponent>", "<ColumnMap>");
    std::vector<int32> column_map;
    if (binary && is.peek() == 'F') {
      // back-compatibility code [temporary]
      Vector<BaseFloat> float_map;
      float_map.Read(is, binary);
      column_map.resize(float_map.Dim());
      for (int32 i = 0; i < float_map.Dim(); i++) {
        // note: casting truncates toward zero: add 0.5 to approximate rounding.
        column_map[i] = static_cast<int32>(float_map(i) + 0.5);
      }
      // the next line is a workaround for a bug in the old
      // writing code, which now causes an assert failure.  it's only
      // valid for the permutations we're currently using.  anyway all this
      // code is only temporary.
      column_map.back() = float_map.Dim() - 1;
    } else {
      ReadIntegerVector(is, binary, &column_map);
    }
    column_map_.CopyFromVec(column_map);
    ExpectToken(is, binary, "</PermuteComponent>");
    ComputeReverseColumnMap();
  }
  
  void PermuteComponent::Write(std::ostream &os, bool binary) const {
    WriteToken(os, binary, "<PermuteComponent>");
    WriteToken(os, binary, "<ColumnMap>");
    std::ostringstream buffer;
    std::vector<int32> column_map;
    column_map_.CopyToVec(&column_map);
    WriteIntegerVector(os, binary, column_map);
    WriteToken(os, binary, "</PermuteComponent>");
  }
  
  std::string PermuteComponent::Info() const {
    std::ostringstream stream;
    stream << Type() << ", dim=" << column_map_.Dim();
    stream << " , column-map=[ ";
    std::vector<int32> column_map(column_map_.Dim());
    column_map_.CopyToVec(&column_map);
    int32 max_size = 5;
    for (size_t i = 0; i < column_map.size() && i < max_size; i++)
      stream << column_map[i] << ' ';
    if (static_cast<int32>(column_map.size()) > max_size)
      stream << "... ";
    stream << "]";
    return stream.str();
  }
  
  
  bool CompositeComponent::IsUpdatable() const {
    for (std::vector<Component*>::const_iterator iter = components_.begin(),
             end = components_.end(); iter != end; ++iter)
      if (((*iter)->Properties() & kUpdatableComponent) != 0)
        return true;
    return false;
  }
  
  // virtual
  int32 CompositeComponent::InputDim() const {
    KALDI_ASSERT(!components_.empty());
    return components_.front()->InputDim();
  }
  
  // virtual
  int32 CompositeComponent::OutputDim() const {
    KALDI_ASSERT(!components_.empty());
    return components_.back()->OutputDim();
  }
  
  // virtual
  int32 CompositeComponent::Properties() const {
    KALDI_ASSERT(!components_.empty());
    int32 last_component_properties = components_.back()->Properties(),
        first_component_properties = components_.front()->Properties();
    // We always assume backprop needs the input, as this would be necessary to
    // get the activations at intermediate layers, if these were not needed in
    // backprop, there would be no reason to use a CompositeComponent.
    int32 ans = kSimpleComponent | kBackpropNeedsInput |
        (last_component_properties &
         (kPropagateAdds|kBackpropNeedsOutput|kOutputContiguous)) |
         (first_component_properties &
          (kBackpropAdds|kInputContiguous)) |
         (IsUpdatable() ? kUpdatableComponent : 0);
    // note, we don't return the kStoresStats property because that function is
    // not implemented; instead, for efficiency, we call StoreStats() on any
    // sub-components as part of the backprop phase.
    if (last_component_properties & kStoresStats)
      ans |= kBackpropNeedsOutput;
    return ans;
  }
  
  
  MatrixStrideType CompositeComponent::GetStrideType(int32 i) const {
    int32 num_components = components_.size();
    if ((components_[i]->Properties() & kOutputContiguous) ||
        (i + 1 < num_components &&
         (components_[i + 1]->Properties() & kInputContiguous)))
      return kStrideEqualNumCols;
    else
      return kDefaultStride;
  }
  
  
  // virtual
  void* CompositeComponent::Propagate(
      const ComponentPrecomputedIndexes *, // indexes
      const CuMatrixBase<BaseFloat> &in,
      CuMatrixBase<BaseFloat> *out) const {
    KALDI_ASSERT(in.NumRows() == out->NumRows() && in.NumCols() == InputDim() &&
                 out->NumCols() == OutputDim());
    int32 num_rows = in.NumRows(),
        num_components = components_.size();
    if (max_rows_process_ > 0 && num_rows > max_rows_process_) {
      // recurse and process smaller parts of the data, to save memory.
      for (int32 row_offset = 0; row_offset < num_rows;
           row_offset += max_rows_process_) {
        int32 this_num_rows = std::min<int32>(max_rows_process_,
                                              num_rows - row_offset);
        const CuSubMatrix<BaseFloat> in_part(in, row_offset, this_num_rows,
                                             0, in.NumCols());
        CuSubMatrix<BaseFloat> out_part(*out, row_offset, this_num_rows,
                                        0, out->NumCols());
        this->Propagate(NULL, in_part, &out_part);
      }
      return NULL;
    }
    std::vector<CuMatrix<BaseFloat> > intermediate_outputs(num_components - 1);
    for (int32 i = 0; i < num_components; i++) {
      if (i + 1 < num_components) {
        MatrixResizeType resize_type =
            ((components_[i]->Properties() & kPropagateAdds) ?
             kSetZero : kUndefined);
        intermediate_outputs[i].Resize(num_rows, components_[i]->OutputDim(),
                                       resize_type, GetStrideType(i));
      }
      const CuMatrixBase<BaseFloat> &this_in = (i == 0 ? in :
                                                intermediate_outputs[i-1]);
      CuMatrixBase<BaseFloat> *this_out = (i + 1 == num_components ?
                                           out : &(intermediate_outputs[i]));
      void *memo =  components_[i]->Propagate(NULL, this_in, this_out);
      // we'll re-do the forward propagation in the backprop, and we can
      // regenerate any memos there, so no need to keep them.
      if (memo != NULL)
        components_[i]->DeleteMemo(memo);
      if (i > 0)
        intermediate_outputs[i-1].Resize(0, 0);
    }
    return NULL;
  }
  
  
  void CompositeComponent::Init(const std::vector<Component*> &components,
                                int32 max_rows_process) {
    DeletePointers(&components_);  // clean up.
    components_ = components;
    KALDI_ASSERT(!components.empty());
    max_rows_process_ = max_rows_process;
  
    for (size_t i = 0; i < components_.size(); i++) {
      // make sure all constituent components are simple.
      KALDI_ASSERT(components_[i]->Properties() & kSimpleComponent);
      if (i > 0) {
        // make sure all the internal dimensions match up.
        KALDI_ASSERT(components_[i]->InputDim() ==
                     components_[i-1]->OutputDim());
      }
    }
  }
  
  // virtual
  void CompositeComponent::Read(std::istream &is, bool binary) {
    // Because we didn't previously write out the learning rate,
    // we need some temporary code.
    int32 max_rows_process;
    if (false) {
      ReadUpdatableCommon(is, binary);
      ExpectToken(is, binary, "<MaxRowsProcess>");
      ReadBasicType(is, binary, &max_rows_process);
    } else {  // temporary code.
      std::string token;
      ReadToken(is, binary, &token);
      if (token == "<CompositeComponent>") {
        // if the first token is the opening tag, then
        // ignore it and get the next tag.
        ReadToken(is, binary, &token);
      }
      if (token == "<LearningRateFactor>") {
        ReadBasicType(is, binary, &learning_rate_factor_);
        ReadToken(is, binary, &token);
      } else {
        learning_rate_factor_ = 1.0;
      }
      if (token == "<IsGradient>") {
        ReadBasicType(is, binary, &is_gradient_);
        ReadToken(is, binary, &token);
      } else {
        is_gradient_ = false;
      }
      if (token == "<LearningRate>") {
        ReadBasicType(is, binary, &learning_rate_);
        ReadToken(is, binary, &token);
      }
      if (token != "<MaxRowsProcess>") {
        KALDI_ERR << "Expected token <MaxRowsProcess>, got "
                  << token;
      }
      ReadBasicType(is, binary, &max_rows_process);
    }
    ExpectToken(is, binary, "<NumComponents>");
    int32 num_components;
    ReadBasicType(is, binary, &num_components); // Read dimension.
    if (num_components < 0 || num_components > 100000)
      KALDI_ERR << "Bad num-components";
    std::vector<Component*> components(num_components);
    for (int32 i = 0; i < num_components; i++)
      components[i] = ReadNew(is, binary);
    Init(components, max_rows_process);
    ExpectToken(is, binary, "</CompositeComponent>");
  }
  
  // virtual
  void CompositeComponent::ZeroStats() {
    // we call ZeroStats() on all components without checking their flags; this
    // will do nothing if the component doesn't store stats.  (components like
    // ReLU and sigmoid and tanh store stats on activations).
    for (size_t i = 0; i < components_.size(); i++)
     components_[i]->ZeroStats();
  }
  
  // virtual
  void CompositeComponent::Write(std::ostream &os, bool binary) const {
    WriteUpdatableCommon(os, binary);  // Write opening tag and learning rate.
    WriteToken(os, binary, "<MaxRowsProcess>");
    WriteBasicType(os, binary, max_rows_process_);
    WriteToken(os, binary, "<NumComponents>");
    int32 num_components = components_.size();
    WriteBasicType(os, binary, num_components);
    for (int32 i = 0; i < num_components; i++)
      components_[i]->Write(os, binary);
    WriteToken(os, binary, "</CompositeComponent>");
  }
  
  
  // virtual
  void CompositeComponent::Backprop(const std::string &debug_info,
                                    const ComponentPrecomputedIndexes *indexes,
                                    const CuMatrixBase<BaseFloat> &in_value,
                                    const CuMatrixBase<BaseFloat> &out_value,
                                    const CuMatrixBase<BaseFloat> &out_deriv,
                                    void *memo,
                                    Component *to_update,
                                    CuMatrixBase<BaseFloat> *in_deriv) const {
    KALDI_ASSERT(in_value.NumRows() == out_deriv.NumRows() &&
                 in_value.NumCols() == InputDim() &&
                 out_deriv.NumCols() == OutputDim());
    int32 num_rows = in_value.NumRows(),
        num_components = components_.size();
    if (max_rows_process_ > 0 && num_rows > max_rows_process_) {
      KALDI_ASSERT(max_rows_process_ > 0);
      // recurse and process smaller parts of the data, to save memory.
      for (int32 row_offset = 0; row_offset < num_rows;
           row_offset += max_rows_process_) {
        bool have_output_value = (out_value.NumRows() != 0);
        int32 this_num_rows = std::min<int32>(max_rows_process_,
                                              num_rows - row_offset);
        // out_value_part will only be used if out_value is nonempty; otherwise we
        // make it a submatrix of 'out_deriv' to avoid errors in the constructor.
        const CuSubMatrix<BaseFloat> out_value_part(have_output_value ? out_value : out_deriv,
                                                    row_offset, this_num_rows,
                                                    0, out_deriv.NumCols());
        // in_deriv_value_part will only be used if in_deriv != NULL; otherwise we
        // make it a submatrix of 'in_value' to avoid errors in the constructor.
        CuSubMatrix<BaseFloat> in_deriv_part(in_deriv != NULL ? *in_deriv : in_value,
                                              row_offset, this_num_rows,
                                              0, in_value.NumCols());
        CuSubMatrix<BaseFloat> in_value_part(in_value, row_offset, this_num_rows,
                                             0, in_value.NumCols());
        const CuSubMatrix<BaseFloat> out_deriv_part(out_deriv,
                                                    row_offset, this_num_rows,
                                                    0, out_deriv.NumCols());
        CuMatrix<BaseFloat>  empty_mat;
        this->Backprop(debug_info, NULL, in_value_part,
                       (have_output_value ? static_cast<const CuMatrixBase<BaseFloat>&>(out_value_part) :
                        static_cast<const CuMatrixBase<BaseFloat>&>(empty_mat)),
                       out_deriv_part, NULL, to_update,
                       in_deriv != NULL ? &in_deriv_part : NULL);
      }
      return;
    }
    // For now, assume all intermediate values and derivatives need to be
    // computed.  in_value and out_deriv will always be supplied.
  
    // intermediate_outputs[i] contains the output of component i.
    std::vector<CuMatrix<BaseFloat> > intermediate_outputs(num_components);
    // intermediate_derivs[i] contains the deriative at the output of component i.
    std::vector<CuMatrix<BaseFloat> > intermediate_derivs(num_components - 1);
  
    KALDI_ASSERT(memo == NULL);
    // note: only a very few components use memos, but we need to support them.
    std::vector<void*> memos(num_components, NULL);
  
    int32 num_components_to_propagate = num_components;
    if (!(components_[num_components - 1]->Properties() & kUsesMemo)) {
      // we only need to propagate the very last component if it uses a memo.
      num_components_to_propagate--;
      if (num_components > 1) {
        // skip the last-but-one component's propagate if the last component's
        // backprop doesn't need the input and the last-but-one component's
        // backprop doesn't need the output.  This is the lowest hanging fruit for
        // optimization; other propagates might also be skippable.
        int32 properties = components_[num_components - 2]->Properties(),
            next_properties = components_[num_components - 1]->Properties();
        if (!(properties & (kBackpropNeedsOutput | kUsesMemo)) &&
            !(next_properties & kBackpropNeedsInput)) {
          num_components_to_propagate--;
        }
      }
    }
  
  
    // Do the propagation again.
    for (int32 i = 0; i < num_components_to_propagate; i++) {
      MatrixResizeType resize_type =
          ((components_[i]->Properties() & kPropagateAdds) ?
           kSetZero : kUndefined);
      intermediate_outputs[i].Resize(num_rows, components_[i]->OutputDim(),
                                     resize_type, GetStrideType(i));
      memos[i] =
          components_[i]->Propagate(NULL,
                               (i == 0 ? in_value : intermediate_outputs[i-1]),
                                &(intermediate_outputs[i]));
    }
  
    for (int32 i = num_components - 1; i >= 0; i--) {
      const CuMatrixBase<BaseFloat> &this_in_value =
          (i == 0 ? in_value : intermediate_outputs[i-1]),
          &this_out_value =
          (i == num_components - 1 ? out_value : intermediate_outputs[i]);
  
      Component *component_to_update =
          (to_update == NULL ? NULL :
           dynamic_cast<CompositeComponent*>(to_update)->components_[i]);
  
      if (component_to_update != NULL  &&
          components_[i]->Properties() & kStoresStats)
        component_to_update->StoreStats(this_in_value, this_out_value, memos[i]);
  
      if (i > 0) {
        MatrixResizeType resize_type =
            ((components_[i]->Properties() & kBackpropAdds) ?
             kSetZero : kUndefined);
        intermediate_derivs[i-1].Resize(num_rows, components_[i]->InputDim(),
                                        resize_type, GetStrideType(i - 1));
      }
      // skip the first component's backprop if it's not updatable and in_deriv is
      // not requested.  Again, this is the lowest-hanging fruit to optimize.
      if (!(i == 0 && !(components_[0]->Properties() & kUpdatableComponent) &&
            in_deriv == NULL)) {
        components_[i]->Backprop(debug_info, NULL,
                  this_in_value, this_out_value,
                  (i + 1 == num_components ? out_deriv : intermediate_derivs[i]),
                  memos[i], component_to_update,
                  (i == 0 ? in_deriv : &(intermediate_derivs[i-1])));
      }
      if (memos[i] != NULL)
        components_[i]->DeleteMemo(memos[i]);
    }
  }
  
  
  // virtual
  std::string CompositeComponent::Info() const {
    std::ostringstream stream;
    stream << Type() << " ";
    for (size_t i = 0; i < components_.size(); i++) {
      if (i > 0) stream << ", ";
      stream << "sub-component" << (i+1) << " = { "
             << components_[i]->Info() << " }";
    }
    return stream.str();
  }
  
  // virtual
  void CompositeComponent::Scale(BaseFloat scale) {
    for (size_t i = 0; i < components_.size(); i++)
      components_[i]->Scale(scale);
  }
  
  // virtual
  void CompositeComponent::Add(BaseFloat alpha, const Component &other_in) {
    const CompositeComponent *other = dynamic_cast<const CompositeComponent*>(
        &other_in);
    KALDI_ASSERT(other != NULL && other->components_.size() ==
                 components_.size() && "Mismatching nnet topologies");
    for (size_t i = 0; i < components_.size(); i++)
      components_[i]->Add(alpha, *(other->components_[i]));
  }
  
  // virtual
  void CompositeComponent::PerturbParams(BaseFloat stddev) {
    KALDI_ASSERT(this->IsUpdatable());  // or should not be called.
    for (size_t i = 0; i < components_.size(); i++) {
      if (components_[i]->Properties() & kUpdatableComponent) {
        UpdatableComponent *uc =
            dynamic_cast<UpdatableComponent*>(components_[i]);
        uc->PerturbParams(stddev);
      }
    }
  }
  
  void CompositeComponent::SetUnderlyingLearningRate(BaseFloat lrate) {
    KALDI_ASSERT(this->IsUpdatable());  // or should not be called.
    UpdatableComponent::SetUnderlyingLearningRate(lrate);
  
    // apply any learning-rate-factor that's set at this level (ill-advised, but
    // we'll do it.)
    BaseFloat effective_lrate = LearningRate();
    for (size_t i = 0; i < components_.size(); i++) {
      if (components_[i]->Properties() & kUpdatableComponent) {
        UpdatableComponent *uc =
            dynamic_cast<UpdatableComponent*>(components_[i]);
        uc->SetUnderlyingLearningRate(effective_lrate);
      }
    }
  }
  
  void CompositeComponent::SetActualLearningRate(BaseFloat lrate) {
    KALDI_ASSERT(this->IsUpdatable());  // or should not be called.
    UpdatableComponent::SetActualLearningRate(lrate);
    for (size_t i = 0; i < components_.size(); i++) {
      if (components_[i]->Properties() & kUpdatableComponent) {
        UpdatableComponent *uc =
            dynamic_cast<UpdatableComponent*>(components_[i]);
        uc->SetActualLearningRate(lrate);
      }
    }
  }
  
  // virtual
  void CompositeComponent::SetAsGradient() {
    KALDI_ASSERT(this->IsUpdatable());  // or should not be called.
    UpdatableComponent::SetAsGradient();
    for (size_t i = 0; i < components_.size(); i++) {
      if (components_[i]->Properties() & kUpdatableComponent) {
        UpdatableComponent *uc =
            dynamic_cast<UpdatableComponent*>(components_[i]);
        uc->SetAsGradient();
      }
    }
  }
  
  // virtual
  int32 CompositeComponent::NumParameters() const {
    KALDI_ASSERT(this->IsUpdatable());  // or should not be called.
    int32 ans = 0;
    for (size_t i = 0; i < components_.size(); i++) {
      if (components_[i]->Properties() & kUpdatableComponent) {
        UpdatableComponent *uc =
            dynamic_cast<UpdatableComponent*>(components_[i]);
        ans += uc->NumParameters();
      }
    }
    return ans;
  }
  
  // virtual
  void CompositeComponent::Vectorize(VectorBase<BaseFloat> *params) const {
    int32 cur_offset = 0;
    KALDI_ASSERT(this->IsUpdatable());  // or should not be called.
    for (size_t i = 0; i < components_.size(); i++) {
      if (components_[i]->Properties() & kUpdatableComponent) {
        UpdatableComponent *uc =
            dynamic_cast<UpdatableComponent*>(components_[i]);
        int32 this_size = uc->NumParameters();
        SubVector<BaseFloat> params_range(*params, cur_offset, this_size);
        uc->Vectorize(&params_range);
        cur_offset += this_size;
      }
    }
    KALDI_ASSERT(cur_offset == params->Dim());
  }
  
  // virtual
  void CompositeComponent::UnVectorize(const VectorBase<BaseFloat> &params) {
    int32 cur_offset = 0;
    KALDI_ASSERT(this->IsUpdatable());  // or should not be called.
    for (size_t i = 0; i < components_.size(); i++) {
      if (components_[i]->Properties() & kUpdatableComponent) {
        UpdatableComponent *uc =
            dynamic_cast<UpdatableComponent*>(components_[i]);
        int32 this_size = uc->NumParameters();
        SubVector<BaseFloat> params_range(params, cur_offset, this_size);
        uc->UnVectorize(params_range);
        cur_offset += this_size;
      }
    }
    KALDI_ASSERT(cur_offset == params.Dim());
  }
  
  // virtual
  BaseFloat CompositeComponent::DotProduct(
      const UpdatableComponent &other_in) const {
    const CompositeComponent *other = dynamic_cast<const CompositeComponent*>(
        &other_in);
    KALDI_ASSERT(other != NULL && other->components_.size() ==
                 components_.size() && "Mismatching nnet topologies");
    BaseFloat ans = 0.0;
    for (size_t i = 0.0; i < components_.size(); i++) {
      if (components_[i]->Properties() & kUpdatableComponent) {
        UpdatableComponent *uc =
            dynamic_cast<UpdatableComponent*>(components_[i]);
        const UpdatableComponent *uc_other =
            dynamic_cast<UpdatableComponent*>(other->components_[i]);
        KALDI_ASSERT(uc != NULL && uc_other != NULL);
        ans += uc->DotProduct(*uc_other);
      }
    }
    return ans;
  }
  
  /// virtual
  void CompositeComponent::FreezeNaturalGradient(bool freeze) {
    for (size_t i = 0; i < components_.size(); i++) {
      if (components_[i]->Properties() & kUpdatableComponent) {
        UpdatableComponent *uc =
            dynamic_cast<UpdatableComponent*>(components_[i]);
        KALDI_ASSERT(uc != NULL);
        uc->FreezeNaturalGradient(freeze);
      }
    }
  }
  
  // virtual
  Component* CompositeComponent::Copy() const {
    std::vector<Component*> components(components_.size());
    for (size_t i = 0; i < components_.size(); i++)
      components[i] = components_[i]->Copy();
    CompositeComponent *ans = new CompositeComponent();
    ans->Init(components, max_rows_process_);
    return ans;
  }
  
  
  // virtual
  void CompositeComponent::InitFromConfig(ConfigLine *cfl) {
    int32 max_rows_process = 4096, num_components = -1;
    cfl->GetValue("max-rows-process", &max_rows_process);
    if (!cfl->GetValue("num-components", &num_components) ||
        num_components < 1)
      KALDI_ERR << "Expected num-components to be defined in "
                << "CompositeComponent config line '" << cfl->WholeLine() << "'";
    std::vector<Component*> components;
    for (int32 i = 1; i <= num_components; i++) {
      std::ostringstream name_stream;
      name_stream << "component" << i;
      std::string component_config;
      if (!cfl->GetValue(name_stream.str(), &component_config)) {
        DeletePointers(&components);
        KALDI_ERR << "Expected '" << name_stream.str() << "' to be defined in "
                  << "CompositeComponent config line '" << cfl->WholeLine() << "'";
      }
      ConfigLine nested_line;
      // note: the nested line may not contain comments.
      std::string component_type;
      Component *this_component = NULL;
      if (!nested_line.ParseLine(component_config) ||
          !nested_line.GetValue("type", &component_type) ||
          !(this_component = NewComponentOfType(component_type)) ||
          nested_line.FirstToken() != "") {
        DeletePointers(&components);
        KALDI_ERR << "Could not parse config line for '" << name_stream.str()
                  << "(or undefined or bad component type [type=xxx]), in "
                  << "CompositeComponent config line '" << cfl->WholeLine() << "'";
      }
      if(this_component->Type() == "CompositeComponent") {
        DeletePointers(&components);
        delete this_component;
        // This is not allowed.  If memory is too much with just one
        // CompositeComponent, try decreasing max-rows-process instead.
        KALDI_ERR << "Found CompositeComponent nested within CompositeComponent."
                  << "Nested line: '" << nested_line.WholeLine() << "'
  "
                  << "Toplevel CompositeComponent line '" << cfl->WholeLine()
                  << "'";
      }
      this_component->InitFromConfig(&nested_line);
      int32 props = this_component->Properties();
      if ((props & kRandomComponent) != 0 ||
          (props & kSimpleComponent) == 0) {
        KALDI_ERR << "CompositeComponent contains disallowed component type: "
                  << nested_line.WholeLine();
      }
      components.push_back(this_component);
    }
    if (cfl->HasUnusedValues())
      KALDI_ERR << "Could not process these elements in initializer: "
                << cfl->UnusedValues();
    this->Init(components, max_rows_process);
  }
  
  const Component* CompositeComponent::GetComponent(int32 i) const {
    KALDI_ASSERT(static_cast<size_t>(i) < components_.size());
    return components_[i];
  }
  
  void CompositeComponent::SetComponent(int32 i, Component *component) {
    KALDI_ASSERT(static_cast<size_t>(i) < components_.size());
    delete components_[i];
    components_[i] = component;
  }
  
  
  SumBlockComponent::SumBlockComponent(const SumBlockComponent &other):
      input_dim_(other.input_dim_), output_dim_(other.output_dim_),
      scale_(other.scale_) { }
  
  void SumBlockComponent::InitFromConfig(ConfigLine *cfl) {
    scale_ = 1.0;
    bool ok = cfl->GetValue("input-dim", &input_dim_) &&
        cfl->GetValue("output-dim", &output_dim_);
    if (!ok)
      KALDI_ERR << "input-dim and output-dim must both be provided.";
    if (input_dim_ <= 0 || input_dim_ % output_dim_ != 0)
      KALDI_ERR << "Invalid values input-dim=" << input_dim_
                << " output-dim=" << output_dim_;
    cfl->GetValue("scale", &scale_);
    if (cfl->HasUnusedValues())
      KALDI_ERR << "Could not process these elements in initializer: "
                << cfl->UnusedValues();
  }
  
  void SumBlockComponent::Read(std::istream &is, bool binary) {
    ExpectOneOrTwoTokens(is, binary, "<SumBlockComponent>", "<InputDim>");
    ReadBasicType(is, binary, &input_dim_);
    ExpectToken(is, binary, "<OutputDim>");
    ReadBasicType(is, binary, &output_dim_);
    ExpectToken(is, binary, "<Scale>");
    ReadBasicType(is, binary, &scale_);
    ExpectToken(is, binary, "</SumBlockComponent>");
  }
  
  void SumBlockComponent::Write(std::ostream &os, bool binary) const {
    WriteToken(os, binary, "<SumBlockComponent>");
    WriteToken(os, binary, "<InputDim>");
    WriteBasicType(os, binary, input_dim_);
    WriteToken(os, binary, "<OutputDim>");
    WriteBasicType(os, binary, output_dim_);
    WriteToken(os, binary, "<Scale>");
    WriteBasicType(os, binary, scale_);
    WriteToken(os, binary, "</SumBlockComponent>");
  }
  
  std::string SumBlockComponent::Info() const {
    std::ostringstream stream;
    stream << Type() << ", input-dim=" << input_dim_
           << ", output-dim=" << output_dim_
           << ", scale=" << scale_;
    return stream.str();
  }
  
  void* SumBlockComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
                                     const CuMatrixBase<BaseFloat> &in,
                                     CuMatrixBase<BaseFloat> *out) const {
    KALDI_ASSERT(out->NumRows() == in.NumRows() &&
                 out->NumCols() == output_dim_ &&
                 in.NumCols() == input_dim_);
    out->AddMatBlocks(scale_, in, kNoTrans);
    return NULL;
  }
  
  void SumBlockComponent::Backprop(
      const std::string &debug_info,
      const ComponentPrecomputedIndexes *indexes,
      const CuMatrixBase<BaseFloat> &, //in_value
      const CuMatrixBase<BaseFloat> &, // out_value,
      const CuMatrixBase<BaseFloat> &out_deriv,
      void *memo,
      Component *to_update,
      CuMatrixBase<BaseFloat> *in_deriv) const {
    if (in_deriv) {
      in_deriv->AddMatBlocks(scale_, out_deriv, kNoTrans);
    }
  }
  
  
  
  } // namespace nnet3
  } // namespace kaldi