-
Notifications
You must be signed in to change notification settings - Fork 32
/
core.py
3919 lines (3307 loc) · 130 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Core contraction tree data structure and methods."""
import collections
import functools
import itertools
import math
import operator
import warnings
from dataclasses import dataclass
from typing import Optional
from autoray import do
from .contract import make_contractor
from .hypergraph import get_hypergraph
from .parallel import (
can_scatter,
maybe_leave_pool,
maybe_rejoin_pool,
parse_parallel_arg,
scatter,
submit,
)
from .pathfinders.path_simulated_annealing import (
parallel_temper_tree,
simulated_anneal_tree,
)
from .plot import (
plot_contractions,
plot_contractions_alt,
plot_hypergraph,
plot_tree_circuit,
plot_tree_flat,
plot_tree_ring,
plot_tree_rubberband,
plot_tree_span,
plot_tree_tent,
)
from .scoring import (
DEFAULT_COMBO_FACTOR,
CompressedStatsTracker,
get_score_fn,
)
from .utils import (
MaxCounter,
compute_size_by_dict,
deprecated,
get_rng,
get_symbol,
groupby,
inputs_output_to_eq,
interleave,
is_valid_node,
node_from_seq,
node_from_single,
node_get_single_el,
node_supremum,
oset,
prod,
unique,
)
def cached_node_property(name):
"""Decorator for caching information about nodes."""
def wrapper(meth):
@functools.wraps(meth)
def getter(self, node):
try:
return self.info[node][name]
except KeyError:
self.info[node][name] = value = meth(self, node)
return value
return getter
return wrapper
def union_it(bs):
"""Non-variadic version of various set type unions."""
b0, *bs = bs
return b0.union(*bs)
def legs_union(legs_seq):
"""Combine a sequence of legs into a single set of legs, summing their
appearances.
"""
new_legs, *rem_legs = legs_seq
new_legs = new_legs.copy()
for legs in rem_legs:
for ix, ix_count in legs.items():
new_legs[ix] = new_legs.get(ix, 0) + ix_count
return new_legs
def legs_without(legs, ind):
"""Discard ``ind`` from legs to create a new set of legs."""
new_legs = legs.copy()
new_legs.pop(ind, None)
return new_legs
def get_with_default(k, obj, default):
return obj.get(k, default)
@dataclass(order=True, frozen=True)
class SliceInfo:
inner: bool
ind: str
size: int
project: Optional[int]
@property
def sliced_range(self):
if self.project is None:
return range(self.size)
else:
return [self.project]
def get_slice_strides(sliced_inds):
"""Compute the 'strides' given the (ordered) dictionary of sliced indices."""
slice_infos = list(sliced_inds.values())
nsliced = len(slice_infos)
strides = [1] * nsliced
# backwards cumulative product
for i in range(nsliced - 2, -1, -1):
strides[i] = strides[i + 1] * slice_infos[i + 1].size
return strides
class ContractionTree:
"""Binary tree representing a tensor network contraction.
Parameters
----------
inputs : sequence of str
The list of input tensor's indices.
output : str
The output indices.
size_dict : dict[str, int]
The size of each index.
track_childless : bool, optional
Whether to dynamically keep track of which nodes are childless. Useful
if you are 'divisively' building the tree.
track_flops : bool, optional
Whether to dynamically keep track of the total number of flops. If
``False`` You can still compute this once the tree is complete.
track_write : bool, optional
Whether to dynamically keep track of the total number of elements
written. If ``False`` You can still compute this once the tree is
complete.
track_size : bool, optional
Whether to dynamically keep track of the largest tensor so far. If
``False`` You can still compute this once the tree is complete.
objective : str or Objective, optional
An default objective function to use for further optimization and
scoring, for example reconfiguring or computing the combo cost. If not
supplied the default is to create a flops objective when needed.
Attributes
----------
children : dict[node, tuple[node]]
Mapping of each node to two children.
info : dict[node, dict]
Information about the tree nodes. The key is the set of inputs (a
set of inputs indices) the node contains. Or in other words, the
subgraph of the node. The value is a dictionary to cache information
about effective 'leg' indices, size, flops of formation etc.
"""
def __init__(
self,
inputs,
output,
size_dict,
track_childless=False,
track_flops=False,
track_write=False,
track_size=False,
objective=None,
):
self.inputs = inputs
self.output = output
if isinstance(self.inputs[0], set) or isinstance(self.output, set):
warnings.warn(
"The inputs or output of this tree are not ordered."
"Costs will be accurate but actually contracting requires "
"ordered indices corresponding to array axes."
)
if not isinstance(next(iter(size_dict.values()), 1), int):
# make sure we are working with python integers to avoid overflow
# comparison errors with inf etc.
self.size_dict = {k: int(v) for k, v in size_dict.items()}
else:
self.size_dict = size_dict
self.N = len(self.inputs)
# the index representation for each input is an ordered mapping of
# each index to the number of times it has appeared on children. By
# also tracking the total number of appearances one can efficiently
# and locally compute which indices should be kept or contracted
self.appearances = {}
for term in self.inputs:
for ix in term:
self.appearances[ix] = self.appearances.get(ix, 0) + 1
# adding output appearances ensures these are never contracted away,
# N.B. if after this step every appearance count is exactly 2,
# then there are no 'hyper' indices in the contraction
for ix in self.output:
self.appearances[ix] = self.appearances.get(ix, 0) + 1
#
self.preprocessing = {}
# mapping of parents to children - the core binary tree object
self.children = {}
# information about all the nodes
self.info = {}
# add constant nodes: the leaves
for leaf in self.gen_leaves():
self._add_node(leaf)
# and the root or top node
self.root = node_supremum(self.N)
self._add_node(self.root)
# whether to keep track of dangling nodes/subgraphs
self.track_childless = track_childless
if self.track_childless:
# the set of dangling nodes
self.childless = oset([self.root])
# running largest_intermediate and total flops
self._track_flops = track_flops
if track_flops:
self._flops = 0
self._track_write = track_write
if track_write:
self._write = 0
self._track_size = track_size
if track_size:
self._sizes = MaxCounter()
# container for caching subtree reconfiguration condidates
self.already_optimized = dict()
# info relating to slicing (base constructor is always unsliced)
self.multiplicity = 1
self.sliced_inds = {}
self.sliced_inputs = frozenset()
# cache for compiled contraction cores
self.contraction_cores = {}
# a default objective function useful for
# further optimization and scoring
self._default_objective = objective
def set_state_from(self, other):
"""Set the internal state of this tree to that of ``other``."""
# immutable or never mutated properties
for attr in (
"appearances",
"inputs",
"multiplicity",
"N",
"output",
"root",
"size_dict",
"sliced_inputs",
"_default_objective",
):
setattr(self, attr, getattr(other, attr))
# mutable properties
for attr in (
"children",
"contraction_cores",
"sliced_inds",
"preprocessing",
):
setattr(self, attr, getattr(other, attr).copy())
# dicts of mutable
for attr in ("info", "already_optimized"):
setattr(
self,
attr,
{k: v.copy() for k, v in getattr(other, attr).items()},
)
self.track_childless = other.track_childless
if other.track_childless:
self.childless = other.childless.copy()
self._track_flops = other._track_flops
if other._track_flops:
self._flops = other._flops
self._track_write = other._track_write
if other._track_write:
self._write = other._write
self._track_size = other._track_size
if other._track_size:
self._sizes = other._sizes.copy()
def copy(self):
"""Create a copy of this ``ContractionTree``."""
tree = object.__new__(self.__class__)
tree.set_state_from(self)
return tree
def set_default_objective(self, objective):
"""Set the objective function for this tree."""
self._default_objective = get_score_fn(objective)
def get_default_objective(self):
"""Get the objective function for this tree."""
if self._default_objective is None:
self._default_objective = get_score_fn("flops")
return self._default_objective
def get_default_combo_factor(self):
"""Get the default combo factor for this tree."""
objective = self.get_default_objective()
try:
return objective.factor
except AttributeError:
return DEFAULT_COMBO_FACTOR
@property
def nslices(self):
"""Simple alias for how many independent contractions this tree
represents overall.
"""
return self.multiplicity
@property
def nchunks(self):
"""The number of 'chunks' - determined by the number of sliced output
indices.
"""
return prod(
si.size for si in self.sliced_inds.values() if not si.inner
)
def node_to_terms(self, node):
"""Turn a node -- a frozen set of ints -- into the corresponding terms
-- a sequence of sets of str corresponding to input indices.
"""
return (self.get_legs(node_from_single(i)) for i in node)
def gen_leaves(self):
"""Generate the nodes representing leaves of the contraction tree, i.e.
of size 1 each corresponding to a single input tensor.
"""
return map(node_from_single, range(self.N))
def get_incomplete_nodes(self):
"""Get the set of current nodes that have no children and the set of
nodes that have no parents. These are the 'childless' and 'parentless'
nodes respectively, that need to be contracted to complete the tree.
The parentless nodes are grouped into the childless nodes that contain
them as subgraphs.
Returns
-------
groups : dict[frozenet[int], list[frozenset[int]]]
A mapping of childless nodes to the list of parentless nodes are
beneath them.
See Also
--------
autocomplete
"""
childless = dict.fromkeys(
node
for node in self.info
# start wth all but leaves
if len(node) != 1
)
parentless = dict.fromkeys(
node
for node in self.info
# start with all but root
if len(node) != self.N
)
for p, (l, r) in self.children.items():
parentless.pop(l)
parentless.pop(r)
childless.pop(p)
groups = {node: [] for node in childless}
for node in parentless:
# get the smallest node that contains this node
ancestor = min(
filter(node.issubset, childless),
key=len,
)
groups[ancestor].append(node)
return groups
def autocomplete(self, **contract_opts):
"""Contract all remaining node groups (as computed by
``tree.get_incomplete_nodes``) in the tree to complete it.
Parameters
----------
contract_opts
Options to pass to ``tree.contract_nodes``.
See Also
--------
get_incomplete_nodes, contract_nodes
"""
groups = self.get_incomplete_nodes()
for _, parentless_subnodes in groups.items():
self.contract_nodes(parentless_subnodes, **contract_opts)
@classmethod
def from_path(
cls,
inputs,
output,
size_dict,
*,
path=None,
ssa_path=None,
autocomplete="auto",
check=False,
**kwargs,
):
"""Create a (completed) ``ContractionTree`` from the usual inputs plus
a standard contraction path or 'ssa_path' - you need to supply one.
Parameters
----------
inputs : Sequence[Sequence[str]]
The input indices of each tensor, as single unicode characters.
output : Sequence[str]
The output indices.
size_dict : dict[str, int]
The size of each index.
path : Sequence[Sequence[int]], optional
The contraction path, a sequence of pairs of tensor ids to
contract. The ids are linear indices into the list of temporary
tensors, which are recycled as each contraction pops a pair and
appends the result. This or ``ssa_path`` must be supplied.
ssa_path : Sequence[Sequence[int]], optional
The contraction path, a sequence of pairs of indices to contract.
The indices are single use, as if the result of each contraction is
appended to the end of the list of temporary tensors without
popping. This or ``path`` must be supplied.
autocomplete : "auto" or bool, optional
Whether to automatically complete the path, i.e. contract all
remaining nodes. If "auto" then a warning is issued if the path is
not complete.
check : bool, optional
Whether to perform some basic checks while creating the contraction
nodes.
Returns
-------
ContractionTree
"""
if int(path is None) + int(ssa_path is None) != 1:
raise ValueError(
"Exactly one of ``path`` or ``ssa_path`` must be " "supplied."
)
if ssa_path is not None:
path = ssa_path
tree = cls(inputs, output, size_dict, **kwargs)
if ssa_path is not None:
# ssa path (single use ids)
nodes = dict(enumerate(tree.gen_leaves()))
ssa = len(nodes)
for p in path:
merge = [nodes.pop(i) for i in p]
nodes[ssa] = tree.contract_nodes(merge, check=check)
ssa += 1
nodes = nodes.values()
else:
# regular path ('recycled' ids)
nodes = list(tree.gen_leaves())
for p in path:
merge = [nodes.pop(i) for i in sorted(p, reverse=True)]
nodes.append(tree.contract_nodes(merge, check=check))
if len(nodes) > 1 and autocomplete:
if autocomplete == "auto":
# warn that we are completing
warnings.warn(
"Path was not complete - contracting all remaining. "
"You can silence this warning with `complete=True`."
)
tree.contract_nodes(nodes, check=check)
return tree
@classmethod
def from_info(cls, info, **kwargs):
"""Create a ``ContractionTree`` from an ``opt_einsum.PathInfo`` object."""
return cls.from_path(
inputs=info.input_subscripts.split(","),
output=info.output_subscript,
size_dict=info.size_dict,
path=info.path,
**kwargs,
)
@classmethod
def from_eq(cls, eq, size_dict, **kwargs):
"""Create a empty ``ContractionTree`` directly from an equation and set
of shapes.
Parameters
----------
eq : str
The einsum string equation.
size_dict : dict[str, int]
The size of each index.
"""
lhs, output = eq.split("->")
inputs = lhs.split(",")
return cls(inputs, output, size_dict, **kwargs)
def get_eq(self):
"""Get the einsum equation corresponding to this tree. Note that this
is the total (or original) equation, so includes indices which have
been sliced.
Returns
-------
eq : str
"""
return inputs_output_to_eq(self.inputs, self.output)
def get_shapes(self):
"""Get the shapes of the input tensors corresponding to this tree.
Returns
-------
shapes : tuple[tuple[int]]
"""
return tuple(
tuple(self.size_dict[ix] for ix in term) for term in self.inputs
)
def get_inputs_sliced(self):
"""Get the input indices corresponding to a single slice of this tree,
i.e. with sliced indices removed.
Returns
-------
inputs : tuple[tuple[str]]
"""
return tuple(
tuple(ix for ix in term if ix not in self.sliced_inds)
for term in self.inputs
)
def get_output_sliced(self):
"""Get the output indices corresponding to a single slice of this tree,
i.e. with sliced indices removed.
Returns
-------
output : tuple[str]
"""
return tuple(ix for ix in self.output if ix not in self.sliced_inds)
def get_eq_sliced(self):
"""Get the einsum equation corresponding to a single slice of this
tree, i.e. with sliced indices removed.
Returns
-------
eq : str
"""
return inputs_output_to_eq(
self.get_inputs_sliced(), self.get_output_sliced()
)
def get_shapes_sliced(self):
"""Get the shapes of the input tensors corresponding to a single slice
of this tree, i.e. with sliced indices removed.
Returns
-------
shapes : tuple[tuple[int]]
"""
return tuple(
tuple(
self.size_dict[ix] for ix in term if ix not in self.sliced_inds
)
for term in self.inputs
)
@classmethod
def from_edge_path(
cls, edge_path, inputs, output, size_dict, check=False, **kwargs
):
"""Create a ``ContractionTree`` from an edge elimination ordering."""
tree = cls(inputs, output, size_dict, **kwargs)
nodes = list(tree.gen_leaves())
for e in edge_path:
# filter out the subgraph induced by edge `e` (generally a pair)
new_terms, merge = [], []
for node in nodes:
term = union_it(tree.node_to_terms(node))
if e in term:
merge.append(node)
else:
new_terms.append(node)
# contract the subgraph
if merge:
nodes = new_terms + [tree.contract_nodes(merge, check=check)]
# make sure we are generating a full contraction tree
nt = len(nodes)
if nt > 1:
# this seems to happen when the initial contraction contains a
# scalar? Or disconnected subgraphs?
warnings.warn(
f"Ended up with {nt} nodes - contracting all remaining."
)
tree.contract_nodes(nodes, check=check)
return tree
def _add_node(self, node, check=False):
if check:
if len(self.info) > 2 * self.N - 1:
raise ValueError("There are too many children already.")
if len(self.children) > self.N - 1:
raise ValueError("There are too many branches already.")
if not is_valid_node(node):
raise ValueError("{} is not a valid node.".format(node))
self.info.setdefault(node, dict())
def _remove_node(self, node):
"""Remove ``node`` from this tree and update the flops and maximum size
if tracking them respectively, as well as input pre-processing.
"""
node_extent = len(node)
if node_extent == 1:
# leaf nodes should always exist
self.info[node].clear()
# input: remove any associated preprocessing
self.preprocessing.pop(node_get_single_el(node), None)
else:
# only non-leaf nodes contribute to size, flops and write
if self._track_size:
self._sizes.discard(self.get_size(node))
if self._track_flops:
self._flops -= self.get_flops(node)
if self._track_write:
self._write -= self.get_size(node)
del self.children[node]
if node_extent == self.N:
# root node should always exist
self.info[node].clear()
else:
del self.info[node]
def compute_leaf_legs(self, i):
"""Compute the effective 'outer' indices for the ith input tensor. This
is not always simply the ith input indices, due to A) potential slicing
and B) potential preprocessing.
"""
# indices of input tensor (after slicing which is done immediately)
if self.sliced_inds:
term = tuple(
ix for ix in self.inputs[i] if ix not in self.sliced_inds
)
else:
term = self.inputs[i]
legs = {}
for ix in term:
legs[ix] = legs.get(ix, 0) + 1
# check for single term simplifications, these are treated as a simple
# preprocessing step that only is taken into account during actual
# contraction, and are not represented in the binary tree
# N.B. need to compute simplifiability *after* slicing
is_simplifiable = (
# repeated indices (diag or traces)
(len(term) != len(legs))
or
# reduced indices (are summed immediately)
any(
ix_count == self.appearances[ix]
for ix, ix_count in legs.items()
)
)
if is_simplifiable:
# compute the simplified legs -> the new effective input legs
legs = {
ix: ix_count
for ix, ix_count in legs.items()
if ix_count != self.appearances[ix]
}
# add a preprocessing step to the list of contractions
eq = inputs_output_to_eq((term,), legs, canonicalize=True)
self.preprocessing[i] = eq
return legs
def has_preprocessing(self):
# touch all inputs legs, since preprocessing is lazily computed
for node in self.gen_leaves():
self.get_legs(node)
return bool(self.preprocessing)
@cached_node_property("legs")
def get_legs(self, node):
"""Get the effective 'outer' indices for the collection of tensors
in ``node``.
"""
node_extent = len(node)
if node_extent == 1:
# leaf legs are inputs
return self.compute_leaf_legs(node_get_single_el(node))
elif node_extent == self.N:
# root legs are output, after slicing
# n.b. the index counts are irrelevant for the output
return {ix: 0 for ix in self.output if ix not in self.sliced_inds}
try:
involved = self.get_involved(node)
except KeyError:
involved = legs_union(self.node_to_terms(node))
return {
ix: ix_count
for ix, ix_count in involved.items()
if ix_count < self.appearances[ix]
}
@cached_node_property("involved")
def get_involved(self, node):
"""Get all the indices involved in the formation of subgraph ``node``."""
if len(node) == 1:
return {}
sub_legs = map(self.get_legs, self.children[node])
return legs_union(sub_legs)
@cached_node_property("size")
def get_size(self, node):
"""Get the tensor size of ``node``."""
return compute_size_by_dict(self.get_legs(node), self.size_dict)
@cached_node_property("flops")
def get_flops(self, node):
"""Get the FLOPs for the pairwise contraction that will create
``node``.
"""
if len(node) == 1:
return 0
involved = self.get_involved(node)
return compute_size_by_dict(involved, self.size_dict)
@cached_node_property("can_dot")
def get_can_dot(self, node):
"""Get whether this contraction can be performed as a dot product (i.e.
with ``tensordot``), or else requires ``einsum``, as it has indices
that don't appear exactly twice in either the inputs or the output.
"""
l, r = self.children[node]
sp, sl, sr = map(self.get_legs, (node, l, r))
srl_symmdiff = sl.copy()
for ix, ix_count in sr.items():
if ix in srl_symmdiff:
srl_symmdiff.pop(ix)
else:
srl_symmdiff[ix] = ix_count
return srl_symmdiff == sp
@cached_node_property("inds")
def get_inds(self, node):
"""Get the indices of this node - an ordered string version of
``get_legs`` that starts with ``tree.inputs`` and maintains the order
they appear in each contraction 'ABC,abc->ABCabc', to match tensordot.
"""
# NB: self.inputs and self.output contain the full (unsliced) indices
# thus we filter even the input legs and output legs
if len(node) in (1, self.N):
return "".join(self.get_legs(node))
legs = self.get_legs(node)
l_inds, r_inds = map(self.get_inds, self.children[node])
# the filter here takes care of contracted indices
return "".join(
unique(filter(legs.__contains__, itertools.chain(l_inds, r_inds)))
)
@cached_node_property("tensordot_axes")
def get_tensordot_axes(self, node):
"""Get the ``axes`` arg for a tensordot ocontraction that produces
``node``. The pairs are sorted in order of appearance on the left
input.
"""
l_inds, r_inds = map(self.get_inds, self.children[node])
l_axes, r_axes = [], []
for i, ind in enumerate(l_inds):
j = r_inds.find(ind)
if j != -1:
l_axes.append(i)
r_axes.append(j)
return tuple(l_axes), tuple(r_axes)
@cached_node_property("tensordot_perm")
def get_tensordot_perm(self, node):
"""Get the permutation required, if any, to bring the tensordot output
of this nodes contraction into line with ``self.get_inds(node)``.
"""
l_inds, r_inds = map(self.get_inds, self.children[node])
# the target output inds
p_inds = self.get_inds(node)
# the tensordot output inds
td_inds = "".join(sorted(p_inds, key=f"{l_inds}{r_inds}".find))
if td_inds == p_inds:
return None
return tuple(map(td_inds.find, p_inds))
@cached_node_property("einsum_eq")
def get_einsum_eq(self, node):
"""Get the einsum string describing the contraction that produces
``node``, unlike ``get_inds`` the characters are mapped into [a-zA-Z],
for compatibility with ``numpy.einsum`` for example.
"""
l, r = self.children[node]
l_inds, r_inds, p_inds = map(self.get_inds, (l, r, node))
# we need to map any extended unicode characters into ascii
char_mapping = {
ord(ix): get_symbol(i)
for i, ix in enumerate(unique(itertools.chain(l_inds, r_inds)))
}
return f"{l_inds},{r_inds}->{p_inds}".translate(char_mapping)
def get_centrality(self, node):
try:
return self.info[node]["centrality"]
except KeyError:
self.compute_centralities()
return self.info[node]["centrality"]
def total_flops(self, dtype=None, log=None):
"""Sum the flops contribution from every node in the tree.
Parameters
----------
dtype : {'float', 'complex', None}, optional
Scale the answer depending on the assumed data type.
"""
if self._track_flops:
C = self.multiplicity * self._flops
else:
self._flops = 0
for node, _, _ in self.traverse():
self._flops += self.get_flops(node)
self._track_flops = True
C = self.multiplicity * self._flops
if dtype is None:
pass
elif "float" in dtype:
C *= 2
elif "complex" in dtype:
C *= 4
else:
raise ValueError(f"Unknown dtype {dtype}")
if log is not None:
C = math.log(C, log)
return C
def total_write(self):
"""Sum the total amount of memory that will be created and operated on."""
if not self._track_write:
self._write = 0
for node, _, _ in self.traverse():
self._write += self.get_size(node)
self._track_write = True
return self.multiplicity * self._write
def combo_cost(self, factor=DEFAULT_COMBO_FACTOR, combine=sum, log=None):
t = 0
for p in self.children:
f = self.get_flops(p)
w = self.get_size(p)
t += combine((f, factor * w))
t *= self.multiplicity
if log is not None:
t = math.log(t, log)
return t
total_cost = combo_cost
def max_size(self, log=None):
"""The size of the largest intermediate tensor."""
if self.N == 1:
return self.get_size(self.root)
if not self._track_size:
self._sizes = MaxCounter()
for node, _, _ in self.traverse():
self._sizes.add(self.get_size(node))
self._track_size = True
size = self._sizes.max()
if log is not None:
size = math.log(size, log)
return size
def peak_size(self, order=None, log=None):
"""Get the peak concurrent size of tensors needed - this depends on the
traversal order, i.e. the exact contraction path, not just the
contraction tree.
"""
tot_size = sum(self.get_size(node) for node in self.gen_leaves())
peak = tot_size
for p, l, r in self.traverse(order=order):
tot_size += self.get_size(p)
# measure peak assuming we need both inputs and output
peak = max(peak, tot_size)
tot_size -= self.get_size(l)
tot_size -= self.get_size(r)
if log is not None:
peak = math.log(peak, log)
return peak
def contract_stats(self, force=False):
"""Simulteneously compute the total flops, write and size of the
contraction tree. This is more efficient than calling each of the
individual methods separately. Once computed, each quantity is then
automatically tracked.
Returns
-------
stats : dict[str, int]
The total flops, write and size.
"""
if force or not (
self._track_flops and self._track_write and self._track_size
):
self._flops = self._write = 0
self._sizes = MaxCounter()
for node, _, _ in self.traverse():
self._flops += self.get_flops(node)
node_size = self.get_size(node)
self._write += node_size
self._sizes.add(node_size)
self._track_flops = self._track_write = self._track_size = True
return {