-
Notifications
You must be signed in to change notification settings - Fork 9
/
core.py
1805 lines (1420 loc) · 49.3 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 lazy array functionality.
"""
import operator
import threading
import functools
import itertools
import contextlib
import collections
from ..autoray import (
shape,
astype,
get_dtype_name,
get_lib_fn,
infer_backend,
multi_class_priorities,
register_backend,
register_function,
tree_flatten,
tree_map,
tree_iter,
tree_unflatten,
)
from .draw import (
plot_graph,
plot_circuit,
plot_history_size_footprint,
plot_history_functions,
plot_history_stats,
)
_EMPTY_DICT = {}
get_depth = operator.attrgetter("_depth")
get_data = operator.attrgetter("_data")
# ------------------------ traversal and computation ------------------------ #
def is_lazy_array(x):
"""Check if ``x`` is a lazy array."""
return isinstance(x, LazyArray)
def to_queue(lz):
"""Parse a pytree of lazy arrays into a queue of nodes, sorted by depth.
This is useful for traversing the computational graph of multiple outputs
in topological order.
"""
if isinstance(lz, LazyArray):
return [lz]
queue = tree_flatten(lz, is_lazy_array)
queue.sort(key=get_depth)
return queue
def descend(lz):
"""Generate each unique computational node. Use ``ascend`` if you need to
visit children before parents.
Parameters
----------
lz : pytree of LazyArray
The output node(s) of the computational graph to descend.
Yields
------
LazyArray
"""
queue = to_queue(lz)
seen = set()
while queue:
node = queue.pop()
nid = id(node)
if nid not in seen:
yield node
queue.extend(node._deps)
seen.add(nid)
def ascend(lz):
"""Generate each unique computational node, from leaves to root. I.e. a
topological ordering of the computational graph. Moreover, the nodes
are visited 'deepest first'.
Parameters
----------
lz : pytree of LazyArray
The output node(s) of the computational graph to ascend to.
Yields
------
LazyArray
"""
queue = to_queue(lz)
seen = set()
ready = set()
while queue:
node = queue[-1]
need_to_visit = [c for c in node._deps if id(c) not in ready]
if need_to_visit:
need_to_visit.sort(key=get_depth)
queue.extend(need_to_visit)
else:
node = queue.pop()
nid = id(node)
ready.add(nid)
if nid not in seen:
yield node
seen.add(nid)
def compute(lz):
"""Compute the value of one or more lazy arrays. All nodes that are
computed clear any references to their function, arguments and
dependencies, and store the result in their ``_data`` attribute.
Parameters
----------
lz : pytree of LazyArray
The output node(s) of the computational graph to compute.
Returns
-------
array or tuple of array
The computed value(s) of the lazy array(s).
"""
for node in ascend(lz):
node._materialize()
return tree_map(get_data, lz, is_lazy_array)
def compute_constants(lz, variables):
"""Fold constant arrays - everything not dependent on ``variables`` -
into the graph.
Parameters
----------
lz : pytree of LazyArray
The output node(s) of the computational graph.
variables : pytree of LazyArray
Nodes that should be treated as variable. I.e. any descendants will
not be folded into the graph.
"""
variables = set(tree_iter(variables, is_lazy_array))
# must ascend
for node in ascend(lz):
if not any(c in variables for c in node._deps):
# can fold
node._materialize()
else:
# inherit variable status
variables.add(node)
def get_source(lz, params=None):
"""Write the source code of an unravelled version of the computational
graph, injecting required runtime objects into ``params``.
Parameters
----------
lz : LazyArray or sequence of LazyArray
The output node(s) of the computational graph to write the source code
for. Their corresponding label is ``f"x{id(node)}"`` in the
source code.
Returns
-------
str
The source code of the computational graph, suitable for ``exec``.
"""
if params is None:
# locals space mapping LazyArray names to values
params = {}
delete_checked = set()
s = [] # source code lines
for node in reversed(tuple(ascend(lz))):
# when *descending*, the first encounter of a node is the
# *last* time it is referenced in forward pass -> delete,
# need to do this for GC since running in single big function
for c in node._deps:
if c not in delete_checked:
if c._deps:
# is an intermediate - safe to delete. While we could
# delete input variables, we want to keep input *constants*
s.append(f"del x{id(c)}")
delete_checked.add(c)
if node._data is None:
# create the array via computation
s.append(node.as_string(params))
else:
# inject the already computed data as constant
params[f"x{id(node)}"] = node._data
# reverse (ascend) into source code
return "\n".join(reversed(s))
class Function:
"""Get a compiled (by python ``compile``), function that performs the
computational graph corresponding to ``inputs`` -> ``outputs``. The
signature of the function is ``func(input_arrays) -> output_arrays``. As an
intermediate step, the computational graph is traced to a flattened source
code string.
Parameters
----------
inputs : pytree of LazyArray
The input node(s) of the computational graph.
outputs : pytree of LazyArray
The output node(s) of the computational graph.
fold_constants : bool, optional
If True, fold constant arrays (those with no dependence on ``inputs``)
into the graph ahead of compile.
See Also
--------
get_source, compute
"""
__slots__ = (
"_in_names",
"_out_names",
"_out_tree",
"_source",
"_code",
"_locals",
)
def __init__(self, inputs, outputs, fold_constants=True):
if fold_constants:
# compute everything not dependent on inputs
compute_constants(outputs, variables=inputs)
# write source and populate locals mapping that function will run
# under, locals will include the functions and other constant objects
self._locals = {}
self._source = get_source(outputs, params=self._locals)
# compile source
self._code = compile(
source=self._source,
filename="<string>",
mode="exec",
optimize=1,
)
# get names to inject and extract arrays into and from locals
self._in_names = tuple(f"x{id(v)}" for v in tree_iter(inputs))
outs_flat, self._out_tree = tree_flatten(outputs, get_ref=True)
self._out_names = tuple(f"x{id(v)}" for v in outs_flat)
def __call__(self, *args):
# this allows any matching zipped tree
for name, array in zip(self._in_names, tree_iter(args)):
self._locals[name] = array
# run the byte-compiled function with the updated locals
exec(self._code, None, self._locals)
# remove inputs from locals
for name in self._in_names:
del self._locals[name]
# pop outputs from locals
outs = tuple(self._locals.pop(name) for name in self._out_names)
# return the outputs in the original tree structure
return tree_unflatten(outs, self._out_tree)
def __getstate__(self):
# can't pickle the code object -> recompile in setstate
return (
self._in_names,
self._out_names,
self._out_tree,
self._source,
self._locals,
)
def __setstate__(self, state):
(
self._in_names,
self._out_names,
self._out_tree,
self._source,
self._locals,
) = state
# recompile the source
self._code = compile(
source=self._source,
filename="<string>",
mode="exec",
optimize=1,
)
def print_source(self):
"""Print the source code of the compiled function."""
print(self._source)
def __repr__(self):
insig = f"{len(self._in_names)} input(s)"
outsig = f"{len(self._out_names)} output(s) "
return f"<Function({insig}) -> {outsig}>"
# --------------------------- computational nodes --------------------------- #
class Placeholder:
"""A singleton object to use as a placeholder in a LazyArray."""
__slots__ = ()
def __repr__(self):
return "Placeholder"
PLACEHOLDER = Placeholder()
class LazyArray:
"""A lazy array representing a node in a computational graph.
Parameters
----------
backend : str
The backend of the array were it to be computed. This can be ``None``
but this may cause problems when propagating information about which
functions to import to child nodes.
fn : callable
The function to call to compute the array, presumable imported from
``backend``. This can be ``None`` if the array already has data (e.g.
is an input).
args : tuple
The positional arguments to pass to ``fn``, which might be
``LazyArray`` instances.
kwargs : dict
The keyword arguments to pass to ``fn``, which might be
``LazyArray`` instances.
shape : tuple
The shape of the array that ``fn(*args, **kwargs)`` will return, or
the shape of the array that ``data`` has.
deps : tuple, optional
The ``LazyArray`` instances that ``fn(*args, **kwargs)`` depends on.
If not specified, these will be automatically found from ``args`` and
``kwargs``, specifying them manually is slightly more efficient.
"""
__slots__ = (
"_backend",
"_fn",
"_args",
"_kwargs",
"_shape",
"_data",
"_deps",
"_depth",
)
def __init__(
self,
backend,
fn,
args,
kwargs,
shape,
deps=None,
):
# info required to perform the computation
self._backend = backend
self._fn = fn
self._args = args
if kwargs is None:
self._kwargs = _EMPTY_DICT
else:
self._kwargs = kwargs
# resulting array information
self._shape = shape
self._data = None
# lazy arrays this ``LazyArray`` depends on
if deps is None:
# automatically find them
self._deps = (*find_lazy(self._args), *find_lazy(self._kwargs))
else:
# manually specified (slightly more efficient)
self._deps = deps
# tracking depth helps when ordering the computational graph
if self._deps:
self._depth = max(d._depth for d in self._deps) + 1
else:
self._depth = 0
@classmethod
def from_data(cls, data):
"""Create a new ``LazyArray`` directly from a concrete array."""
obj = cls.__new__(cls)
obj._backend = infer_backend(data)
obj._fn = obj._args = obj._kwargs = None
obj._shape = shape(data)
obj._data = data
obj._deps = ()
obj._depth = 0
return obj
@classmethod
def from_shape(cls, shape, backend="numpy"):
"""Create a new ``LazyArray`` with a given shape."""
obj = cls.__new__(cls)
obj._backend = backend
obj._fn = obj._args = obj._kwargs = None
obj._shape = tuple(map(int, shape))
obj._data = PLACEHOLDER
obj._deps = ()
obj._depth = 0
return obj
def to(
self,
fn,
args=None,
kwargs=None,
backend=None,
shape=None,
deps=None,
):
"""Create a new ``LazyArray``, by default propagating backend, shape,
and deps from the the current LazyArray.
"""
return LazyArray(
fn=fn,
args=args if args is not None else (self,),
kwargs=kwargs,
backend=backend if backend is not None else self._backend,
shape=shape if shape is not None else self.shape,
deps=deps if deps is not None else (self,),
)
def _materialize(self):
"""Recursively compute all required args and kwargs for this node
before computing itself and dereferencing dependencies. Note using this
to materialize a large computation from scratch should be avoided due
to the recursion limit, use ``x.compute()`` instead.
"""
if self._data is None:
# materialize any actual array args
args = (maybe_materialize(x) for x in self._args)
kwargs = {k: maybe_materialize(v) for k, v in self._kwargs.items()}
self._data = self._fn(*args, **kwargs)
# free any references to deps
self._fn = self._args = self._kwargs = None
self._deps = ()
return self._data
descend = descend
ascend = ascend
def compute(self):
"""Compute the value of this lazy array, clearing any references to the
function, arguments and dependencies, and storing the result in the
``_data`` attribute as well as returning it.
Unlike ``self._materialize()`` this avoids deep recursion.
"""
for node in self.ascend():
node._materialize()
return self._data
compute_constants = compute_constants
def as_string(self, params):
"""Create a string which evaluates to the lazy array creation."""
# name function and store in locals
fn_name = f"{getattr(self._fn, '__name__', 'fn')}{id(self._fn)}"
params.setdefault(fn_name, self._fn)
# string of args and kwargs
str_call = ", ".join(
itertools.chain(
(stringify(x, params) for x in self._args),
(
f"{k}: {stringify(v, params)}"
for k, v in self._kwargs.items()
),
)
)
# assign function call to new variable
return f"x{id(self)} = {fn_name}({str_call})"
get_source = get_source
def get_function(self, variables, fold_constants=True):
"""Get a compiled function that computes ``fn(arrays)``, with ``fn``
describing the computational graph of this ``LazyArray`` and ``arrays``
corresponding to the downstream ``LazyArray`` nodes ``variables``.
Parameters
----------
variables : sequence of LazyArray
Input nodes whose data can change between calls.
fold_constants : bool, optional
Compute all intermediates which do not depend on ``variables``
prior to compilation.
Returns
-------
fn : callable
Function with signature ``fn(arrays)``.
"""
return Function(
inputs=variables, outputs=self, fold_constants=fold_constants
)
def show(self, filler=" ", max_lines=None, max_depth=None):
"""Show the computational graph as a nested directory structure."""
if max_lines is None:
max_lines = float("inf")
if max_depth is None:
max_depth = float("inf")
# ┃ ━ ┗ ┣ │ ─ └ ╰ ├ ← ⬤
bar = f"│{filler}"
space = f"{filler}{filler}"
junction = "├─"
bend = "╰─"
line = 0
seen = {}
queue = [(self, ())]
while queue and (line < max_lines):
t, columns = queue.pop()
prefix = ""
if columns:
# work out various lines we need to draw based on whether the
# sequence of parents are themselves the last child of their
# parent
prefix += "".join(
bar if not p else space for p in columns[:-1]
)
prefix += bend if columns[-1] else junction
if t.fn_name not in (None, "None"):
item = f"{t.fn_name}{list(t.shape)}"
else:
# input node
item = f"←{list(t.shape)}"
if t in seen:
# ignore loops, but point to when it was computed
print(f"{line:>4} {prefix} ... ({item} from line {seen[t]})")
line += 1
continue
print(f"{line:>4} {prefix}{item}")
seen[t] = line
line += 1
if len(columns) < max_depth:
deps = sorted(t.deps, key=get_depth, reverse=True)
islasts = [True] + [False] * (len(deps) - 1)
for islast, d in zip(islasts, deps):
queue.append((d, columns + (islast,)))
def history_num_nodes(self):
"""Return the number of unique computational nodes in the history of
this ``LazyArray``.
"""
num_nodes = 0
for _ in self.descend():
num_nodes += 1
return num_nodes
def history_max_size(self):
"""Get the largest single tensor size appearing in this computation."""
return max(node.size for node in self.descend())
def history_size_footprint(self, include_inputs=True):
"""Get the combined size of intermediates at each step of the
computation. Note this assumes that intermediates are immediately
garbage collected when they are no longer required.
Parameters
----------
include_inputs : bool, optional
Whether to include the size of the inputs in the computation. If
``True`` It is assumed they can be garbage collected once used but
are all present at the beginning of the computation.
"""
delete_checked = set()
sizes = []
input_size = 0
for node in reversed(tuple(self.ascend())):
for c in node._deps:
if c not in delete_checked:
# last time a dependency is seen, subtract the size
if include_inputs or c._deps:
sizes.append(-c.size)
delete_checked.add(c)
if node._data is None:
# this is a new intermediate, add the size
sizes.append(+node.size)
elif include_inputs:
# this is an input, size is added at beginning
input_size += node.size
sizes.append(input_size)
sizes.reverse()
return list(itertools.accumulate(sizes))
def history_peak_size(self, include_inputs=True):
"""Get the peak combined intermediate size of this computation.
Parameters
----------
include_inputs : bool, optional
Whether to include the size of the inputs in the computation. If
``True`` It is assumed they can be garbage collected once used but
are all present at the beginning of the computation.
"""
return max(self.history_size_footprint(include_inputs=include_inputs))
def history_total_size(self):
"""The the total size of all unique arrays in the computational graph,
possibly relevant e.g. for back-propagation algorithms.
"""
return sum(node.size for node in self.descend())
def history_stats(self, fn):
"""Compute aggregate statistics about the computational graph.
Parameters
----------
fn : callable or str
Function to apply to each node in the computational graph. If a
string, one of 'count', 'sizein', 'sizeout' can be used to count
the number of nodes, the total size of the inputs, or the total
size of each output respectively.
Returns
-------
stats : dict
Dictionary mapping function names to the aggregate statistics.
"""
if not callable(fn):
if fn == "count":
def fn(node):
return 1
elif fn == "sizein":
def fn(node):
return sum(child.size for child in node.deps)
elif fn == "sizeout":
def fn(node):
return node.size
stats = collections.defaultdict(int)
for node in self.descend():
node_cost = fn(node)
if node_cost is not None:
stats[node.fn_name] += fn(node)
return dict(stats)
def history_fn_frequencies(self):
"""Get a dictionary mapping function names to the number of times they
are used in the computational graph.
"""
return self.history_stats("count")
def to_nx_digraph(self, variables=None):
"""Convert this ``LazyArray`` into a ``networkx.DiGraph``."""
import networkx as nx
if variables is None:
variables = set()
elif isinstance(variables, LazyArray):
variables = {variables}
else:
variables = set(variables)
G = nx.DiGraph()
nodemap = {}
for i, node in enumerate(self.ascend()):
nodemap[node] = i
variable = (node in variables) or any(
child in variables for child in node.deps
)
if variable:
variables.add(node)
G.add_node(i, array=node, variable=variable)
for x in node.deps:
G.add_edge(nodemap[x], nodemap[node])
return G
plot = plot_circuit
plot_graph = plot_graph
plot_circuit = plot_circuit
plot_history_size_footprint = plot_history_size_footprint
plot_history_functions = plot_history_functions
plot_history_functions_scatter = functools.partialmethod(
plot_history_functions, kind="scatter"
)
plot_history_functions_lines = functools.partialmethod(
plot_history_functions, kind="lines"
)
plot_history_functions_image = functools.partialmethod(
plot_history_functions, kind="image"
)
plot_history_stats = plot_history_stats
plot_history_stats_counts = functools.partialmethod(
plot_history_stats, fn="count"
)
plot_history_stats_sizein = functools.partialmethod(
plot_history_stats, fn="sizein"
)
@property
def fn(self):
"""The function to use to compute this array."""
return self._fn
@property
def fn_name(self):
"""The name of the function to use to compute this array."""
return getattr(self._fn, "__name__", "None")
@property
def args(self):
"""The positional arguments to the function to use to compute this
array.
"""
return self._args
@property
def kwargs(self):
"""The keyword arguments to the function to use to compute this
array.
"""
return self._kwargs
@property
def shape(self):
return self._shape
def __len__(self):
return self.shape[0]
def __iter__(self):
import warnings
warnings.warn(
"Iterating over LazyArray to get the computational graph nodes is "
"deprecated - use `LazyArray.descend()` instead. Eventually "
"`iter(lz)` will iterate over first axis slices."
)
return self.descend()
@property
def ndim(self):
return len(self._shape)
@property
def size(self):
return functools.reduce(operator.mul, self.shape, 1)
@property
def backend(self):
return self._backend
@property
def deps(self):
"""A tuple of the dependencies, other LazyArray instances, of this
array.
"""
return self._deps
@property
def depth(self):
"""The maximum distance to any input array in the computational graph.
"""
return self._depth
def __getitem__(self, key):
return getitem(self, key)
# this makes numpy operations delegate to __rmatmul__ etc.
__array_ufunc__ = None
def __mul__(self, other):
return multiply(self, other)
def __rmul__(self, other):
return multiply(self, other)
def __add__(self, other):
return add(self, other)
def __radd__(self, other):
return add(self, other)
def __sub__(self, other):
return sub(self, other)
def __rsub__(self, other):
return sub(other, self)
def __floordiv__(self, other):
return floordivide(self, other)
def __rfloordiv__(self, other):
return floordivide(other, self)
def __truediv__(self, other):
return truedivide(self, other)
def __rtruediv__(self, other):
return truedivide(other, self)
def __pow__(self, other):
return pow_(self, other)
def __rpow__(self, other):
return pow_(other, self)
def __matmul__(self, other):
return matmul(self, other)
def __rmatmul__(self, other):
return matmul(other, self)
def __abs__(self):
return abs_(self)
def __neg__(self):
return self.to(operator.neg)
def __ne__(self, other):
return ne(self, other)
def __gt__(self, other):
return gt(self, other)
def __lt__(self, other):
return lt(self, other)
def __ge__(self, other):
return ge(self, other)
def __le__(self, other):
return le(self, other)
@property
def T(self):
return transpose(self)
@property
def H(self):
return conj(transpose(self))
def reshape(self, shape):
return reshape(self, shape)
def astype(self, dtype_name):
return lazy_astype(self, dtype_name)
@property
def real(self):
return real(self)
@property
def imag(self):
return imag(self)
def __repr__(self):
return (
f"<{self.__class__.__name__}("
f"fn={self.fn_name}, "
f"shape={self.shape}, "
f"backend='{self.backend}')>"
)
register_backend(LazyArray, "autoray.lazy")
def ensure_lazy(array):
if not isinstance(array, LazyArray):
return LazyArray.from_data(array)
return array
def find_lazy(x):
"""Recursively search for ``LazyArray`` instances in pytrees."""
if isinstance(x, LazyArray):
yield x
return
if isinstance(x, (tuple, list)):
for subx in x:
yield from find_lazy(subx)
return
if isinstance(x, dict):
for subx in x.values():
yield from find_lazy(subx)
return
# --------------------- recusively evaluating 'pytrees' --------------------- #
def materialize_larray(x):
return x._materialize()
def materialize_tuple(x):
return tuple(map(maybe_materialize, x))
def materialize_list(x):
return list(map(maybe_materialize, x))
def materialize_dict(x):
return {k: maybe_materialize(v) for k, v in x.items()}
def materialize_identity(x):
return x
_materialize_dispatch = {
LazyArray: materialize_larray,
tuple: materialize_tuple,
list: materialize_list,
dict: materialize_dict,
}
def maybe_materialize(x):
"""Recursively evaluate LazyArray instances in tuples, lists and dicts."""
try:
return _materialize_dispatch[x.__class__](x)
except KeyError:
_materialize_dispatch[x.__class__] = materialize_identity
return x
# -------------------- recusively stringifying 'pytrees' -------------------- #
def stringify_larray(x, params):
name = f"x{id(x)}"
if x._data is not None:
params.setdefault(name, x._data)
return name
def stringify_tuple(x, params):
if not x:
return "()"
return f"({', '.join(stringify(xi, params) for xi in x)},)"
def stringify_list(x, params):
return f"[{', '.join(stringify(xi, params) for xi in x)}]"
def stringify_dict(x, params):
entries = (f"{k}: {stringify(v, params)}" for k, v in x.items())
return f"{{{', '.join(entries)}}}"
def stringify_identity(x, params):
if isinstance(x, (int, float, complex, bool, slice, range)):
return f"{x}"