Repository navigation
Expand file tree
/
Copy pathnetwork.py
More file actions
2355 lines (1907 loc) · 77.2 KB
/
Copy pathnetwork.py
File metadata and controls
2355 lines (1907 loc) · 77.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
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
import collections
import dataclasses
import fractions
import functools
import itertools
import logging
import math
import pathlib
import pickle
import random
import zlib
from typing import Dict, FrozenSet, List, Optional, Text, Tuple, Union
import numba
import numpy as np
from numba import types
from scipy import special
import configuration
import corpora
import utils
_NODE_VALUE_LIMIT = np.int32(1_000_000)
LINEAR = 0
RELU = 1
SIGMOID = 2
_TANH = 3
SQUARE = 4
FLOOR = 5
UNSIGNED_STEP = 6
_GAUSSIAN = 7
_SINUS = 8
_INVERSE = 9
_ABS = 10
_COSINE = 11
MODULO_2 = 12
SHIFT_RIGHT = 13
MODULO_3 = 14
FORWARD_CONNECTION = 0
RECURRENT_CONNECTION = 1
_BIAS_CONNECTION = 2
SUMMATION_UNIT = 0
MULTIPLICATION_UNIT = 1
_CLASSES_DTYPE = np.uint16
_INF = float("inf")
def _linear(x):
return x
@numba.jit(
(types.Array(utils.NUMBA_FLOAT_DTYPE, ndim=1, layout="C", readonly=True),),
nopython=True,
)
def _relu(x):
return x * (x > 0)
@numba.jit(
(types.Array(utils.NUMBA_FLOAT_DTYPE, ndim=1, layout="C", readonly=True),),
nopython=True,
)
def _square(x):
return x ** 2
_sigmoid = special.expit
def _tanh(x):
return np.tanh(x)
def _floor(x):
return np.floor(x)
def _gaussian(x):
return np.exp(-np.multiply(x, x) / 2.0)
@numba.jit(
(types.Array(utils.NUMBA_FLOAT_DTYPE, ndim=1, layout="C", readonly=True),),
nopython=True,
)
def _unsigned_step(x):
# Taken from Gaier & Ha.
return 1.0 * (x > 0.0)
def _sinus(x):
# Taken from Gaier & Ha.
return np.sin(np.pi * x)
def _inverse(x):
return -x
def _cosine(x):
# Taken from Giaer & Ha.
return np.cos(np.pi * x)
@numba.jit(
(types.Array(utils.NUMBA_FLOAT_DTYPE, ndim=1, layout="C", readonly=True),),
nopython=True,
)
def _modulo_2_numba(x):
return np.mod(x, 2)
@numba.jit(
(types.Array(utils.NUMBA_FLOAT_DTYPE, ndim=1, layout="C", readonly=True),),
nopython=True,
)
def _modulo_3_numba(x):
return np.mod(x, 3)
@numba.jit(
(types.Array(utils.NUMBA_FLOAT_DTYPE, ndim=1, layout="C", readonly=True),),
nopython=True,
)
def _shift_right(x):
return np.floor_divide(x, 2)
_ACTIVATIONS = {
LINEAR: _linear,
RELU: _relu,
SIGMOID: _sigmoid,
_TANH: _tanh,
SQUARE: _square,
FLOOR: _floor,
UNSIGNED_STEP: _unsigned_step,
_GAUSSIAN: _gaussian,
_SINUS: _sinus,
_INVERSE: _inverse,
_COSINE: _cosine,
_ABS: np.abs,
MODULO_2: _modulo_2_numba,
MODULO_3: _modulo_3_numba,
SHIFT_RIGHT: _shift_right,
}
_ACTIVATION_NAMES = {
LINEAR: "linear",
RELU: "relu",
SIGMOID: "sigmoid",
_TANH: "tanh",
SQUARE: "square",
FLOOR: "floor",
_GAUSSIAN: "gaussian",
UNSIGNED_STEP: "step",
_SINUS: "sin",
_INVERSE: "inverse",
_ABS: "abs",
_COSINE: "cosine",
MODULO_2: "mod2",
MODULO_3: "mod3",
SHIFT_RIGHT: ">>",
}
_ACTIVATION_COSTS = {
# Ordered by performance cost.
LINEAR: 0,
_INVERSE: 1,
_ABS: 1,
RELU: 2,
SQUARE: 2,
SIGMOID: 4,
FLOOR: 4,
_TANH: 8,
MODULO_2: 8,
MODULO_3: 8,
UNSIGNED_STEP: 8,
_GAUSSIAN: 16,
_SINUS: 16,
_COSINE: 16,
SHIFT_RIGHT: 16,
}
def _eq_zero(x):
# Using `isclose` for zero comparison because of precision-point float instabilities.
# See `https://stackoverflow.com/questions/69256825/numpy-matrix-multiplication-instability-across-rows`.
return np.isclose(x, 0.0)
def _binary_output_probabs(x: np.ndarray) -> np.ndarray:
return np.clip(x, a_min=0, a_max=1.0)
def normalize_multiclass(x: np.ndarray) -> np.ndarray:
x[x < 0] = 0
sums = np.sum(x, axis=-1)
# If output is all zeros, force probabs to be uniform.
sums_eq_zero = _eq_zero(sums)
zero_output_idxs = np.where(sums_eq_zero)
x[zero_output_idxs] = 1
sums[sums_eq_zero] = x.shape[-1]
return x / np.expand_dims(sums, -1)
@dataclasses.dataclass(frozen=True)
class _Weight:
sign: int
numerator: int
denominator: int
_Node = int
_Edge = Tuple[_Node, _Node]
_Connections = Dict[_Node, FrozenSet[_Node]]
_Weights = Dict[_Edge, _Weight]
_Biases = Dict[_Node, _Weight]
_Activations = Dict[_Node, int]
@dataclasses.dataclass(frozen=True)
class Fitness:
mdl: float
grammar_encoding_length: float
data_encoding_length: float
accuracy: float
@dataclasses.dataclass(frozen=True)
class Network:
input_units_range: List[int]
output_units_range: List[int]
forward_weights: _Weights
recurrent_weights: _Weights
forward_connections: _Connections
reverse_forward_connections: _Connections
recurrent_connections: _Connections
reverse_recurrent_connections: _Connections
biases: _Biases
activations: _Activations
unit_types: _Activations
fitness: Optional[Fitness] = None
def __eq__(self, other):
return hash(self) == hash(other)
def __hash__(self):
tup = tuple(
tuple(sorted(x.items()))
for x in [
self.forward_weights,
self.recurrent_weights,
self.forward_connections,
self.recurrent_connections,
self.biases,
self.activations,
self.unit_types,
]
)
return hash(tup)
def __repr__(self):
return to_string(self)
_IDENTITY_WEIGHT = _Weight(1, 1, 1)
class _InvalidNet(Exception):
pass
def _make_random_weight() -> _Weight:
numerator, denominator = _geometric_sample(shape=2, minimum=1)
return _Weight(
sign=np.random.choice([-1, 1]), numerator=numerator, denominator=denominator
)
def _get_weight_real_value(w: _Weight) -> float:
return w.sign * w.numerator / w.denominator
def _get_next_available_unit(active_units: FrozenSet[_Node]) -> int:
"""
Units = {0,1,2,3} -> 4
Units = {0,1,2,5} -> 3
"""
try:
return next(x for x in range(len(active_units)) if x not in active_units)
except StopIteration:
return len(active_units)
def topological_sort_through_time(
net: Network,
) -> Tuple[FrozenSet[_Edge], Tuple[_Node, ...]]:
units = get_units(net)
loop_edges_for_forward_paths, topological_sort = run_dfs(
units=units,
reverse_connections=net.reverse_forward_connections,
input_units=net.input_units_range,
output_units=net.output_units_range,
)
units_with_outgoing_recurrent_edges = frozenset(
node
for node in net.recurrent_connections
if len(net.recurrent_connections[node])
)
units_with_outgoing_recurrent_not_in_topo_sort = list(
units_with_outgoing_recurrent_edges - frozenset(topological_sort)
)
loop_edges_including_recurrent_paths, recurrent_topological_sort = run_dfs(
units=units,
reverse_connections=net.reverse_forward_connections,
input_units=net.input_units_range,
output_units=units_with_outgoing_recurrent_not_in_topo_sort,
)
topological_sort_including_recurrent = topological_sort + tuple(
x for x in recurrent_topological_sort if x not in frozenset(topological_sort)
)
loop_edges = loop_edges_for_forward_paths | loop_edges_including_recurrent_paths
return loop_edges, topological_sort_including_recurrent
def run_dfs(
units: FrozenSet[_Node],
reverse_connections: _Connections,
input_units: List[_Node],
output_units: List[_Node],
) -> Tuple[FrozenSet[_Edge], Tuple[_Node, ...]]:
""" Runs DFS (iterative) on a directed graph which may contain cycles.
Returns a set of back edges and a topological sort of nodes in the graph as if it didn't contain cycles.
"""
reverse_connections = _dict_copy(reverse_connections)
active_units = units
entry_node = _get_next_available_unit(active_units)
sink_node = _get_next_available_unit(active_units | {entry_node})
reverse_connections[entry_node] = frozenset(output_units)
for input_node in input_units:
if input_node not in reverse_connections:
reverse_connections[input_node] = frozenset()
reverse_connections[input_node] |= {sink_node}
loop_edges = set()
topological_sort = []
black = set()
gray = {entry_node}
stack = [entry_node]
while stack:
node = stack[0]
neighbors = reverse_connections.get(node, set())
recurse = False
for neighbor in neighbors:
if neighbor in gray:
loop_edges.add((neighbor, node))
elif neighbor not in black:
stack.insert(0, neighbor)
gray.add(neighbor)
recurse = True
break
if recurse:
continue
black.add(node)
gray.remove(node)
stack.pop(0)
if node not in (entry_node, sink_node):
topological_sort.append(node)
return frozenset(loop_edges), tuple(topological_sort)
def _geometric_sample(shape=None, minimum: int = 0, dtype=np.int):
return np.floor(-np.log2(np.random.random(shape))).astype(dtype) + minimum
def _ceil_log2(x):
return np.ceil(np.log2(x))
@functools.lru_cache(maxsize=100_000)
def _ceil_log2_python(x):
return math.ceil(math.log2(x))
def _reverse_set_dict(d: Dict) -> Dict:
new_dict = collections.defaultdict(frozenset)
for x, vals in d.items():
for y in vals:
new_dict[y] |= {x}
return dict(new_dict)
@functools.lru_cache(maxsize=100_000)
def _int_to_binary_string(n, sequence_length=None) -> Text:
binary = f"{n:b}"
if sequence_length is not None:
binary = ("0" * (sequence_length - len(binary))) + binary
return binary
@functools.lru_cache(maxsize=100_000)
def _integer_encoding(n) -> Text:
# Based on Vitanyi & Li's self-delimiting encoding: `unary_encoding(log2_N) + '0' + binary_encoding(N)`.
if n == 0:
return "0"
binary = _int_to_binary_string(n)
return ("1" * len(binary)) + "0" + binary
@functools.lru_cache(maxsize=100_000)
def _get_weight_encoding(weight: _Weight) -> Text:
encoding = ""
encoding += "0" if weight.sign == -1 else "1"
encoding += _integer_encoding(weight.numerator)
encoding += _integer_encoding(weight.denominator)
return encoding
def _get_bitsring_encoding(net: Network, allowed_activations: Tuple[int, ...]) -> Text:
num_units = get_num_units(net)
single_activation_encoding_length = _ceil_log2_python(len(allowed_activations))
# Using fixed-length encoding to prevent a bias for lower-id units.
unit_id_encoding_length = _ceil_log2_python(num_units)
# Specify how many units we need to parse.
encoding = _integer_encoding(num_units)
for unit in range(num_units):
unit_forward_targets = net.forward_connections.get(unit, ())
unit_recurrent_targets = net.recurrent_connections.get(unit, ())
# Specify how many connections we need to parse for this unit.
encoding += _integer_encoding(
len(unit_forward_targets) + len(unit_recurrent_targets)
)
for forward_target_unit in unit_forward_targets:
encoding += "0" # "Forward" bit.
encoding += _int_to_binary_string(
forward_target_unit, sequence_length=unit_id_encoding_length
)
encoding += _get_weight_encoding(
net.forward_weights[(unit, forward_target_unit)]
)
for recurrent_target_unit in unit_recurrent_targets:
encoding += "1" # "Recurrent" bit.
encoding += _int_to_binary_string(
recurrent_target_unit, sequence_length=unit_id_encoding_length
)
encoding += _get_weight_encoding(
net.recurrent_weights[(unit, recurrent_target_unit)]
)
# Unit type.
encoding += {SUMMATION_UNIT: "1", MULTIPLICATION_UNIT: "0"}[
net.unit_types[unit]
]
# Unit activation and delimiter.
encoding += _int_to_binary_string(
net.activations[unit], sequence_length=single_activation_encoding_length
)
encoding += ("1" * _ACTIVATION_COSTS[net.activations[unit]]) + "0"
# Unit bias.
if unit in net.biases:
encoding += _get_weight_encoding(net.biases[unit])
else:
# "Skip".
encoding += "00"
return encoding
def get_encoding_length(
net: Network, allowed_activations: Tuple[int, ...], compress_encoding: bool
) -> float:
encoding_bitstring = _get_bitsring_encoding(
net=net, allowed_activations=allowed_activations
)
if compress_encoding:
bytes_ = zlib.compress(encoding_bitstring.encode("utf-8"))
return len(bytes_)
return len(encoding_bitstring)
def _try_early_stop(
sequence_length: int,
targets_mask: Optional[np.ndarray],
input_mask: Optional[np.ndarray],
time_step: int,
time_step_outputs: np.ndarray,
):
"""Stop sequence feeding in case a target is given a categorical 0.0 probab, causing D:G => infinity. """
# Using log to scale slowly with sequence length.
early_stop_limit = _ceil_log2_python(sequence_length)
if targets_mask is None or input_mask is None or time_step >= early_stop_limit:
return
time_step_targets_mask = targets_mask[:, time_step]
time_step_input_mask = input_mask[:, time_step]
early_stop = False
if time_step_targets_mask.shape[-1] == 1:
# Binary outputs. Mask means target == 1.
targets_mask = time_step_targets_mask.squeeze(axis=-1)
target_outputs = np.copy(time_step_outputs.squeeze(axis=-1))
target_outputs[~targets_mask] = 1 - target_outputs[~targets_mask]
target_outputs = target_outputs[time_step_input_mask]
if not all(target_outputs):
early_stop = True
else:
target_outputs = time_step_outputs[time_step_targets_mask]
target_outputs_leq_zero = target_outputs[time_step_input_mask] <= 0
if any(target_outputs_leq_zero):
# Rule out cases of all-zeros outputs, which return a uniform probability.
positive_outputs = time_step_outputs[time_step_input_mask] > 0
early_stop = np.any(positive_outputs[target_outputs_leq_zero])
if early_stop:
raise _InvalidNet(f"Early stop on step {time_step}")
def _calculate_inputs_product(weights: np.ndarray, inputs: np.ndarray) -> np.ndarray:
# Weighted inputs.
multiplication = np.multiply(weights, inputs.T)
# Product of weighted inputs.
return np.prod(multiplication, axis=1)
@numba.jit(
(types.Array(utils.NUMBA_FLOAT_DTYPE, ndim=1, layout="C"), types.int32),
nopython=True,
)
def _clip(arr, limit):
arr[arr < -limit] = -limit
arr[arr > limit] = limit
@numba.jit(
(
types.Array(utils.NUMBA_FLOAT_DTYPE, ndim=1, layout="C"),
types.Array(utils.NUMBA_FLOAT_DTYPE, ndim=2, layout="C", readonly=True),
),
nopython=True,
)
def _scalar_matmul_numba(weights, inputs) -> np.ndarray:
return (weights[0] * inputs).reshape((-1,))
@numba.jit(
(types.Array(utils.NUMBA_FLOAT_DTYPE, ndim=2, layout="C", readonly=True),),
nopython=True,
)
def _scalar_negative_numba(inputs: np.ndarray) -> np.ndarray:
return np.negative(inputs).reshape((-1,))
def _calculate_incoming_value_by_unit_type(
weights: np.ndarray, inputs: np.ndarray, unit_type: int
) -> np.ndarray:
if unit_type == SUMMATION_UNIT or inputs.shape[0] == 1:
if weights.shape[0] == 1:
if weights[0] == 1.0:
# TODO: Not using the faster reshape((-1,) since it returns a view which currently creates problems downstream.
return inputs.flatten()
if weights[0] == -1.0:
return _scalar_negative_numba(inputs)
return _scalar_matmul_numba(weights, inputs)
return np.matmul(weights, inputs)
elif unit_type == MULTIPLICATION_UNIT:
return _calculate_inputs_product(weights, inputs)
raise ValueError(f"Invalid unit type {unit_type}")
def _calculate_forward_inputs(
node: int,
node_values: Dict,
unit_type: int,
incoming_units: List[int],
incoming_weights: np.ndarray,
is_input_unit: bool,
):
if not incoming_units:
return
if len(incoming_units) == 1:
incoming_unit_values = node_values[incoming_units[0]].reshape((1, -1))
else:
incoming_unit_values = np.array([node_values[x] for x in incoming_units])
incoming_value = _calculate_incoming_value_by_unit_type(
incoming_weights, incoming_unit_values, unit_type
)
if is_input_unit:
# Only input units can have non-zero values here, intermediate nodes are guaranteed to be 0 because of topological order.
# Creating new value here (instead of +=) since input values are immutable.
if unit_type == SUMMATION_UNIT:
node_values[node] = node_values[node] + incoming_value
elif unit_type == MULTIPLICATION_UNIT:
node_values[node] = node_values[node] * incoming_value
else:
node_values[node] = incoming_value
def _calculate_recurrent_inputs(
node: int,
current_step_node_values: Dict,
previous_step_node_values: Dict,
incoming_recurrent_units: List[int],
incoming_recurrent_weights: np.ndarray,
unit_type: int,
batch_size: int,
):
if len(incoming_recurrent_units) == 1:
recurrent_slice = previous_step_node_values[
incoming_recurrent_units[0]
].reshape((1, -1))
else:
recurrent_vals = []
for x in incoming_recurrent_units:
try:
recurrent_vals.append(previous_step_node_values[x])
except KeyError:
recurrent_vals.append(np.zeros(batch_size, dtype=utils.FLOAT_DTYPE))
recurrent_slice = np.array(recurrent_vals)
incoming_value = _calculate_incoming_value_by_unit_type(
incoming_recurrent_weights, recurrent_slice, unit_type
)
# `ValueError` is raised if unit is an input unit, whose values are immutable, or for a unit
# with recurrent inputs but no forward inputs, in which case values are the default immutable zeros.
if unit_type == SUMMATION_UNIT:
try:
current_step_node_values[node] += incoming_value
except ValueError:
current_step_node_values[node] = (
current_step_node_values[node] + incoming_value
)
elif unit_type == MULTIPLICATION_UNIT:
try:
current_step_node_values[node] *= incoming_value
except ValueError:
current_step_node_values[node] = (
current_step_node_values[node] * incoming_value
)
else:
raise ValueError("Invalid unit type")
def _calculate_bias(node: int, node_bias: _Weight, node_values: Dict, unit_type: int):
node_values[node] = node_values[node] + _get_weight_real_value(node_bias)
def _apply_activation(node: int, activation: int, node_values: Dict):
node_values[node] = _ACTIVATIONS[activation](node_values[node])
def _get_incoming_units_and_weights(
net: Network,
topological_sort: Tuple[_Node, ...],
loop_edges: FrozenSet[_Edge],
recurrent_connections: bool,
) -> Tuple[Dict, Dict, Dict, Dict]:
incoming_forward_units_per_node = {}
incoming_forward_weights_per_node = {}
incoming_recurrent_units_per_node = {}
incoming_recurrent_weights_per_node = {}
for node in topological_sort:
incoming_forward_units_per_node[node] = list(
x
for x in net.reverse_forward_connections.get(node, [])
if (x, node) not in loop_edges
)
forward_weights = np.array(
[
_get_weight_real_value(net.forward_weights[(from_node, node)])
for from_node in incoming_forward_units_per_node[node]
],
dtype=utils.FLOAT_DTYPE,
)
incoming_forward_weights_per_node[node] = forward_weights
if not (
recurrent_connections
and node in net.reverse_recurrent_connections
and net.reverse_recurrent_connections[node]
):
continue
incoming_recurrent_units = net.reverse_recurrent_connections[node]
if incoming_recurrent_units:
incoming_recurrent_units_per_node[node] = list(
net.reverse_recurrent_connections[node]
)
recurrent_weights = np.array(
[
_get_weight_real_value(net.recurrent_weights[(from_node, node)])
for from_node in incoming_recurrent_units_per_node[node]
],
dtype=utils.FLOAT_DTYPE,
)
incoming_recurrent_weights_per_node[node] = recurrent_weights
return (
incoming_forward_units_per_node,
incoming_forward_weights_per_node,
incoming_recurrent_units_per_node,
incoming_recurrent_weights_per_node,
)
def predict_probabs(
net: Network,
input_sequence: np.ndarray,
recurrent_connections: bool,
truncate_large_values: bool,
softmax_outputs: bool,
inputs_per_time_step: Optional[Dict[int, np.ndarray]] = None,
input_mask: Optional[np.ndarray] = None,
targets_mask: Optional[np.ndarray] = None,
) -> np.ndarray:
sequence_outputs = feed_sequence(
net,
input_sequence,
recurrent_connections=recurrent_connections,
truncate_large_values=truncate_large_values,
inputs_per_time_step=inputs_per_time_step,
input_mask=input_mask,
targets_mask=targets_mask,
)
output_size = len(net.output_units_range)
if output_size == 1:
sequence_output_probabs = _binary_output_probabs(sequence_outputs)
else:
if softmax_outputs:
sequence_output_probabs = special.softmax(sequence_outputs, axis=-1)
else:
sequence_output_probabs = normalize_multiclass(sequence_outputs)
return sequence_output_probabs
def _truncate_large_values(
truncate_large_values: bool, node_values: Dict[int, np.ndarray], current_node: int
):
if (
truncate_large_values
# No point in clipping input values (array immutability indicates input values).
and node_values[current_node].flags.writeable
):
_clip(node_values[current_node], _NODE_VALUE_LIMIT)
def feed_sequence(
net: Network,
input_sequence: np.ndarray,
recurrent_connections: bool,
truncate_large_values: bool,
inputs_per_time_step: Optional[Dict[int, np.ndarray]] = None,
input_mask: Optional[np.ndarray] = None,
targets_mask: Optional[np.ndarray] = None,
) -> np.ndarray:
batch_size = input_sequence.shape[0]
sequence_length = input_sequence.shape[1]
loop_edges, topological_sort = topological_sort_through_time(net)
(
incoming_forward_units_per_node,
incoming_forward_weights_per_node,
incoming_recurrent_units_per_node,
incoming_recurrent_weights_per_node,
) = _get_incoming_units_and_weights(
net, topological_sort, loop_edges, recurrent_connections
)
sequence_outputs = []
previous_step_node_values = {}
initial_zeros = np.zeros(batch_size, dtype=utils.FLOAT_DTYPE)
initial_zeros.flags.writeable = False
for time_step in range(sequence_length):
node_values = {}
for input_unit in net.input_units_range:
if inputs_per_time_step:
input_val = inputs_per_time_step[input_unit][time_step]
else:
input_val = np.ascontiguousarray(
input_sequence[:, time_step, input_unit]
)
node_values[input_unit] = input_val
# Fill node values using dynamic programming based on topological sort.
for current_node in topological_sort:
if current_node not in node_values:
node_values[current_node] = initial_zeros
_calculate_forward_inputs(
node=current_node,
node_values=node_values,
unit_type=net.unit_types[current_node],
incoming_units=incoming_forward_units_per_node[current_node],
incoming_weights=incoming_forward_weights_per_node[current_node],
is_input_unit=current_node in net.input_units_range,
)
if (
recurrent_connections
and time_step > 0
and current_node in incoming_recurrent_units_per_node
):
_calculate_recurrent_inputs(
node=current_node,
current_step_node_values=node_values,
previous_step_node_values=previous_step_node_values,
incoming_recurrent_units=incoming_recurrent_units_per_node[
current_node
],
incoming_recurrent_weights=incoming_recurrent_weights_per_node[
current_node
],
unit_type=net.unit_types[current_node],
batch_size=batch_size,
)
if current_node in net.biases:
_calculate_bias(
node=current_node,
node_bias=net.biases[current_node],
node_values=node_values,
unit_type=net.unit_types[current_node],
)
_truncate_large_values(truncate_large_values, node_values, current_node)
_apply_activation(current_node, net.activations[current_node], node_values)
current_time_step_outputs = np.array(
[node_values[x] for x in net.output_units_range]
).T
sequence_outputs.append(current_time_step_outputs)
_try_early_stop(
sequence_length=sequence_length,
targets_mask=targets_mask,
input_mask=input_mask,
time_step=time_step,
time_step_outputs=current_time_step_outputs,
)
previous_step_node_values = node_values
return np.array(sequence_outputs).swapaxes(0, 1)
def feed_language_model(
net: Network,
symbol_to_class: Dict[Text, int],
sample: bool,
prefix: Tuple[Text, ...],
end_of_sequence_class: int,
softmax_outputs: bool,
truncate_large_values: bool,
) -> Tuple[Tuple[int, ...], Tuple[int, ...], np.ndarray]:
prefix_inputs = np.zeros((1, len(prefix), len(symbol_to_class)))
for i, symbol in enumerate(prefix):
prefix_inputs[0, i, symbol_to_class[symbol]] = 1.0
inputs = np.copy(prefix_inputs)
output_classes = [symbol_to_class[x] for x in prefix]
while True:
outputs = predict_probabs(
net,
inputs,
recurrent_connections=True,
truncate_large_values=truncate_large_values,
softmax_outputs=softmax_outputs,
)
if sample:
next_class = np.random.choice(len(symbol_to_class), p=outputs[0, -1])
else:
next_class = np.argmax(outputs[0, -1])
output_classes.append(next_class)
if next_class == end_of_sequence_class:
break
next_step_input = np.zeros((1, 1, outputs.shape[-1]))
next_step_input[0, 0, next_class] = 1.0
inputs = np.concatenate([inputs, next_step_input], axis=1)
input_classes = tuple(np.argmax(inputs, axis=-1).squeeze(axis=0))
return (
tuple(output_classes),
input_classes,
np.concatenate([prefix_inputs[:, 1:], outputs[:, len(prefix) - 1 :]], axis=1),
)
def _calculate_accuracy(
predicted_classes: np.ndarray,
target_classes: np.ndarray,
input_mask: Optional[np.ndarray],
) -> float:
if input_mask is not None:
predicted_classes = predicted_classes[input_mask]
target_classes = target_classes[input_mask]
correct_predictions = predicted_classes == target_classes
if logging.getLogger().level == logging.DEBUG:
logging.debug(
f"Sequences with wrong predictions: {list(set(np.where(~correct_predictions)[0]))}"
)
return (np.sum(correct_predictions) / predicted_classes.size).item()
def calculate_deterministic_accuracy(
net: Network, corpus: corpora.Corpus, config: configuration.SimulationConfig
) -> float:
output_probabs = predict_probabs(
net,
input_sequence=corpus.input_sequence,
recurrent_connections=config.recurrent_connections,
truncate_large_values=config.truncate_large_values,
softmax_outputs=config.softmax_outputs,
inputs_per_time_step=corpus.input_values_per_time_step,
input_mask=corpus.input_mask,
targets_mask=corpus.targets_mask,
)
target_sequence = corpus.target_sequence
deterministic_steps_mask = corpus.deterministic_steps_mask
rows_repeated_by_weights = None
if corpus.sample_weights:
rows_repeated_by_weights = list(
itertools.chain(
*[[row] * weight for row, weight in enumerate(corpus.sample_weights)]
)
)
output_probabs = output_probabs[rows_repeated_by_weights]
deterministic_steps_mask = deterministic_steps_mask[rows_repeated_by_weights]
target_sequence = target_sequence[rows_repeated_by_weights]
deterministic_probabs = output_probabs[deterministic_steps_mask]
predicted_classes = deterministic_probabs.argmax(axis=-1)
target_classes = target_sequence[deterministic_steps_mask].argmax(axis=-1)
original_rows = np.where(deterministic_steps_mask)[0]
rows_with_errors = np.where(predicted_classes != target_classes)[0]
original_rows_with_errors = frozenset([original_rows[i] for i in rows_with_errors])
if rows_repeated_by_weights:
original_rows_with_errors = frozenset(
rows_repeated_by_weights[i] for i in original_rows_with_errors
)
if original_rows_with_errors:
logging.debug(
f"Deterministic accuracy: rows with errors: {original_rows_with_errors}"
)