-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
partial_eval.py
2423 lines (2117 loc) · 105 KB
/
partial_eval.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
# Copyright 2018 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
from collections import namedtuple
import contextlib
import functools
from functools import partial
import inspect
import itertools as it
import operator as op
from typing import (Any, Callable, Dict, NamedTuple, Optional, Sequence, Tuple,
List, Union, Hashable, Set, cast)
from weakref import ref
import numpy as np
from jax import core
from jax import linear_util as lu
from jax._src import api_util
from jax._src import dtypes
from jax._src import profiler
from jax._src.ad_util import Zero
from jax._src.api_util import flattened_fun_in_tree, flatten_fun_nokwargs
from jax._src.tree_util import (PyTreeDef, treedef_tuple, tree_unflatten,
tree_leaves)
from jax._src.util import (unzip2, safe_zip, safe_map, toposort, split_list,
merge_lists, partition_list, OrderedSet,
as_hashable_function, weakref_lru_cache)
from jax.core import (Trace, Tracer, Jaxpr, Literal, get_aval, AbstractValue,
ClosedJaxpr, new_jaxpr_eqn, ConcreteArray, Var, DropVar,
raise_to_shaped, Atom, JaxprEqn, Primitive, ShapedArray,
DShapedArray, AbstractBInt, mapped_aval, unmapped_aval,
DBIdx, InDBIdx, OutDBIdx, InputType, OutputType,
get_referent)
from jax._src import source_info_util
from jax.config import config
map, unsafe_map = safe_map, map
zip, unsafe_zip = safe_zip, zip
def identity(x): return x
TracerId = int
AvalId = int
ConstId = int
def _update_annotation_known(
f: lu.WrappedFun,
orig_type: Optional[InputType],
in_knowns: List[bool]
) -> lu.WrappedFun:
if orig_type is None: return f
# orig_type might contain DBIdx, but we're tossing out some args so we have to
# re-index. moreover some of the implicit args may not be needed anymore.
# so we basically just re-infer the lambda input type
if (all(e for _, e in orig_type) and
not any(type(d) is DBIdx for a, _ in orig_type for d in a.shape
if type(a) is DShapedArray)):
new_type = [ty for ty, known in zip(orig_type, in_knowns) if known]
return lu.annotate(f, tuple(new_type))
# Replace DBIdx with names, prune down to explicit only.
class Name:
def __init__(self, a): self.a = a
names = [Name(a) for a, _ in orig_type]
avals = [a.update(shape=tuple(names[d.val] if type(d) is DBIdx else d # type: ignore
for d in a.shape))
if type(a) is DShapedArray else a for a, e in orig_type if e]
avals = [a for a, known in zip(avals, in_knowns) if known]
# Figure out the implicit part: names which aren't explicit and known.
expl_names = [o for o, (_, e) in zip(names, orig_type) if e]
expl_names = [o for o, k in zip(expl_names, in_knowns) if k]
expl_names_ = set(expl_names)
impl_names = {d for a in avals if type(a) is DShapedArray for d in a.shape
if type(d) is Name and d not in expl_names_}
impl_part = [(n.a, False) for n in impl_names] # type: ignore
# Figure out the explicit part: known explicit avals, replacing names w/ dbidx
name_map = {n: DBIdx(i) for i, n in enumerate((*impl_names, *expl_names))}
expl_part = [(a.update(shape=tuple(name_map.get(d, d) for d in a.shape))
if type(a) is DShapedArray else a, True) for a in avals]
return lu.annotate(f, (*impl_part, *expl_part))
class PartialVal(tuple):
"""Partial value: either a known value or an unknown (abstract) value.
Represented as a pair `(aval_opt, const)` of one of two kinds:
* `(None, <Constant>)` indicates a known value, where the constant is either a
Tracer or satisfies `core.valid_jaxtype(const)`;
* `(<AbstractValue>, None)` indicates an unknown value characterized by an
abstract value.
"""
def __new__(cls, xs: Tuple[Optional[AbstractValue], core.Value]):
pv, const = xs
if config.jax_enable_checks:
# type checks
assert isinstance(pv, (AbstractValue, type(None))), xs
assert (const is None or isinstance(const, core.Tracer) or
core.valid_jaxtype(const)), const
# invariant checks
assert (pv is None) ^ (const is None)
return tuple.__new__(cls, xs)
@classmethod
def known(cls, const: core.Value) -> PartialVal:
return PartialVal((None, const))
@classmethod
def unknown(cls, aval: AbstractValue) -> PartialVal:
return PartialVal((aval, None))
def is_known(self) -> bool:
return self[0] is None
def get_known(self) -> Optional[core.Value]:
"""Get the known value, if known, else None."""
return self[1] if self[0] is None else None
def get_aval(self) -> AbstractValue:
"""Get AbstractValue directly (if unknown) or from the constant (known)."""
known = self.get_known()
if known is not None:
return get_aval(known)
else:
return self[0]
class JaxprTrace(Trace):
def __init__(self, *args, name_stack: source_info_util.NameStack):
super().__init__(*args)
self.name_stack = name_stack
def pure(self, val: Any) -> JaxprTracer:
return self.new_const(val)
def lift(self, val: Tracer) -> JaxprTracer:
return self.new_const(val)
def sublift(self, val: JaxprTracer) -> JaxprTracer:
return JaxprTracer(self, val.pval, FreeVar(val))
def new_const(self, val) -> JaxprTracer:
if isinstance(val, Tracer) and val._trace.level == self.level:
raise Exception
return JaxprTracer(self, PartialVal.known(val), None)
def new_instantiated_literal(self, val) -> JaxprTracer:
aval = get_aval(val)
return JaxprTracer(self, PartialVal.unknown(aval),
Literal(val, raise_to_shaped(aval)))
def new_instantiated_const(self, val) -> JaxprTracer:
aval = get_aval(val)
if isinstance(aval, DShapedArray):
shape = [self.new_instantiated_const(d)
if isinstance(d, Tracer) and d._trace.level < self.level else d
for d in aval.shape]
aval = aval.update(shape=tuple(shape))
return JaxprTracer(self, PartialVal.unknown(aval), ConstVar(val))
def new_arg(self, pval: PartialVal) -> JaxprTracer:
const = pval.get_known()
# XXX: Think twice before changing this constant argument pruning!
# This has really important consequences for partial_eval_jaxpr.
# Most importantly, this guarantees that the unknown jaxpr never uses
# known inputs (if it needs them, then they get passed through residuals).
if const is None:
aval = pval.get_aval()
if type(aval) is DShapedArray:
shape = [self.new_instantiated_const(d)
if isinstance(d, Tracer) and d._trace.level < self.level else d
for d in aval.shape]
aval = aval.update(shape=tuple(shape))
return JaxprTracer(self, PartialVal.unknown(aval), LambdaBinding())
else:
return self.new_const(const)
def instantiate_const(self, tracer) -> Tracer:
const = tracer.pval.get_known()
if const is None:
return tracer
else:
if type(const) in core.literalable_types and np.shape(const) == ():
return self.new_instantiated_literal(const)
else:
return self.new_instantiated_const(const)
def instantiate_const_abstracted(self, tracer) -> JaxprTracer:
const = tracer.pval.get_known()
if const is None:
return tracer
else:
aval = raise_to_shaped(get_aval(const), np.isscalar(const))
return JaxprTracer(self, PartialVal.unknown(aval), ConstVar(const))
def process_primitive(self, primitive, tracers, params):
if primitive in custom_partial_eval_rules:
return custom_partial_eval_rules[primitive](self, *tracers, **params)
else:
return self.default_process_primitive(primitive, tracers, params)
def default_process_primitive(self, primitive, tracers, params):
# By default, if all the input tracers are known, then bind the primitive
# and consider all outputs known. Otherwise, stage the application into the
# jaxpr and consider all outputs unknown.
consts = [t.pval.get_known() for t in tracers]
if all(c is not None for c in consts):
return primitive.bind(*consts, **params)
tracers = map(self.instantiate_const, tracers)
avals = [t.aval for t in tracers]
out_aval, effects = primitive.abstract_eval(*avals, **params)
name_stack = self._current_truncated_name_stack()
source = source_info_util.current().replace(name_stack=name_stack)
if primitive.multiple_results:
out_tracers = [JaxprTracer(self, PartialVal.unknown(aval), None)
for aval in out_aval]
eqn = new_eqn_recipe(tracers, out_tracers, primitive, params, effects, source)
for t in out_tracers: t.recipe = eqn
return out_tracers
else:
out_tracer = JaxprTracer(self, PartialVal.unknown(out_aval), None)
out_tracer.recipe = new_eqn_recipe(tracers, [out_tracer], primitive,
params, effects, source)
return out_tracer
def process_call(self, primitive, f, tracers, params):
rule = call_partial_eval_rules.get(primitive)
if rule:
return rule(self, primitive, f, tracers, params)
update_params = call_param_updaters.get(primitive) or (lambda p, _, __: p)
in_knowns, in_avals, in_consts = partition_pvals([t.pval for t in tracers])
# TODO(mattjj): check in_avals are consistent with f.in_type
# We want to partially evaluate this call into two calls: one evaluated now
# taking known values (in_consts) as inputs and producing known values
# (out_consts) as outputs, and the other staged out as an eqn into the jaxpr
# being built. The latter takes as input residuals (res) produced as outputs
# of the first call, shared closed-over values (env), and explicit arguments
# which were unknown to the first call (corresponding to in_avals).
# Wrap f to perform the partial evaluation and plumb out aux data.
if not config.jax_dynamic_shapes:
f_ = trace_to_subjaxpr_nounits_fwd(f, self.main, False)
f_, aux = partial_eval_wrapper_nounits(f_, tuple(in_knowns),
tuple(in_avals))
else:
if f.in_type is None:
f = lu.annotate(f, tuple((a, True) for a in in_avals))
f_, aux = trace_to_subjaxpr_nounits_dyn(f, self.main, tuple(in_knowns),
f.in_type, False)
# Adjust parameters (e.g. donated_invars) for the call to be evaluated now.
const_params = update_params(params, in_knowns, 0)
# Run the call, getting known out vals and aux data used for staged-out call
out = primitive.bind(_update_annotation_known(f_, f.in_type, in_knowns),
*in_consts, **const_params)
fwds, out_knowns, out_type, jaxpr, env = aux()
# Split apart known outputs from the original call and non-fwded residuals.
out_consts, non_fwd_res_ = split_list(out, [sum(out_knowns)])
# Form the complete list of residuals by forwarding some inputs.
if config.jax_dynamic_shapes:
# With dynamic shapes, we may need to forward implicit arguments.
in_consts_, in_knowns_ = iter(in_consts), iter(in_knowns)
in_consts_full = [None] * len(f.in_type)
for idx, (aval, explicit) in enumerate(f.in_type):
if explicit and next(in_knowns_):
c = in_consts_full[idx] = next(in_consts_)
if aval.shape:
for d1, d2 in zip(aval.shape, c.shape):
if type(d1) is DBIdx:
in_consts_full[d1.val] = d2
else:
in_consts_full = in_consts
non_fwd_res = iter(non_fwd_res_)
res = [next(non_fwd_res) if i is None else in_consts_full[i] for i in fwds]
sentinel = object()
assert next(non_fwd_res, sentinel) is sentinel
# Create the input tracers for the staged-out (unknown-value) call.
res_tracers = map(self.instantiate_const, map(self.new_const, res))
env_tracers = map(self.full_raise, env)
unknown_arg_tracers = [t for t in tracers if not t.is_known()]
# Adjust parameters (e.g. donated_invars) for the staged-out call's args.
num_new_args = len(res_tracers) + len(env_tracers)
staged_params = dict(params, call_jaxpr=convert_constvars_jaxpr(jaxpr))
staged_params = update_params(staged_params, map(op.not_, in_knowns),
num_new_args)
# The outputs of the staged-out call are Tracers with the new eqn as recipe.
if config.jax_dynamic_shapes:
# With dynamic shapes, we may need to substitute Tracers into avals.
out_tracers = []
for aval, _ in out_type:
assert not isinstance(aval, ConcreteArray)
if type(aval) is DShapedArray:
shape = [[*res_tracers, *env_tracers, *unknown_arg_tracers][d.val]
if type(d) is InDBIdx else d for d in aval.shape]
aval = aval.update(shape=tuple(shape))
out_tracers.append(JaxprTracer(self, PartialVal.unknown(aval), None))
else:
out_tracers = [JaxprTracer(self, PartialVal.unknown(a), None)
for a in out_type]
name_stack = self._current_truncated_name_stack()
source = source_info_util.current().replace(name_stack=name_stack)
eqn = new_eqn_recipe((*res_tracers, *env_tracers, *unknown_arg_tracers),
out_tracers, primitive, staged_params, jaxpr.effects,
source)
for t in out_tracers: t.recipe = eqn
return merge_lists(out_knowns, out_tracers, out_consts)
def process_map(self, primitive, f: lu.WrappedFun, tracers, params):
update_params = call_param_updaters.get(primitive) or (lambda p, _, __: p)
in_knowns, in_avals, in_consts = partition_pvals([t.pval for t in tracers])
# This method is like process_call above, except:
# 1. we delete an axis from mapped-over input avals' shapes, and
# analogously add an axis to mapped-over output avals' shapes;
# 2. we update the in_axes and out_axes/out_axes_thunk parameters to
# reflect the inputs and outputs pruned from the unknown/known sides.
# Map (delete an axis from) unknown inputs' avals as dictated by in_axes.
unk_in_axes, const_in_axes = partition_list(in_knowns, params['in_axes'])
in_avals_mapped = [mapped_aval(params['axis_size'], ax, aval)
for ax, aval in zip(unk_in_axes, in_avals)]
# Wrap f to perform partial evaluation and plumb out aux data.
f = trace_to_subjaxpr_nounits(f, self.main, False)
f, aux = partial_eval_wrapper_nounits(f, tuple(in_knowns),
tuple(in_avals_mapped))
# Adjust params for knowns (e.g. donated_invars, in_axes, out_axes_thunk)
const_params = update_params(params, in_knowns, 0) # handles donated_invars
out_axes_thunk = params['out_axes_thunk']
@as_hashable_function(closure=out_axes_thunk)
def const_out_axes_thunk():
out_knowns, _, jaxpr, _ = aux()
_, out_axes = partition_list(out_knowns, out_axes_thunk())
return tuple(out_axes) + (0,) * len(jaxpr.constvars) # res mapped axis 0
const_params = dict(const_params, in_axes=tuple(const_in_axes),
out_axes_thunk=const_out_axes_thunk)
# Run the map, getting known out vals and aux data used for staged-out map.
out = primitive.bind(f, *in_consts, **const_params)
out_knowns, out_avals_mapped, jaxpr, env = aux()
# Split apart known outputs from the original call and residuals.
out_consts, res = split_list(out, [len(out) - len(jaxpr.constvars)])
# We can only check_jaxpr with the dynamic axis environment extended:
with core.extend_axis_env(params['axis_name'], params['axis_size'], None):
call_jaxpr = convert_constvars_jaxpr(jaxpr)
# Compute staged and const out_axes, taking into account residuals.
out_axes = params['out_axes_thunk']()
staged_out_axes, _ = partition_list(out_knowns, out_axes)
staged_in_axes = (0,) * len(res) + (None,) * len(env) + (*unk_in_axes,)
# Create the input tracers for the staged-out (unkonwn-value) call.
const_tracers = map(self.new_instantiated_const, res)
env_tracers = map(self.full_raise, env)
unknown_arg_tracers = [t for t in tracers if not t.is_known()]
# Adjust params for staged-out call on unknown values.
num_new_args = len(const_tracers) + len(env_tracers)
staged_params = update_params(params, map(op.not_, in_knowns), num_new_args)
staged_params = dict(staged_params, in_axes=staged_in_axes,
out_axes=tuple(staged_out_axes), call_jaxpr=call_jaxpr)
del staged_params['out_axes_thunk']
# The outputs of the staged-out call are Tracers with the new eqn as recipe.
out_avals = [unmapped_aval(params['axis_size'], params['axis_name'], ax, a)
for ax, a in zip(staged_out_axes, out_avals_mapped)]
out_tracers = [JaxprTracer(self, PartialVal.unknown(a), None)
for a in out_avals]
eqn = new_eqn_recipe((*const_tracers, *env_tracers, *unknown_arg_tracers),
out_tracers, primitive, staged_params,
jaxpr.effects,
source_info_util.current())
for t in out_tracers: t.recipe = eqn
return merge_lists(out_knowns, out_tracers, out_consts)
def post_process_call(self, primitive, out_tracers, params):
unknown_out_tracers = [t for t in out_tracers if not t.is_known()]
jaxpr, res, env = tracers_to_jaxpr([], unknown_out_tracers)
out_pvals = [t.pval for t in out_tracers]
out_knowns, out_avals, out_consts = partition_pvals(out_pvals)
out = [*out_consts, *res]
main = self.main
def todo(out):
trace = main.with_cur_sublevel()
out_consts, res = split_list(out, [len(out) - len(jaxpr.constvars)])
const_tracers = map(trace.new_instantiated_const, res)
in_tracers = (*const_tracers, *map(trace.full_raise, env))
out_tracers = [JaxprTracer(trace, PartialVal.unknown(a), None)
for a in out_avals]
update_params = call_param_updaters.get(primitive) or (lambda p, _, __: p)
new_params = update_params(params, [], len(in_tracers))
new_params = dict(new_params, call_jaxpr=convert_constvars_jaxpr(jaxpr))
name_stack = self._current_truncated_name_stack()
source = source_info_util.current().replace(name_stack=name_stack)
eqn = new_eqn_recipe(in_tracers, out_tracers, primitive, new_params,
jaxpr.effects, source)
for t in out_tracers: t.recipe = eqn
return merge_lists(out_knowns, out_tracers, out_consts)
return out, todo
def post_process_map(self, primitive, out_tracers, params):
unknown_out_tracers = [t for t in out_tracers if not t.is_known()]
jaxpr, res, env = tracers_to_jaxpr([], unknown_out_tracers)
out_pvals = [t.pval for t in out_tracers]
out_knowns, out_avals_mapped, out_consts = partition_pvals(out_pvals)
out = [*out_consts, *res]
main = self.main
with core.extend_axis_env(params['axis_name'], params['axis_size'], None):
call_jaxpr = convert_constvars_jaxpr(jaxpr)
def todo(out):
trace = main.with_cur_sublevel()
out_consts, res = split_list(out, [len(out) - len(jaxpr.constvars)])
const_tracers = map(trace.new_instantiated_const, res)
env_tracers = map(trace.full_raise, env)
staged_out_axes = tuple(out_axes_unknown) # set by out_axes_transform
staged_in_axes = (0,) * len(res) + (None,) * len(env)
update_params = call_param_updaters.get(primitive) or (lambda p, _, __: p)
staged_params = update_params(params, [], len(res) + len(env))
staged_params = dict(staged_params, in_axes=staged_in_axes,
out_axes=tuple(staged_out_axes),
call_jaxpr=call_jaxpr)
out_avals = [unmapped_aval(params['axis_size'], params['axis_name'], d, a)
for d, a in zip(staged_out_axes, out_avals_mapped)]
out_tracers = [JaxprTracer(trace, PartialVal.unknown(a), None)
for a in out_avals]
name_stack = self._current_truncated_name_stack()
source = source_info_util.current().replace(name_stack=name_stack)
eqn = new_eqn_recipe((*const_tracers, *env_tracers), out_tracers,
primitive, staged_params, jaxpr.effects, source)
for t in out_tracers: t.recipe = eqn
return merge_lists(out_knowns, out_tracers, out_consts)
def out_axes_transform(out_axes):
nonlocal out_axes_unknown
out_axes_unknown, out_axes_known = partition_list(out_knowns, out_axes)
return tuple(out_axes_known) + (0,) * len(jaxpr.constvars)
out_axes_unknown: Optional[list] = None
return out, (todo, out_axes_transform)
def _current_truncated_name_stack(self):
return source_info_util.current_name_stack()[len(self.name_stack):]
def process_custom_jvp_call(self, prim, fun, jvp, tracers):
# We assume partial evaluation is only performed to build linear functions,
# and hence we don't need to keep the custom JVP rule around anymore.
del jvp
assert not all(t.is_known() for t in tracers)
return fun.call_wrapped(*tracers)
def post_process_custom_jvp_call(self, out_tracers, _):
# This path should only be reachable if we expose a partial eval API
# unrelated to autodiff, since we raise an error when differentiation with
# respect to values over which a custom_jvp function closes is detected.
raise NotImplementedError # TODO(mattjj)
def process_custom_transpose(self, prim, call, tracers, **params):
res_ts, lin_ts = split_list(tracers, [params['res_tree'].num_leaves])
assert all(t.is_known() for t in res_ts)
lin_all_known = all(t.is_known() for t in lin_ts)
if lin_all_known:
res_cvals = [t.pval[1] for t in res_ts]
lin_cvals = [t.pval[1] for t in lin_ts]
return prim.bind(call, *res_cvals, *lin_cvals, **params)
else:
out_tracers = [JaxprTracer(self, PartialVal.unknown(aval), None)
for aval in params['out_types']]
in_tracers = map(self.instantiate_const, tracers)
new_params = dict(params, call=call)
eqn = new_eqn_recipe(in_tracers, out_tracers, prim, new_params,
core.no_effects, source_info_util.current())
for t in out_tracers: t.recipe = eqn
return out_tracers
def process_custom_vjp_call(self, prim, f, fwd, bwd, tracers, out_trees):
# TODO(mattjj): after old remat is deleted, make this method trivial.
# Because we instantiate all tracers, in_knowns is all False.
tracers = map(self.instantiate_const_abstracted, tracers)
in_knowns, in_avals, () = partition_pvals([t.pval for t in tracers])
f = trace_to_subjaxpr_nounits(f, self.main, True)
f, aux = partial_eval_wrapper_nounits(f, tuple(in_knowns), tuple(in_avals))
out_flat = prim.bind(f, fwd, bwd, out_trees=out_trees)
out_knowns, out_avals, jaxpr, env = aux()
out_consts, res = split_list(out_flat, [len(out_flat)-len(jaxpr.constvars)])
res_tracers = map(self.new_instantiated_const, res)
env_tracers = map(self.full_raise, env)
out_tracers = [JaxprTracer(self, PartialVal.unknown(a), None)
for a in out_avals]
closed_jaxpr = core.ClosedJaxpr(convert_constvars_jaxpr(jaxpr), ())
@_memoize
def fwd_jaxpr_thunk():
fwd_ = trace_to_subjaxpr_nounits(fwd, self.main, True)
fwd_, aux = partial_eval_wrapper_nounits(
fwd_, tuple(in_knowns), tuple(in_avals))
with core.new_sublevel():
out_flat = fwd_.call_wrapped()
out_knowns, out_avals, jaxpr, env = aux()
_, res = split_list(out_flat, [len(out_flat)-len(jaxpr.constvars)])
converted_jaxpr = convert_envvars_to_constvars(jaxpr, len(env))
return converted_jaxpr, (*res, *env)
name_stack = self._current_truncated_name_stack()
source = source_info_util.current().replace(name_stack=name_stack)
eqn = new_eqn_recipe((*res_tracers, *env_tracers, *tracers),
out_tracers, prim.initial_style,
dict(fun_jaxpr=closed_jaxpr,
fwd_jaxpr_thunk=fwd_jaxpr_thunk,
num_consts=len(res) + len(env),
bwd=bwd, out_trees=out_trees),
jaxpr.effects, source)
for t in out_tracers: t.recipe = eqn
return merge_lists(out_knowns, out_tracers, out_consts)
def post_process_custom_vjp_call(self, out_tracers, _):
# This path should only be reachable if we expose a partial eval API
# unrelated to autodiff, since we raise an error when differentiation with
# respect to values over which a custom_vjp function closes is detected.
raise NotImplementedError # TODO(mattjj)
def partition_pvals(
pvals: List[PartialVal]
) -> Tuple[List[bool], List[AbstractValue], List[Any]]:
knowns = [pval.is_known() for pval in pvals ]
avals = [pval.get_aval() for pval in pvals if not pval.is_known()]
consts = [pval.get_known() for pval in pvals if pval.is_known()]
return knowns, avals, consts
@lu.transformation_with_aux
def partial_eval_wrapper_nounits(
in_knowns: Sequence[bool], in_avals: Sequence[AbstractValue],
*in_consts: Any):
in_avals_, in_consts_ = iter(in_avals), iter(in_consts)
in_pvals = [PartialVal.known(next(in_consts_)) if known else
PartialVal.unknown(next(in_avals_)) for known in in_knowns]
sentinel = object()
assert next(in_avals_, sentinel) is next(in_consts_, sentinel) is sentinel
jaxpr, (*maybe_fwds, out_pvals, res, env) = yield (in_pvals,), {}
out_knowns, out_avals, out_consts = partition_pvals(out_pvals)
yield (*out_consts, *res), (*maybe_fwds, out_knowns, out_avals, jaxpr, env)
@lu.transformation_with_aux
def trace_to_subjaxpr_nounits_dyn(
main: core.MainTrace, in_knowns: Sequence[bool], in_type: InputType,
instantiate: Union[bool, Sequence[bool]],
*in_consts: Any):
trace = main.with_cur_sublevel()
in_avals, which_explicit = unzip2(in_type)
# To form input tracers from in_type, we need to first build ConstVar tracers
# for all axis sizes, so that we can then use those tracers in the shapes of
# avals for unknown inputs' tracers. We use ConstVar recipes for on-the-fly
# type agreement checking via get_referent.
in_consts_full: List[Optional[JaxprTracer]] = [None] * len(in_type)
in_consts_iter, in_knowns_iter = iter(in_consts), iter(in_knowns)
for idx, (aval, explicit) in enumerate(in_type):
if explicit and next(in_knowns_iter):
constval = next(in_consts_iter)
if isinstance(aval, DShapedArray):
for i, d in enumerate(aval.shape):
if isinstance(d, DBIdx):
if in_consts_full[d.val] is None:
in_consts_full[d.val] = \
JaxprTracer(trace, PartialVal.unknown(in_avals[d.val]),
ConstVar(constval.shape[i]))
assert core.same_referent(constval.shape[i], in_consts_full[d.val])
shape = [in_consts_full[d.val] if type(d) is DBIdx else d # type: ignore
for d in aval.shape]
aval = aval.update(shape=tuple(shape))
in_consts_full[idx] = JaxprTracer(trace, PartialVal.unknown(aval),
ConstVar(constval))
# Check that we covered all axis sizes with ConstVar tracers.
for idx, (aval, explicit) in enumerate(in_type):
if not explicit: assert in_consts_full[idx] is not None
if isinstance(aval, DShapedArray):
assert all(type(d) is not DBIdx or in_consts_full[d.val] is not None # type: ignore
for d in aval.shape)
# Next, build tracers for all unknown inputs, using the in_consts_full list
# for axis size tracers when necessary.
in_tracers = []
in_knowns_iter = iter(in_knowns)
for aval, explicit in in_type:
if explicit and not next(in_knowns_iter):
if isinstance(aval, DShapedArray):
shape = [in_consts_full[d.val] if type(d) is DBIdx else d # type: ignore
for d in aval.shape]
aval = aval.update(shape=tuple(shape))
tracer = JaxprTracer(trace, PartialVal.unknown(aval), LambdaBinding())
in_tracers.append(tracer)
# Merge in_consts and in_tracers and call wrapped fn with explicit arguments.
in_args = merge_lists(in_knowns, in_tracers, in_consts)
ans = yield in_args, {}
# Instantiate outputs and build jaxpr.
if isinstance(instantiate, bool):
instantiate = [instantiate] * len(ans)
out_tracers = map(trace.full_raise, map(core.full_lower, ans))
out_tracers = [trace.instantiate_const(trace.full_raise(t)) if inst else t
for inst, t in zip(instantiate, out_tracers)]
# Collect known outputs.
out_knowns: List[bool] = [t.is_known() for t in out_tracers]
out_consts: List[Any] = [t.pval.get_known() for t in out_tracers
if t.is_known()]
# Build the jaxpr.
out_tracers = [t for t in out_tracers if not t.is_known()]
jaxpr, res, env = tracers_to_jaxpr(in_tracers, out_tracers)
out_avals = [v.aval for v in jaxpr.outvars]
idx_map = {v: InDBIdx(i)
for i, v in enumerate(it.chain(jaxpr.constvars, jaxpr.invars))}
out_type = [(a.update(shape=tuple(idx_map.get(d, d) for d in a.shape)) # type: ignore
if type(a) is DShapedArray else a, True) for a in out_avals]
# Which residuals are just forwarded inputs? Check obj id, then prune.
id_map = {id(c.recipe.val): i for i, c in enumerate(in_consts_full) # type: ignore
if c is not None}
fwds: List[Optional[int]] = [id_map.get(id(c)) for c in res]
res = tuple([c for c, fwd in zip(res, fwds) if fwd is None])
del main, in_consts, trace, in_consts_iter, in_knowns_iter, in_consts_full, \
in_tracers, in_args, ans, out_tracers, out_avals
yield (*out_consts, *res), (fwds, out_knowns, tuple(out_type), jaxpr, env)
custom_partial_eval_rules: Dict[Primitive, Callable] = {}
call_partial_eval_rules: Dict[Primitive, Callable] = {}
call_param_updaters: Dict[Primitive, Callable] = {}
def _closed_call_param_updater(params, _, __):
jaxpr = params.get('call_jaxpr')
if jaxpr is None: return params
assert type(jaxpr) is core.Jaxpr
return dict(params, call_jaxpr=core.ClosedJaxpr(jaxpr, ()))
call_param_updaters[core.closed_call_p] = _closed_call_param_updater
def abstract_eval_fun(fun, *avals, debug_info=None, **params):
_, avals_out, _ = trace_to_jaxpr_dynamic(
lu.wrap_init(fun, params), avals, debug_info)
assert all(isinstance(aval, AbstractValue) for aval in avals_out)
return avals_out
JaxprTracerRecipe = Union['JaxprEqnRecipe', 'LambdaBinding', 'FreeVar',
'ConstVar', Literal]
class JaxprTracer(Tracer):
__slots__ = ['pval', 'recipe']
def __init__(self, trace: JaxprTrace, pval: PartialVal,
recipe: Optional[JaxprTracerRecipe]):
assert isinstance(pval, PartialVal)
pv, const = pval
if isinstance(const, Tracer) and const._trace.level >= trace.level:
raise core.escaped_tracer_error(
const, f"Tracer from a higher level: {const} in trace {trace}")
if isinstance(pv, DShapedArray):
assert all(not isinstance(d, Tracer) or isinstance(d, JaxprTracer) and
d._trace.level == trace.level for d in pv.shape)
self._trace = trace
self.pval = pval
self.recipe = recipe
def __repr__(self):
return f'Traced<{self.aval}:{self._trace}>'
@property
def aval(self) -> AbstractValue:
return self.pval.get_aval()
@property
def parents(self) -> Sequence[JaxprTracer]:
if isinstance(self.recipe, JaxprEqnRecipe):
# TODO broadcast_in_dim can create a new tracer...
return self.recipe.in_tracers
elif isinstance(self.aval, DShapedArray):
return [d for d in self.aval.shape if isinstance(d, JaxprTracer)]
else:
return []
def full_lower(self):
known = self.pval.get_known()
if known is not None:
return core.full_lower(known)
else:
return self
def is_known(self):
return self.pval.is_known()
def get_referent(self):
if self.pval.is_known():
return get_referent(self.pval.get_known())
elif isinstance(self.recipe, (FreeVar, ConstVar, Literal)):
return get_referent(self.recipe.val)
else:
return self
@profiler.annotate_function
def trace_to_jaxpr(
fun: lu.WrappedFun, pvals: Sequence[PartialVal],
instantiate: Union[bool, Sequence[bool]] = False,
) -> Tuple[Jaxpr, List[PartialVal], List[core.Value]]:
"""
Partially evaluate a function, building a jaxpr for un-evaluated computation.
Args:
fun: lu.WrappedFun representing the function to be partially evaluated. The
function must be flattened, in the sense of accepting jaxpr type arguments
and returning a flat list of jaxpr type outputs.
pvals: sequence of PartialVals of length equal to the number of inputs to
`fun` indicating which inputs are known or unknown.
instantiate: optional bool or sequence of bools of length equal to the
number of outputs of `fun` indicating which outputs should be forced to be
treated as unknown and hence instantiated in the jaxpr. If a single bool,
the value is applied to all outputs. Default False.
Returns:
A triple where the first element is a jaxpr representing the computation
which depends on unknown inputs; the second element is a list of PartialVals
of length equal to the length of the output of `fun` representing which
outputs are known and unknown (along with their values and abstract values,
respectively); the third element is a list of known residual values. The
returned jaxpr takes as inputs the known residual values followed by values
of the originally unknown inputs.
"""
current_name_stack = source_info_util.current_name_stack()
with core.new_main(JaxprTrace, name_stack=current_name_stack) as main:
fun = trace_to_subjaxpr(fun, main, instantiate)
jaxpr, (out_pvals, consts, env) = fun.call_wrapped(pvals)
assert not env
del main, fun, env
return jaxpr, out_pvals, consts
@profiler.annotate_function
def trace_to_jaxpr_nounits(
fun: lu.WrappedFun, pvals: Sequence[PartialVal],
instantiate: Union[bool, Sequence[bool]] = False,
) -> Tuple[Jaxpr, List[PartialVal], List[core.Value]]:
current_name_stack = source_info_util.current_name_stack()
with core.new_main(JaxprTrace, name_stack=current_name_stack) as main:
fun = trace_to_subjaxpr_nounits(fun, main, instantiate)
jaxpr, (out_pvals, consts, env) = fun.call_wrapped(pvals)
assert not env
del main, fun, env
return jaxpr, out_pvals, consts
@lu.transformation
def trace_to_subjaxpr_nounits(
main: core.MainTrace,
instantiate: Union[bool, Sequence[bool]],
in_pvals: Sequence[PartialVal]):
assert all([isinstance(pv, PartialVal) for pv in in_pvals]), in_pvals
out_tracers, jaxpr, out_consts, env = yield from _trace_to_subjaxpr_nounits(
main, instantiate, in_pvals)
out_pvals = [t.pval for t in out_tracers]
del out_tracers
yield jaxpr, (out_pvals, out_consts, env)
def _trace_to_subjaxpr_nounits(main, instantiate, in_pvals):
trace = main.with_cur_sublevel()
in_knowns = [pval.is_known() for pval in in_pvals]
in_consts = [pval.get_known() for pval in in_pvals if pval.is_known()]
in_tracers = [trace.new_arg(pval) for pval in in_pvals if not pval.is_known()]
in_args = merge_lists(in_knowns, in_tracers, in_consts)
ans = yield in_args, {}
assert isinstance(ans, (list, tuple)), (
f"Got unexpected return type when tracing function to jaxpr: {ans}")
assert all(isinstance(x, core.Tracer) or core.valid_jaxtype(x) for x in ans), (
f"Got unexpected return type when tracing function to jaxpr: {ans}")
if isinstance(instantiate, bool):
instantiate = [instantiate] * len(ans)
out_tracers = map(trace.full_raise, map(core.full_lower, ans))
out_tracers = [trace.instantiate_const(trace.full_raise(t)) if inst else t
for inst, t in zip(instantiate, out_tracers)]
out_tracers_ = [t for t in out_tracers if not t.is_known()]
jaxpr, out_consts, env = tracers_to_jaxpr(in_tracers, out_tracers_)
return out_tracers, jaxpr, out_consts, env
# The below variant implements an optimization where residuals which are also
# inputs are indicated in auxiliary data rather than passed as outputs.
# TODO(mattjj): update all callers to use this version, delete other version.
@lu.transformation
def trace_to_subjaxpr_nounits_fwd(
main: core.MainTrace,
instantiate: Union[bool, Sequence[bool]],
in_pvals: Sequence[PartialVal]):
assert all([isinstance(pv, PartialVal) for pv in in_pvals]), in_pvals
out_tracers, jaxpr, out_consts, env = yield from _trace_to_subjaxpr_nounits(
main, instantiate, in_pvals)
out_pvals = [t.pval for t in out_tracers]
# Which out_consts (aka residuals) are just forwarded inputs? Check obj id.
in_consts = [pval.get_known() for pval in in_pvals if pval.is_known()]
id_map = {id(c): i for i, c in enumerate(in_consts)}
fwds: List[Optional[int]] = [id_map.get(id(c)) for c in out_consts]
pruned_consts = [c for c, fwd in zip(out_consts, fwds) if fwd is None]
del out_tracers
yield jaxpr, (fwds, out_pvals, pruned_consts, env)
FreeVar = namedtuple('FreeVar', ['val'])
ConstVar = namedtuple('ConstVar', ['val'])
LambdaBinding = namedtuple('LambdaBinding', [])
class JaxprEqnRecipe(NamedTuple):
eqn_id: Any
in_tracers: Sequence[JaxprTracer]
out_tracer_refs: Sequence[ref[JaxprTracer]]
out_avals: Sequence[core.AbstractValue]
primitive: Primitive
params: Dict[str, Any]
effects: core.Effects
source_info: source_info_util.SourceInfo
def new_eqn_recipe(in_tracers: Sequence[JaxprTracer],
out_tracers: Sequence[JaxprTracer],
primitive: Primitive,
params: Dict[str, Any],
effects: core.Effects,
source_info: source_info_util.SourceInfo
) -> JaxprEqnRecipe:
# TODO(necula): move these checks to core.check_jaxpr, and call in more places
if primitive.call_primitive or primitive.map_primitive:
assert "call_jaxpr" in params
assert ("donated_invars" not in params or
len(params["donated_invars"]) == len(params["call_jaxpr"].invars))
if primitive.map_primitive:
assert ("in_axes" in params and
len(params["in_axes"]) == len(params["call_jaxpr"].invars))
assert ("donated_invars" in params and
len(params["donated_invars"]) == len(params["call_jaxpr"].invars))
out_avals = [core.raise_to_shaped(t.aval) for t in out_tracers]
return JaxprEqnRecipe(object(), tuple(in_tracers), map(ref, out_tracers),
out_avals, primitive, params, effects, source_info)
def recipe_to_eqn(getvar: Callable[[JaxprTracer], Atom],
recipe: JaxprEqnRecipe) -> core.JaxprEqn:
(_, in_tracers, out_tracer_refs, out_avals, prim, params, eff, src) = recipe
invars = [getvar(t) for t in in_tracers]
out_tracers = [t_ref() for t_ref in out_tracer_refs]
outvars = [DropVar(a) if t is None else getvar(t) # type: ignore
for a, t in zip(out_avals, out_tracers)]
return new_jaxpr_eqn(invars, outvars, prim, params, eff, src)
def tracers_to_jaxpr(
in_tracers: Sequence[JaxprTracer],
out_tracers: Sequence[JaxprTracer]
) -> Tuple[Jaxpr, Tuple[Any, ...], Tuple[Any, ...]]:
"""Constructs Jaxpr given tracers for inputs and outputs.
Params:
in_tracers: the tracers that were created for the function inputs
out_tracers: the tracers that were output by the function.
Returns: a triple of a `Jaxpr`, a list of constant values corresponding to
the `constvars` in the returned Jaxps, and a list of environment values.
The vars for the environment values have been prepended to the Jaxpr's
`invars`.
"""
gensym = core.gensym()
t_to_var: Dict[TracerId, Var] = {}
consts: Dict[Var, Any] = {}
env: Dict[Var, JaxprTracer] = {}
constid_to_var: Dict[ConstId, Var] = {} # for deduplication
def get_atom(t: JaxprTracer) -> Atom:
return t.recipe if type(t.recipe) is Literal else t_to_var[id(t)]
def newvar(t: JaxprTracer) -> Var:
var = gensym(type_substitute(t.aval))
assert t_to_var.setdefault(id(t), var) is var
return var
def type_substitute(aval: AbstractValue) -> AbstractValue:
if isinstance(aval, DShapedArray):
# Replace any Tracers in aval.shape with Vars or Literal values
shape = [get_atom(d) if type(d) is JaxprTracer else d for d in aval.shape]
shape = [d.val if type(d) is Literal else d for d in shape]
aval = aval.update(shape=tuple(shape))
return aval
processed_eqn_ids = set()
eqns: List[core.JaxprEqn] = []
for t in toposort([*in_tracers, *out_tracers]):
r = t.recipe
if isinstance(r, JaxprEqnRecipe):
# TODO broadcast_in_dim can create a new tracer, not present in parents
if r.eqn_id not in processed_eqn_ids:
in_atoms = map(get_atom, r.in_tracers)
outvars = [DropVar(type_substitute(a)) if rf() is None else newvar(rf())
for a, rf in zip(r.out_avals, r.out_tracer_refs)]
eqns.append(new_jaxpr_eqn(in_atoms, outvars, r.primitive, r.params,
r.effects, r.source_info))
processed_eqn_ids.add(r.eqn_id)
elif isinstance(r, LambdaBinding):
if not any(t is in_tracer for in_tracer in in_tracers):
raise core.escaped_tracer_error(t, f"Tracer not in input tracers: {t}")
newvar(t)
elif isinstance(r, ConstVar):
var = constid_to_var.get(id(r.val))
if var is None:
var = constid_to_var[id(r.val)] = newvar(t)
consts[var] = r.val
t_to_var[id(t)] = var
elif isinstance(r, FreeVar):
env[newvar(t)] = r.val # type: ignore
elif isinstance(r, Literal):
pass
elif r is None:
assert False
else:
raise TypeError(r)
env_vars, env_vals = unzip2(env.items())
const_vars, const_vals = unzip2(consts.items())
effects = core.join_effects(*(eqn.effects for eqn in eqns))
jaxpr = Jaxpr(const_vars, [*env_vars, *map(get_atom, in_tracers)],
map(get_atom, out_tracers), eqns, effects)
config.jax_enable_checks and core.check_jaxpr(jaxpr)
# del getvar # needed to avoid cyclic-reference closure, apparently!
return jaxpr, const_vals, env_vals
@weakref_lru_cache
def convert_constvars_jaxpr(jaxpr: Jaxpr) -> Jaxpr:
"""Moves the constvars to the start of invars."""
config.jax_enable_checks and core.check_jaxpr(jaxpr)
lifted_jaxpr = Jaxpr(constvars=(),
invars=jaxpr.constvars + jaxpr.invars,
outvars=jaxpr.outvars, eqns=jaxpr.eqns,
effects=jaxpr.effects)
config.jax_enable_checks and core.check_jaxpr(lifted_jaxpr)
return lifted_jaxpr
def convert_envvars_to_constvars(jaxpr: Jaxpr, num_env_vars: int) -> Jaxpr:
config.jax_enable_checks and core.check_jaxpr(jaxpr)
env_vars, invars = split_list(jaxpr.invars, [num_env_vars])
converted_jaxpr = Jaxpr(constvars=jaxpr.constvars + env_vars,
invars=invars, outvars=jaxpr.outvars, eqns=jaxpr.eqns,
effects=jaxpr.effects)
config.jax_enable_checks and core.check_jaxpr(converted_jaxpr)
return converted_jaxpr
def partial_eval_jaxpr_nounits(
jaxpr: ClosedJaxpr, unknowns: Sequence[bool],
instantiate: Union[bool, Sequence[bool]],
) -> Tuple[ClosedJaxpr, ClosedJaxpr, List[bool], List[AbstractValue]]:
"""Unzip a jaxpr in two by data dependence into 'known' and 'unknown' parts.
That is, given a jaxpr and a sequence of booleans indicating which jaxpr
inputs (i.e. invars) are considered unknown, produce two jaxprs, a list of
booleans representing which of the original jaxpr's outputs are unknown (i.e.
have a data dependence on an unknown input), and a list of abstract values
representing residuals (part of the first jaxpr's output and the second
jaxpr's input). The two jaxprs result from partitioning the original jaxpr's
first-order primitive applications based on whether all the inputs to the
application are known (in which case the application is represented in the
'known' jaxpr and its result is considered known) or whether any inputs to the
application are unknown (in which case the application is represented in the
'unknown' jaxpr and its result is considered unknown). Higher-order primitives
are recursively unzipped in two.
The `instantiate` argument can be used to ensure some outputs are lifted into
the 'unknown' jaxpr.
For example, give an input jaxpr:
{ lambda ; a:f32[] b:f32[]. let
c:f32[] = cos a
d:f32[] = sin a