-
Notifications
You must be signed in to change notification settings - Fork 69
/
prims.py
3625 lines (2869 loc) · 114 KB
/
prims.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
from enum import auto, Enum
from numbers import Number
from functools import reduce, wraps
import operator
import builtins
import math
from types import NoneType
from typing import Union, Type, Any, List, Dict, Tuple, Optional
from collections.abc import Callable
from collections.abc import Callable, Hashable, Sequence
import torch
from thunder.core.langctxs import LanguageContext, register_langctx, Languages, langctx
#
# Creates and registers the torch language context
#
# NOTE That this is done separately from the definition of thunder.torch operations, because the
# language context must be available before those operations are defined
_method_name_to_fn_map: dict[str, Callable] = {}
# Creates and registers the primitive language context
# TODO RC1 Register additinoal methods and record operations on numbers
class PrimCtx(LanguageContext):
def __init__(self):
super().__init__("primitive")
def has_method(self, id: str) -> bool:
return id in _method_name_to_fn_map
def get_method(self, id: Any, *args, **kwargs) -> Callable:
# Note: concrete implmenetations should only raise AttributeError or
# return None for "missing" methods as the proxies will
# route __getattr__ to here and hasattr relies on __getattr__
# throwing AttributeError (only) when the attribute does
# not exist.
# Verifies that the method is not being called on any tensor proxies
inps, _ = tree_flatten((args, kwargs))
for x in inps:
if isinstance(x, TensorProxy):
raise ValueError(f"Attempting to call {id} from the primitive language context on a tensor proxy")
method: None | Callable = _method_name_to_fn_map.get(id, None)
if method is None:
raise ValueError(f"The {self.name} language context has no method {id}")
return method
primctx = PrimCtx()
register_langctx(Languages.PRIMS, primctx)
# Registers a method with the torch language context
def register_method(method_name: str, method: Callable, /) -> None:
_method_name_to_fn_map[method_name] = method
from thunder.core.symbol import Symbol, BoundSymbol, default_python_printer
from thunder.core.proxies import (
CollectionProxy,
TensorProxy,
NumberProxy,
is_proxyable,
proxy,
numberproxy,
pytype,
pyval,
Proxy,
StringProxy,
TupleProxy,
AnyProxy,
)
import thunder.core.codeutils as codeutils
from thunder.core.codeutils import Printable
import thunder.core.utils as utils
import thunder.core.baseutils as baseutils
import thunder.core.devices as devices
import thunder.core.dtypes as dtypes
from thunder.core.pytree import tree_flatten, tree_unflatten, tree_map
from thunder.core.trace import get_tracectx
from thunder.core.langctxs import langctx, LanguageContext, register_langctx, Languages
#
# Primitives and helpers for defining them
#
class PrimIDs(Enum):
# Unpacking and input validation prims
ASSERT_TENSOR_METADATA = auto()
CHECK_TENSOR_SHAPE_AND_METADATA = auto()
CHECK_NONE = auto()
CHECK_EMPTY = auto()
CHECK_LITERAL_LIKE = auto()
CHECK_TYPE = auto()
CHECK_INSTANCE = auto()
CHECK_NUMBER_TYPE_AND_VALUE = auto()
CHECK_BOOL_CONVERSION = auto()
CHECK_STRING_VALUE = auto()
CHECK_LEN = auto()
ASSERT_COMPARE = auto()
PYTHON_VARS = auto()
UNPACK_FUNCTION_OBJ = auto()
UNPACK_CACHE_INFO = auto()
UNPACK_ATTR = auto()
UNPACK_GETITEM = auto()
UNPACK_EMPTY_DICT = auto()
UNPACK_ITER = auto()
UNPACK_NEXT = auto()
UNPACK_KEY = auto()
UNPACK_SEQUENCE = auto()
UNPACK_TRIVIAL = auto()
UNPACK_TUPLE = auto()
UNPACK_LIST = auto()
UNPACK_DICT_KEY = auto()
CONSTRUCT_TUPLE = auto()
PACK_SETITEM = auto()
# TODO: UNPACK_SET
# Utility prims
COMMENT = auto()
DEL = auto()
PRINT = auto()
RETURN = auto()
# Prims related to transforms (like grad)
GET_GRAD = auto()
PUT_GRAD = auto()
# Data movement and transformation prims
CONVERT_ELEMENT_TYPE = auto()
DEVICE_PUT = auto()
NUMPY_ARRAY_TO_TORCH_TENSOR = auto() # Experimental
# Tensor creation prims
EXOGENOUS_LIKE = auto()
FULL = auto()
IOTA = auto()
UNIFORM = auto()
UNIFORM_PHILOX = auto()
RANDN = auto()
TENSOR_FROM_SEQUENCE = auto()
# Probability distribution-related ops
MULTINOMIAL = auto()
# Reshaping and permuting prims
BROADCAST_IN_DIM = auto()
CAT = auto()
FLIP = auto()
RESHAPE = auto()
SLICE = auto()
SQUEEZE = auto()
TRANSPOSE = auto()
UNFOLD = auto()
VIEW = auto()
# Memory layout prims (Experimental)
STRIDE_ORDER = auto()
# Elementwise unary prims
PY_ABS = auto()
ABS = auto()
ACOS = auto()
ACOSH = auto()
ASIN = auto()
ASINH = auto()
ATAN = auto()
ATANH = auto()
BITWISE_NOT = auto()
CEIL = auto()
COS = auto()
COSH = auto()
DIGAMMA = auto()
ERF = auto()
ERFC = auto()
ERFCINV = auto()
ERFINV = auto()
EXP = auto()
EXP2 = auto()
EXPM1 = auto()
FLOOR = auto()
ISFINITE = auto()
LGAMMA = auto()
LOG = auto()
LOG10 = auto()
LOG1P = auto()
LOG2 = auto()
NDTRI = auto()
NEG = auto()
RECIPROCAL = auto()
ROUND = auto()
RSQRT = auto()
SIGN = auto()
SIGNBIT = auto()
SIN = auto()
SINH = auto()
SQRT = auto()
TAN = auto()
TANH = auto()
TRUNC = auto()
REAL = auto()
# Elementwise binary prims
ADD = auto()
ATAN2 = auto()
BITWISE_AND = auto()
BITWISE_OR = auto()
BITWISE_XOR = auto()
DIV = auto()
EQ = auto()
PY_FLOORDIV = auto()
FMOD = auto()
GE = auto()
GT = auto()
LE = auto()
LT = auto()
MAXIMUM = auto()
MINIMUM = auto()
MUL = auto()
NE = auto()
NEXTAFTER = auto()
POW = auto()
REMAINDER = auto()
SUB = auto()
ZETA = auto()
# Conditional prims
WHERE = auto()
# Reduction prims
AMAX = auto()
AMIN = auto()
PROD = auto()
SUM = auto()
VAR = auto()
VAR_MEAN = auto()
ARGMAX = auto()
ARGMIN = auto()
TOPK = auto()
# Scatter and gather prims (Experimental!)
INDEX_ADD = auto()
INDEX_PUT = auto()
SCATTER_ADD = auto()
TAKE = auto()
TAKE_ALONG_AXIS = auto()
# Linear algebra prims (Mostly experimental)
MATMUL = auto()
# NN prims (Experimental!)
CONVOLUTION = auto()
EMBEDDING = auto()
EMBEDDING_BACKWARD = auto()
LINEAR = auto()
PAD = auto()
BATCH_NORM = auto()
# Memory access methods
ITEM = auto()
COPY_ = auto()
class OpTags(Enum):
# TODO -- Consider renaming this tag
# The operation manipulates a tensor's shape
# These operations may return a view or a new tensor in PyTorch
# e.g. slice, squeeze, transpose, view, reshape
SHAPE_OP = auto()
REDUCTION_OP = auto()
RANDOM_OP = auto()
# Ops that might cause a device sync
DEVICE_SYNC_OP = auto()
# Labels operations that should not be removed by the dead code elimination (DCE) pass
DONT_DCE = auto()
# TODO RC1 Document this function and describe the parts of a primitive
def make_prim(
id,
name,
*,
meta,
python_printer=default_python_printer,
python_impl: None | Callable = None,
tags: None | Sequence[OpTags] = None,
method_name: None | str = None,
_bind_postprocess: None | Callable = None,
_print_as_impl: bool = False,
):
sym = Symbol(
name=name,
meta=langctx(Languages.PRIMS)(meta),
id=id,
is_prim=True,
tags=tags,
python_printer=python_printer,
python_impl=python_impl,
_bind_postprocess=_bind_postprocess,
_print_as_impl=_print_as_impl,
)
if method_name is not None:
register_method(method_name, sym)
return sym
#
# Unpacking and input validation prims
#
# TODO Add a tag for these assertions
# TODO Review performance (comparisons and string construction)
# TODO Change shape check into a rank check once constraints are generated on dimension lengths separately
# TODO The conversions to torch devices and dtypes could be done at compile time instead of runtime
# Checks type, shape, device, and dtype
def assert_tensor_metadata_impl(
t: torch.Tensor, /, shape: tuple[int], device: devices.Device, dtype: dtypes.dtype, requires_grad: bool
) -> None:
dtype = dtypes.to_torch_dtype(dtype)
if (
type(t) in (torch.Tensor, torch.nn.Parameter)
and tuple(t.shape) == shape
and str(t.device) == str(device)
and t.dtype == dtype
and t.requires_grad == requires_grad
):
return
raise AssertionError(
f"Object had unexpected metadata. Expected type Tensor/nn.Parameter (without subclass), shape {shape}, device {str(device)}, dtype {dtype}, and {requires_grad=}, but found type {type(t)}, shape {tuple(t.shape)}, device {str(t.device)}, and requires_grad {t.requires_grad}"
)
def assert_tensor_metadata_meta(
t: torch.Tensor, /, shape: tuple[int], device: devices.Device, dtype: dtypes.dtype, requires_grad: bool
) -> None:
return
assert_tensor_metadata = make_prim(
PrimIDs.ASSERT_TENSOR_METADATA,
"assert_tensor_metadata",
meta=assert_tensor_metadata_meta,
python_impl=assert_tensor_metadata_impl,
_print_as_impl=True,
)
# TODO: Or maybe assert op to include comparisons?
def assert_compare_impl(v: Any, /, op: str, other: Any) -> None:
cmp_impls = {
"<": lambda x, y: x < y,
"<=": lambda x, y: x <= y,
"==": lambda x, y: x == y,
"!=": lambda x, y: x != y,
">": lambda x, y: x > y,
">=": lambda x, y: x >= y,
}
if cmp_impls[op](v, other):
return
raise AssertionError(f"Comparison constraint violated: {v} {op} {other}")
def assert_compare_meta(v: Any, /, op: str, other: Any) -> None:
return
assert_compare = make_prim(
PrimIDs.ASSERT_COMPARE,
"assert_compare",
meta=assert_compare_meta,
python_impl=assert_compare_impl,
_print_as_impl=True,
)
def python_vars_impl(arg: None | str = None, /) -> dict:
if arg is None:
return vars()
return vars(arg)
def python_vars_meta(arg: None | str = None, /) -> Proxy:
return Proxy()
def python_vars_printer(
bsym: BoundSymbol, out_printables: Any, arg_printables: Sequence[Printable], kwarg_printables: dict[str, Printable]
) -> str:
utils.check(
len(arg_printables) <= 1,
lambda: f"Expected at most one argument for vars but got {arg_printables}",
exception_type=AssertionError,
)
utils.check(
len(kwarg_printables) == 0,
lambda: f"Expected no kwargs for vars but got {kwarg_printables}",
exception_type=AssertionError,
)
utils.check(
type(out_printables) is Proxy,
lambda: f"Expected a proxy output for vars, but got {out_printables=}",
exception_type=AssertionError,
)
out_str = codeutils.prettyprint(out_printables)
(args,) = arg_printables
arg_str = codeutils.prettyprint(args)
utils.check(
type(arg_str) is str,
lambda: f"Expected a string argument for vars, but got {arg_str}",
exception_type=AssertionError,
)
# NOTE Implementing vars (mruberry)
# thunder programs are compiled by Python's builtin compile
# this means that their globals() is defined by the
# dictionary passed to compile, and we want to be able
# to access a variety of global dicts, including the
# globals dict of the "main" module (which is not directly
# accessible, as best I can tell). To do this, for now
# at least, we assume that vars() is always being called
# in one of our "prologue" traces, where we add the key
# "__globals_dicts" to the dict that we pass to compile,
# and it contains the various global dictionaries indexed
# by their module names. In the future the prologue
# trace could import modules (other than the main module)
# and call vars directly on those module names, which
# would be more readable.
# Special cases dunder main
# TODO Review this -- maybe we should acquire the globals by
# getting dunder globals on the compiled function itself
s = f"{out_str} = globals()['__global_dicts'][{arg_str}]"
return s
python_vars = make_prim(
PrimIDs.PYTHON_VARS,
"python_vars",
meta=python_vars_meta,
python_printer=python_vars_printer,
python_impl=python_vars_impl,
)
def _collectify(x: Any, *, name: str | None = None) -> Any:
if isinstance(x, Proxy):
return x
if baseutils.is_collection(x):
return CollectionProxy(x, name=name)
return x
# TODO RC1 Align with ASSERT_TENSOR_METADATA
# NOTE The device is stored as a string for easier, more readable comparisons
def _check_tensor_shape_and_metadata_meta(
t: TensorProxy, shape: tuple[int, ...], device: str, dtype: torch.dtype, requires_grad: bool
) -> None:
# Validates types
baseutils.check_type(t, TensorProxy)
baseutils.check_valid_shape(shape)
baseutils.check_type(device, str)
baseutils.check_type(dtype, torch.dtype)
baseutils.check_type(requires_grad, bool)
check_tensor_shape_and_metadata = make_prim(
PrimIDs.CHECK_TENSOR_SHAPE_AND_METADATA,
"check_tensor_metadata",
meta=_check_tensor_shape_and_metadata_meta,
tags=(OpTags.DONT_DCE,),
)
def _check_none_meta(p: AnyProxy, /) -> None:
# Validates types
baseutils.check_type(p, AnyProxy)
baseutils.check(pytype(p) is NoneType, lambda: f"Expected {p} to be None")
check_none = make_prim(
PrimIDs.CHECK_NONE,
"check_none",
meta=_check_none_meta,
tags=(OpTags.DONT_DCE,),
)
def _check_empty_meta(seq: tuple | list | dict, /) -> None:
# Validates types
baseutils.check_type(seq, (tuple, list, dict))
baseutils.check(len(seq) == 0, lambda: f"Expected an empty sequence, but found {seq=}")
check_empty = make_prim(
PrimIDs.CHECK_EMPTY,
"check_empty",
meta=_check_empty_meta,
tags=(OpTags.DONT_DCE,),
)
def _check_len_meta(seq: tuple | list | dict, length: int, /) -> None:
# Validates types
# baseutils.check_type(seq, (tuple, list, dict))
baseutils.check_type(length, (int,))
check_len = make_prim(
PrimIDs.CHECK_LEN,
"check_len",
meta=_check_len_meta,
tags=(OpTags.DONT_DCE,),
)
def _check_literal_like_meta(p: AnyProxy, v: Any, /) -> None:
# Validates types
baseutils.check_type(p, AnyProxy)
baseutils.check(pyval(p) == v, lambda: f"Expected {p} to be equal to {v}")
check_literal_like = make_prim(
PrimIDs.CHECK_LITERAL_LIKE,
"check_literal_like",
meta=_check_literal_like_meta,
tags=(OpTags.DONT_DCE,),
)
def _check_type_meta(x: Any, typ: type, /) -> None:
# Validates types
baseutils.check(typ, type, lambda: f"Expected a type for check_type, but found {typ}")
baseutils.check(pytype(x) is typ, lambda: f"Different types for {pytype(x)} and {typ}")
check_type = make_prim(
PrimIDs.CHECK_TYPE,
"check_type",
meta=_check_type_meta,
tags=(OpTags.DONT_DCE,),
)
def _check_instance_meta(x: Any, types: tuple[type], /) -> None:
# Validates types
baseutils.check(types, tuple, lambda: f"Expected a tuple of types for check_instance, but found {types}")
for typ in types:
baseutils.check(
type(typ) is type,
lambda: f"Expected a tuple of types for check_instance, but found an object of type {type(typ)} in the tuple",
)
baseutils.check(any(map(lambda y: issubclass(pytype(x), y), types)), lambda: f"Type {pytype(x)} was not in {types}")
check_instance = make_prim(
PrimIDs.CHECK_INSTANCE,
"check_instance",
meta=_check_instance_meta,
tags=(OpTags.DONT_DCE,),
)
def _check_number_type_and_value_meta(n: NumberProxy, value: Number, /) -> None:
# Validates types
baseutils.check_type(n, NumberProxy)
baseutils.check_type(value, Number)
baseutils.check(pytype(n) == pytype(value), lambda: f"Different types for {n} and {value}")
check_number_type_and_value = make_prim(
PrimIDs.CHECK_NUMBER_TYPE_AND_VALUE,
"check_number_type_and_value",
meta=_check_number_type_and_value_meta,
tags=(OpTags.DONT_DCE,),
)
def _check_bool_conversion_meta(n: NumberProxy, b: bool, /) -> None:
# Validates types
baseutils.check_type(n, NumberProxy)
baseutils.check_type(b, bool)
check_bool_conversion = make_prim(
PrimIDs.CHECK_BOOL_CONVERSION,
"check_bool_conversion",
method_name="check_bool_conversion",
meta=_check_bool_conversion_meta,
tags=(OpTags.DONT_DCE,),
)
def _check_string_value_meta(s: StringProxy, value: str) -> None:
# Validates types
baseutils.check_type(s, StringProxy)
baseutils.check_type(value, str)
check_string_value = make_prim(
PrimIDs.CHECK_STRING_VALUE,
"check_string_value",
meta=_check_string_value_meta,
tags=(OpTags.DONT_DCE,),
)
def unpack_trivial_impl(x: Any, /, *, name: str | None = None) -> Any:
return x
def unpack_trivial_meta(x: Any, /, *, name: str | None = None) -> Any:
return _collectify(x, name=name)
def unpack_trivial_printer(
bsym: BoundSymbol, out_printables: Any, arg_printables: Sequence[Printable], kwarg_printables: dict[str, Printable]
) -> str:
utils.check(
len(arg_printables) == 0,
lambda: f"Expected zero arguments for unpack_trivial but got {arg_printables}",
exception_type=AssertionError,
)
utils.check(
len(kwarg_printables) <= 1,
lambda: f"Expected at most one kwarg for unpack_trivial but got {kwarg_printables}",
exception_type=AssertionError,
)
result_str = "_" if bsym.output is None else f"{codeutils.prettyprint(out_printables, with_type=True)}"
s = f"# {result_str}{' (unused)' if bsym.output is None else ''}"
return s
# Removes the inputs from unpack_trivial, so it appears to have no input
def _unpack_trivial_bind_postprocess(bsym: BoundSymbol) -> None:
bsym.args = ()
unpack_trivial = make_prim(
PrimIDs.UNPACK_TRIVIAL,
"unpack_trivial",
meta=unpack_trivial_meta,
python_printer=unpack_trivial_printer,
python_impl=unpack_trivial_impl,
_bind_postprocess=_unpack_trivial_bind_postprocess,
)
def unpack_function_obj_impl(x: Any, /, *, name: str | None = None) -> Any:
return x
def unpack_function_obj_meta(x: Any, /, *, name: str | None = None) -> Any:
return x
def unpack_function_obj_printer(
bsym: BoundSymbol, out_printables: Any, arg_printables: Sequence[Printable], kwarg_printables: dict[str, Printable]
) -> str:
utils.check(
len(arg_printables) == 0,
lambda: f"Expected zero arguments for unpack_function_obj but got {arg_printables}",
exception_type=AssertionError,
)
utils.check(
len(kwarg_printables) <= 1,
lambda: f"Expected at most one kwarg for unpack_function_obj but got {kwarg_printables}",
exception_type=AssertionError,
)
result_str = "_" if bsym.output is None else f"{codeutils.prettyprint(out_printables, with_type=True)}"
s = f"{result_str} = globals()['__function_obj']"
return s
unpack_function_obj = make_prim(
PrimIDs.UNPACK_FUNCTION_OBJ,
"unpack_function_obj",
meta=unpack_function_obj_meta,
python_printer=unpack_function_obj_printer,
python_impl=unpack_function_obj_impl,
_bind_postprocess=_unpack_trivial_bind_postprocess,
)
def unpack_cache_info_impl(x: Any, /, *, name: str | None = None) -> Any:
return x
def unpack_cache_info_meta(x: Any, /, *, name: str | None = None) -> Any:
return x
def unpack_cache_info_printer(
bsym: BoundSymbol, out_printables: Any, arg_printables: Sequence[Printable], kwarg_printables: dict[str, Printable]
) -> str:
utils.check(
len(arg_printables) == 0,
lambda: f"Expected zero arguments for unpack_cache_info but got {arg_printables}",
exception_type=AssertionError,
)
utils.check(
len(kwarg_printables) <= 1,
lambda: f"Expected at most one kwarg for unpack_cache_info but got {kwarg_printables}",
exception_type=AssertionError,
)
result_str = "_" if bsym.output is None else f"{codeutils.prettyprint(out_printables, with_type=True)}"
s = f"{result_str} = thunder._get_cache_info()"
return s
unpack_cache_info = make_prim(
PrimIDs.UNPACK_CACHE_INFO,
"unpack_cache_info",
meta=unpack_cache_info_meta,
python_printer=unpack_cache_info_printer,
python_impl=unpack_cache_info_impl,
_bind_postprocess=_unpack_trivial_bind_postprocess,
)
# TODO Restore const criteria
def unpack_sequence_meta(x: Sequence | CollectionProxy, l: int, /) -> list:
if isinstance(x, CollectionProxy):
x = x.collection()
utils.check_type(x, Sequence)
utils.check_type(l, int)
baseutils.check(len(x) == l, lambda x=x, l=l: f"Expected the length of {x=} to be {l=}")
return list(_collectify(y) for y in x)
def _make_parts_into_line_or_lines(parts: list[str], out: list[str] | None = None) -> list[str]:
if out is None:
lines = []
else:
lines = out
line_parts = []
pos = 0
for p in parts:
if pos and pos + len(p) > 80:
lines.append("".join(line_parts) + "\\")
line_parts = []
pos = 0
line_parts.append(p)
pos += len(p)
lines.append("".join(line_parts))
return lines
# TODO Possibly put the length in the code to show the requirement
def unpack_sequence_printer(
bsym: BoundSymbol, out_printables: Any, arg_printables: Sequence[Printable], kwarg_printables: dict[str, Printable]
):
utils.check(
len(arg_printables) == 2,
lambda: f"Expected two arguments for unpack_sequence but got {arg_printables}",
exception_type=AssertionError,
)
utils.check(
len(kwarg_printables) == 0,
lambda: f"Expected no kwargs for unpack_sequence but got {kwarg_printables}",
exception_type=AssertionError,
)
utils.check_type(bsym.output, Sequence)
x, l = arg_printables
call_str = f"{codeutils.prettyprint(x)}"
# Short-circuits if there's nothing to unpack:
if len(bsym.output) == 0:
return f"# {call_str} (empty sequence)"
parts = [f"{codeutils.prettyprint(out, literals_as_underscores=True)}, " for out in out_printables]
parts.append(f"= {call_str}")
lines = _make_parts_into_line_or_lines(parts)
return lines
def unpack_sequence_impl(x: Sequence, l: int) -> list:
return list(x)
unpack_sequence = make_prim(
PrimIDs.UNPACK_SEQUENCE,
"unpack_sequence",
meta=unpack_sequence_meta,
python_printer=unpack_sequence_printer,
python_impl=unpack_sequence_impl,
)
# NOTE This actually returns a new tuple of the elements, which allows the elements of tup
# to appear in the symbol's output. If the original tuple is a proxy and it were just
# returned directly then the output would just be the tuple
def _unpack_tuple_meta(tup: tuple, /) -> tuple:
utils.check_type(tup, tuple)
def _proxy(x: Any):
if isinstance(x, Proxy):
return x
return proxy(x)
return tuple(_proxy(x) for x in tup)
def _unpack_tuple_printer(
bsym: BoundSymbol, out_printables: Any, arg_printables: Sequence[Printable], kwarg_printables: dict[str, Printable]
):
utils.check(
len(arg_printables) == 1,
lambda: f"Expected one argument for unpack_tuple but got {arg_printables}",
exception_type=AssertionError,
)
utils.check(
len(kwarg_printables) == 0,
lambda: f"Expected no kwargs for unpack_tuple but got {kwarg_printables}",
exception_type=AssertionError,
)
utils.check_type(bsym.output, tuple)
(x,) = arg_printables
call_str = f"{codeutils.prettyprint(x)}"
# Short-circuits if there's nothing to unpack:
if len(bsym.output) == 0:
return f"# {call_str} (empty tuple)"
parts = [f"{codeutils.prettyprint(out, literals_as_underscores=True)}, " for out in out_printables]
parts.append(f"= {call_str}")
lines = _make_parts_into_line_or_lines(parts)
return lines
unpack_tuple = make_prim(
PrimIDs.UNPACK_TUPLE,
"unpack_tuple",
meta=_unpack_tuple_meta,
python_printer=_unpack_tuple_printer,
)
# NOTE This actually returns a new tuple of the elements, which allows the elements of tup
# to appear in the symbol's output. If the original tuple is a proxy and it were just
# returned directly then the output would just be the tuple
def _unpack_list_meta(lst: list, /) -> list:
utils.check_type(lst, list)
def _proxy(x: Any):
if isinstance(x, Proxy):
return x
return proxy(x)
return list(_proxy(x) for x in lst)
def _unpack_list_printer(
bsym: BoundSymbol, out_printables: Any, arg_printables: Sequence[Printable], kwarg_printables: dict[str, Printable]
):
utils.check(
len(arg_printables) == 1,
lambda: f"Expected one argument for unpack_list but got {arg_printables}",
exception_type=AssertionError,
)
utils.check(
len(kwarg_printables) == 0,
lambda: f"Expected no kwargs for unpack_list but got {kwarg_printables}",
exception_type=AssertionError,
)
utils.check_type(bsym.output, list)
(x,) = arg_printables
call_str = f"{codeutils.prettyprint(x)}"
# Short-circuits if there's nothing to unpack:
if len(bsym.output) == 0:
return f"# {call_str} (empty list)"
parts = [f"{codeutils.prettyprint(out, literals_as_underscores=True)}, " for out in out_printables]
parts.append(f"= {call_str}")
lines = _make_parts_into_line_or_lines(parts)
return lines
unpack_list = make_prim(
PrimIDs.UNPACK_LIST,
"unpack_list",
meta=_unpack_list_meta,
python_printer=_unpack_list_printer,
)
def _construct_tuple_meta(tup: tuple, /) -> tuple:
utils.check_type(tup, tuple)
return TupleProxy(tup)
construct_tuple = make_prim(PrimIDs.CONSTRUCT_TUPLE, "construct_tuple", meta=_construct_tuple_meta)
# NOTE UNPACK_ATTR is intended only to be bound to directly, and not called
def unpack_attr_meta(o: Any, key: str) -> Any:
raise NotImplementedError
def unpack_attr_printer(
bsym: BoundSymbol, out_printables: Any, arg_printables: Sequence[Printable], kwarg_printables: dict[str, Printable]
):
utils.check(
len(arg_printables) == 2,
lambda: f"Expected two arguments for unpack_attr but got {arg_printables}",
exception_type=AssertionError,
)
utils.check(
len(kwarg_printables) == 0,
lambda: f"Expected no kwargs for unpack_attr but got {kwarg_printables}",
exception_type=AssertionError,
)
# Converts printables to strings
origin, key = arg_printables
origin_str = codeutils.prettyprint(origin)
keystr = key
outstr = codeutils.prettyprint(out_printables, with_type=True, literals_as_underscores=True)
return f"{outstr} = {origin_str}.{keystr}"
def unpack_attr_impl(o: Any, key: str) -> Any:
return getattr(o, key)
unpack_attr = make_prim(
PrimIDs.UNPACK_ATTR,
"unpack_attr",
meta=unpack_attr_meta,
python_printer=unpack_attr_printer,
python_impl=unpack_attr_impl,
)
# NOTE PACK_SETITEM is intended only to be bound to directly, and not called
def pack_setitem_meta(o: Any, key: Any, value: Any) -> Any:
raise NotImplementedError
def pack_setitem_printer(
bsym: BoundSymbol, out_printables: Any, arg_printables: Sequence[Printable], kwarg_printables: dict[str, Printable]
):
utils.check(
len(arg_printables) == 3,
lambda: f"Expected three arguments for pack_setitem but got {arg_printables}",
exception_type=AssertionError,
)
utils.check(
len(kwarg_printables) == 0,
lambda: f"Expected no kwargs for pack_setitem but got {kwarg_printables}",
exception_type=AssertionError,
)
# Converts printables to strings
obj, key, value = arg_printables
obj_str = codeutils.prettyprint(obj)
key_str = codeutils.prettyprint(key)
value_str = codeutils.prettyprint(value)
return f"{obj_str}[{key_str}] = {value_str}"
def pack_setitem_impl(o: Any, key: Any, v: Any) -> None:
o[key] = value
return None
pack_setitem = make_prim(
PrimIDs.PACK_SETITEM,
"unpack_setitem",
meta=pack_setitem_meta,
python_printer=pack_setitem_printer,
python_impl=pack_setitem_impl,
tags=(OpTags.DONT_DCE,),
)
# NOTE UNPACK_GETITEM is intended only to be bound to directly, and not called
def unpack_getitem_meta(o: Any, key: Any) -> Any:
raise NotImplementedError
def unpack_getitem_printer(
bsym: BoundSymbol, out_printables: Any, arg_printables: Sequence[Printable], kwarg_printables: dict[str, Printable]
):
utils.check(