-
Notifications
You must be signed in to change notification settings - Fork 23.6k
/
Copy pathlowering.py
7046 lines (5797 loc) · 224 KB
/
lowering.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
# mypy: allow-untyped-defs
from __future__ import annotations
import contextlib
import dataclasses
import functools
import itertools
import logging
import math
import operator
import os
import textwrap
import warnings
from collections import defaultdict
from collections.abc import Iterable, Sequence
from typing import Any, Callable, cast, Optional, TYPE_CHECKING, TypeVar, Union
from typing_extensions import ParamSpec
from unittest.mock import patch
import sympy
import torch
import torch.ao.quantization.fx._decomposed
import torch.fx
import torch.utils._pytree as pytree
from torch._dynamo.utils import counters
from torch._higher_order_ops.associative_scan import associative_scan_op
from torch._higher_order_ops.triton_kernel_wrap import triton_kernel_wrapper_mutation
from torch._prims_common import (
canonicalize_dim,
canonicalize_dims,
check,
dtype_to_type,
elementwise_dtypes,
ELEMENTWISE_TYPE_PROMOTION_KIND,
get_computation_dtype,
is_boolean_dtype,
is_float_dtype,
is_integer_dtype,
Number,
)
from torch.fx.experimental.sym_node import magic_methods, method_to_operator
from torch.utils._ordered_set import OrderedSet
from torch.utils._sympy.functions import (
CeilDiv,
FloorDiv,
Identity,
IntTrueDiv,
ModularIndexing,
)
from .._dynamo.utils import import_submodule
from . import config, inductor_prims, ir, test_operators # NOQA: F401
from .decomposition import decompositions, get_decompositions
from .ir import (
DtypeView,
ExpandView,
IndexingConstant,
IRNode,
is_triton,
OnlineSoftmaxReduction,
ops_wrapper,
PermuteView,
Pointwise,
Reduction,
SqueezeView,
TensorBox,
validate_ir,
View,
)
from .utils import (
ceildiv,
decode_device,
is_dynamic,
is_gpu,
is_pointwise_use,
needs_fallback_due_to_atomic_add_limitations,
pad_listlike,
register_op_dtype_propagation_rules,
sympy_product,
use_scatter_fallback,
)
from .virtualized import ops, V
if TYPE_CHECKING:
from .ops_handler import ReductionType
_T = TypeVar("_T")
_P = ParamSpec("_P")
# TODO(jansel): we should implement decomps or lowerings for these
# https://github.com/pytorch/torchdynamo/issues/327
FALLBACK_ALLOW_LIST = OrderedSet(
[
"torchvision::roi_align",
"aten::index_add",
]
)
log = logging.getLogger(__name__)
lowerings: dict[Union[Callable[..., Any], str], Callable[..., Any]] = {}
# Use maybe_layout_constraints to access this dict, we lazily register tag-based layout constraints
_maybe_layout_constraints: dict[
torch._ops.OpOverload, Optional[Callable[..., Any]]
] = {}
fallbacks = OrderedSet[torch._ops.OpOverload]()
aten = torch.ops.aten
tr_c10d = torch.ops.tr_c10d
prims = torch.ops.prims
needs_realized_inputs = OrderedSet[torch._ops.OpOverload]()
foreach_ops = OrderedSet[torch._ops.OpOverload](
[torch._higher_order_ops._foreach_map] # type: ignore[list-item]
)
# TODO(rec): torch._higher_order_ops._foreach_map is not an OpOverload
# so why is it in foreach_ops?
inplace_foreach_ops = OrderedSet[torch._ops.OpOverload]()
inplaceable_foreach_ops: dict[torch._ops.OpOverload, torch._ops.OpOverload] = {}
quantized_decomposed = torch.ops.quantized_decomposed
def cur_node_has_non_foreach_users():
for node in V.graph.current_node.users:
for user in node.users:
if not (user.op == "call_function" and (user.target in foreach_ops)):
return True
return False
# group by device, whether any of the inputs are dynamic
# note arg_pairs may or may not be a pair
# foreach_map for example just passes output buffers here
def group_foreach_args(arg_pairs: Iterable[Union[tuple[Any, Any], Any]]):
out = defaultdict(list)
unpack_args = False
for i, args in enumerate(arg_pairs):
if not isinstance(args, Iterable):
unpack_args = True
args = (args,)
use_foreach = (
not is_dynamic(*args) or config.combo_kernel_foreach_dynamic_shapes
)
device = None
for t in args:
if isinstance(t, TensorBox):
device = t.data.get_device()
break
assert device is not None, "foreach op should have at least one tensor arg"
if unpack_args:
(args,) = args
out[(device, use_foreach)].append((i, args))
return out
def maybe_layout_constraints(fn: Callable[..., Any]) -> Optional[Callable[..., Any]]:
"""Get layout constraints. Returns None if there are no layout constraints."""
if not isinstance(fn, torch._ops.OpOverload):
# Only OpOverloads have layout constraints.
return None
if fn in _maybe_layout_constraints:
return _maybe_layout_constraints[fn]
# OpOverload with custom lowerings override tag-based layout constraints
if fn in lowerings:
_maybe_layout_constraints[fn] = None
return None
# We lazily register tag-based layout constraints.
def handle_layout_constraint_tag(tag):
if tag is torch._C.Tag.needs_fixed_stride_order:
_maybe_layout_constraints[fn] = constrain_to_fx_strides
return _maybe_layout_constraints[fn]
elif tag is torch._C.Tag.flexible_layout:
_maybe_layout_constraints[fn] = None
return None
else:
raise AssertionError(f"Unknown layout constraint tag: {tag}")
tag = get_layout_constraint_tag(fn)
return handle_layout_constraint_tag(tag)
def get_layout_constraint_tag(fn):
tags_by_priority = [
torch._C.Tag.needs_fixed_stride_order,
torch._C.Tag.flexible_layout,
]
for tag in tags_by_priority:
if tag in fn.tags:
return tag
if torch._library.utils.is_builtin(fn):
return torch._C.Tag.flexible_layout
return getattr(torch._C.Tag, config.custom_op_default_layout_constraint)
def assert_nyi(cond, msg):
if not cond:
raise NotImplementedError(f"inductor does not support {msg}")
def add_needs_realized_inputs(fn):
if isinstance(fn, (list, set, tuple, OrderedSet)): # noqa: set_linter
return [add_needs_realized_inputs(x) for x in fn]
needs_realized_inputs.add(fn)
if isinstance(fn, torch._ops.OpOverloadPacket):
needs_realized_inputs.update(
getattr(fn, overload) for overload in fn.overloads()
)
def add_layout_constraint(fn, constraint):
if isinstance(fn, torch._ops.OpOverloadPacket):
for overload in fn.overloads():
_maybe_layout_constraints[getattr(fn, overload)] = constraint
else:
_maybe_layout_constraints[fn] = constraint
add_needs_realized_inputs(
[
aten.as_strided,
aten.as_strided_copy,
aten.avg_pool2d,
aten.avg_pool2d_backward,
aten.bmm,
aten.convolution,
aten.convolution_backward,
aten.max_pool2d_with_indices,
aten.max_pool2d_with_indices_backward,
aten.mm,
aten.upsample_nearest2d,
aten._upsample_nearest_exact2d,
aten._int_mm,
]
)
# TODO(jansel): ezyang says we won't need this in the future, try removing it
# based on https://github.com/pytorch/pytorch/blob/9e3eb329df8f701/c10/core/ScalarType.h#L28
DTYPE_ID_LOOKUP = {
0: torch.uint8,
1: torch.int8,
2: torch.int16,
3: torch.int32,
4: torch.int64,
5: torch.float16,
6: torch.float32,
7: torch.float64,
8: torch.complex32,
9: torch.complex64,
10: torch.complex32,
11: torch.bool,
15: torch.bfloat16,
# TODO(jansel): add quantized types?
# _(c10::qint8, QInt8) /* 12 */
# _(c10::quint8, QUInt8) /* 13 */
# _(c10::qint32, QInt32) /* 14 */
# _(c10::quint4x2, QUInt4x2) /* 16 */
# _(c10::quint2x4, QUInt2x4) /* 17 */
}
def decode_dtype(dtype: int):
if not isinstance(dtype, int):
return dtype
assert dtype in DTYPE_ID_LOOKUP, f"id {dtype} missing from DTYPE_ID_LOOKUP"
dtype = DTYPE_ID_LOOKUP[dtype]
return dtype
def is_integer_type(x):
if isinstance(x, TensorBox):
return is_integer_dtype(x.get_dtype()) or is_boolean_dtype(x.get_dtype())
elif isinstance(x, sympy.Expr):
return x.is_integer is True # type: ignore[attr-defined]
else:
return isinstance(x, int)
def is_boolean_type(x):
if isinstance(x, TensorBox):
return is_boolean_dtype(x.get_dtype())
else:
return isinstance(x, bool)
def get_promoted_dtype(*args, type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND):
def construct_input(inp):
if isinstance(inp, (Number, sympy.Basic)):
return inp
else:
dim = len(inp.get_size())
# construct a tmp tensor to feed into torch.result_type
return torch.zeros([1] * dim, dtype=inp.get_dtype())
inps = [construct_input(arg) for arg in args]
_, dtype = elementwise_dtypes(*inps, type_promotion_kind=type_promotion_kind)
return dtype
def get_overloads(aten_fn):
if not isinstance(aten_fn, (list, tuple)):
aten_fn = [aten_fn]
else:
aten_fn = list(aten_fn)
for fn in list(aten_fn):
if isinstance(fn, torch._ops.OpOverloadPacket):
for overload in fn.overloads():
other_fn = getattr(fn, overload)
if other_fn not in lowerings:
aten_fn.append(other_fn)
return aten_fn
def in_namespace(op, namespace):
if isinstance(op, torch._ops.OpOverloadPacket):
return namespace in op._qualified_op_name
elif isinstance(op, torch._ops.OpOverload):
return namespace in op.name()
return False
def transform_args(
args: list[Any],
kwargs: dict[str, Any],
broadcast: bool,
type_promotion_kind: Optional[ELEMENTWISE_TYPE_PROMOTION_KIND],
convert_input_to_bool: bool,
) -> tuple[list[Any], dict[str, Any]]:
args_indices = [i for i, x in enumerate(args) if isinstance(x, TensorBox)]
kwargs_indices = [k for k, v in kwargs.items() if isinstance(v, TensorBox)]
# check that there's something to transform
if not args_indices and not kwargs_indices:
return args, kwargs
if type_promotion_kind or convert_input_to_bool:
if convert_input_to_bool:
dtype = torch.bool
else:
# FIXME this is a crude approximation for promoting args
promoting_args = [
a
for a in args
if isinstance(a, (Number, sympy.Basic)) or hasattr(a, "dtype")
]
# only consider tensor kwargs for promotion, for now
promoting_args.extend(a for a in kwargs.values() if hasattr(a, "dtype"))
dtype = get_promoted_dtype(
*promoting_args,
type_promotion_kind=type_promotion_kind, # type: ignore[arg-type]
)
device = (
args[args_indices[0]] if args_indices else kwargs[kwargs_indices[0]]
).get_device()
# sometimes args are an immutable list so we can't mutate them
def promote(arg):
if isinstance(arg, TensorBox):
return to_dtype(arg, dtype)
elif isinstance(arg, ir.Constant):
return ir.Constant(value=arg.value, dtype=dtype, device=device)
else:
return arg
args = [promote(a) for a in args]
kwargs = {k: promote(v) for k, v in kwargs.items()}
if broadcast:
broadcasted = broadcast_tensors(
*list(
itertools.chain(
(args[i] for i in args_indices),
(kwargs[k] for k in kwargs_indices),
)
)
)
size = list(broadcasted[0].get_size())
for i, x in zip(args_indices, broadcasted[: len(args_indices)]):
args[i] = x
for k, x in zip(kwargs_indices, broadcasted[len(args_indices) :]):
kwargs[k] = x
for i in range(len(args)):
if isinstance(args[i], ir.Constant):
args[i] = ExpandView.create(args[i], size)
for k in kwargs:
if isinstance(kwargs[k], ir.Constant):
kwargs[k] = ExpandView.create(kwargs[k], size)
return args, kwargs
def _register_foreach_lowering(aten_fn, decomp_fn):
"""
Add a foreach lowering to lowerings dict.
Arguments:
aten_fn: torch.ops.aten.* fn we are lowering
decomp_fn: alternate implementation on our IR
broadcast: True to apply broadcasting to tensor inputs
type_promotion_kind: kind of type promotion applied to tensor inputs, `None` means no type promotion
convert_input_to_bool: some logical ops require inputs are converted to bool
"""
@functools.wraps(decomp_fn)
def wrapped(*args, **kwargs):
assert len(args) <= 2
out = decomp_fn(*args, **kwargs)
validate_ir(out)
return out
aten_fns = get_overloads(aten_fn)
foreach_ops.update(aten_fns)
lowerings.update(dict.fromkeys(aten_fns, wrapped))
return wrapped
def _register_lowering(
aten_fn,
decomp_fn,
broadcast,
type_promotion_kind: Optional[ELEMENTWISE_TYPE_PROMOTION_KIND],
convert_input_to_bool,
):
"""
Add a lowering to lowerings dict
Arguments:
aten_fn: torch.ops.aten.* fn we are lowering
decomp_fn: alternate implementation on our IR
broadcast: True to apply broadcasting to tensor inputs
type_promotion_kind: kind of type promotion applied to tensor inputs, `None` means no type promotion
convert_input_to_bool: some logical ops require inputs are converted to bool
"""
@functools.wraps(decomp_fn)
def wrapped(*args, **kwargs):
args: list[Any] = list(args)
kwargs: dict[str, Any] = dict(kwargs)
unpacked = False
# TODO maybe we need to use pytrees here
if len(args) == 1 and isinstance(args[0], (list, tuple)):
unpacked = True
args = list(args[0])
if not all(
(fn in fallbacks or in_namespace(fn, "_c10d_functional")) for fn in aten_fn
):
# explicitly assert for "out=" ops for better error messages
assert not any(x == "out" for x in kwargs.keys()), (
"out= ops aren't yet supported"
)
args, kwargs = transform_args(
args, kwargs, broadcast, type_promotion_kind, convert_input_to_bool
)
if unpacked:
args = [args]
out = decomp_fn(*args, **kwargs)
validate_ir(out)
return out
aten_fn = get_overloads(aten_fn)
lowerings.update(dict.fromkeys(aten_fn, wrapped))
return wrapped
def register_lowering(
aten_fn,
broadcast=False,
type_promotion_kind: Optional[
ELEMENTWISE_TYPE_PROMOTION_KIND
] = ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
convert_input_to_bool=False,
) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]:
"""
Shim to support decorator syntax.
"""
return functools.partial(
_register_lowering,
aten_fn,
broadcast=broadcast,
type_promotion_kind=type_promotion_kind,
convert_input_to_bool=convert_input_to_bool,
)
def broadcast_symbolic_shapes(a, b):
"""
Broadcasting logic based on symbolic shapes.
We give the shapes 0 and 1 concrete values, while all other shapes
are symbolic sympy formulas.
"""
output = []
for x, y in itertools.zip_longest(reversed(a), reversed(b), fillvalue=sympy.S.One):
if V.graph.sizevars.shape_env.evaluate_expr(
sympy.Eq(y, 1), size_oblivious=True
):
output.append(x)
elif V.graph.sizevars.shape_env.evaluate_expr(
sympy.Eq(x, 1), size_oblivious=True
):
output.append(y)
else:
V.graph.sizevars.guard_equals(x, y)
if len(sympy.expand(y).free_symbols) < len(sympy.expand(x).free_symbols):
output.append(y) # prefer shorter formula
else:
output.append(x)
return tuple(reversed(output))
def promote_constants(inputs, override_return_dtype=None, type_promotion_kind=None):
assert override_return_dtype is None or type_promotion_kind is None, (
"only one of override_return_dtype or type_promotion_kind may be given"
)
if override_return_dtype is None and type_promotion_kind is None:
type_promotion_kind = ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
if not any(isinstance(x, (sympy.Basic, int, float)) for x in inputs):
return inputs
if all(isinstance(x, (int, float, sympy.Basic)) for x in inputs):
dtype = override_return_dtype or get_promoted_dtype(
*inputs, type_promotion_kind=type_promotion_kind
)
def const_func(x):
if isinstance(x, sympy.Basic):
return ir.IndexingConstant(
index=x, dtype=dtype, device=decode_device(None)
)
else:
return ir.Constant(value=x, dtype=dtype, device=decode_device(None))
return [const_func(x) for x in inputs]
ex = next(x for x in inputs if isinstance(x, (TensorBox, ExpandView, ir.Constant)))
out = []
for x in inputs:
if isinstance(x, (int, float)):
out.append(
ExpandView.create(
ir.Constant(
value=x, dtype=ex.get_dtype(), device=ex.get_device_or_error()
),
list(ex.get_size()),
)
)
elif isinstance(x, sympy.Basic):
out.append(
ExpandView.create(
IndexingConstant(
index=x, dtype=ex.get_dtype(), device=ex.get_device_or_error()
),
list(ex.get_size()),
)
)
else:
out.append(x)
return out
def make_pointwise(
fn,
override_return_dtype=None,
override_device=None,
override_fn_when_input_bool=None,
override_fn_when_gpu_float64=None,
allow_alpha=False,
triton_fallback=None,
):
def inner(*inputs: TensorBox, alpha=None):
if triton_fallback is not None and any(
isinstance(inp, IRNode) and is_triton(inp) for inp in inputs
):
assert not allow_alpha # not implemented
return triton_fallback(*inputs)
inputs = promote_constants(inputs, override_return_dtype)
if allow_alpha:
if alpha is not None and alpha != 1:
inputs = list(inputs)
inputs[-1] = mul(inputs[-1], alpha)
else:
assert alpha is None
loaders = [x.make_loader() for x in inputs]
ranges = inputs[0].get_size()
dtype = override_return_dtype or inputs[0].get_dtype()
is_gpu_device = is_gpu(decode_device(inputs[0].get_device()).type)
for other in inputs[1:]:
assert isinstance(other, ir.BaseConstant) or len(ranges) == len(
other.get_size()
), f"ndim mismatch {fn} {ranges} {other.get_size()}"
# in tracing, we will annotate pointwise nodes that correspond to the output of
# a pointwise node that would have been run in eager. intermediary pointwise nodes
# during decompositions are not annotated.
low_pr_fp = (torch.bfloat16, torch.float16)
emulate_precision_casts = (
V.graph is not None
and getattr(V.graph, "current_node", None) is not None
and V.graph.current_node.meta is not None
and V.graph.current_node.meta.get("low_precision_pointwise_barrier", False)
and dtype in low_pr_fp
)
def inner_fn(index):
assert len(index) == len(ranges), f"wrong ndim {index} {ranges}"
if dtype == torch.bool and override_fn_when_input_bool is not None:
return override_fn_when_input_bool(*[load(index) for load in loaders])
elif (
override_fn_when_gpu_float64
and is_gpu_device
and dtype == torch.float64
):
return override_fn_when_gpu_float64(*[load(index) for load in loaders])
else:
inputs_loaded = []
for inp_index, load in enumerate(loaders):
out = load(index)
inp_dtype = inputs[inp_index].get_dtype()
if emulate_precision_casts and inp_dtype in low_pr_fp:
downcast = ops.to_dtype(out, inp_dtype, use_compute_types=False)
out = ops.to_dtype(downcast, inp_dtype)
inputs_loaded.append(out)
out = fn(*inputs_loaded)
if emulate_precision_casts:
# fp16/bf16 kernels are computed in fp32. Casting down to fp16/bf16 here,
# then upcasting again, to emulate casts that eager would do.
downcast = ops.to_dtype(out, dtype, use_compute_types=False)
return ops.to_dtype(downcast, dtype)
return out
if not override_device:
device = None
for i in inputs:
if is_gpu(i.get_device().type):
device = i.get_device()
break
if not device:
device = inputs[0].get_device()
device = override_device or device
return Pointwise.create(
device=device, # type: ignore[arg-type]
dtype=dtype,
inner_fn=inner_fn,
ranges=ranges,
)
return inner
def make_foreach_pointwise(pw_fn, allow_alpha=False):
def inner(*inputs: list[list[TensorBox]], alpha=1):
realize_outputs = (
len(V.graph.current_node.users) == 0
or V.graph.current_node.target in inplace_foreach_ops
or cur_node_has_non_foreach_users()
)
a_list_input = None
for input in inputs:
if isinstance(input, (list, tuple)):
a_list_input = input
break
assert a_list_input is not None, (
"at least one input must be a list to a foreach op"
)
# broadcast scalar inputs to match length of list inputs
broadcast_inputs = []
for input in inputs:
if not isinstance(input, (list, tuple)):
broadcast_inputs.append([input] * len(a_list_input))
else:
broadcast_inputs.append(input)
groups = group_foreach_args(zip(*broadcast_inputs))
outputs = [None] * len(a_list_input)
for (device, use_foreach), group in groups.items():
operation_list: list[str] = []
for (
output_ind,
args,
) in group:
if allow_alpha:
output = pw_fn(*args, alpha=alpha)
else:
output = pw_fn(*args)
outputs[output_ind] = output
if (
V.graph.has_feature(device, BackendFeature.FOREACH)
and use_foreach
and realize_outputs
):
output.realize()
operation_list.append(output.get_operation_name())
if operation_list:
V.graph.register_operation_list(operation_list)
assert all(x is not None for x in outputs)
return outputs
return inner
def to_dtype(x: TensorBox, dtype: torch.dtype, copy=False):
src_dtype = x.get_dtype()
if src_dtype == dtype:
return clone(x) if copy else x
def _to_dtype(x):
return ops.to_dtype(x, dtype, src_dtype=src_dtype)
return make_pointwise(_to_dtype, override_return_dtype=dtype)(x)
@register_lowering(torch._higher_order_ops._foreach_map, type_promotion_kind=None)
def _foreach_map(subgraph, *args, **kwargs):
"""
This lowers an invocation of foreach_map
The way this works is that an arbitrary N-arg func is provided by the user, looped over by the
polyfill with the same semantics as a foreach op (a loop applying an n-ary function to n args)
and then traced into a subgraph by dynamo.
This code allows us to inline the subgraph into the main graph lowering using the PontwiseSubgraphLowering.
The graph outputs represent the vertically fused sequence of ops, and then register_operation_list
below registers the buffers as horizontally fuseable in the scheduler.
"""
from .subgraph_lowering import PointwiseSubgraphLowering
inputs = args
gm = subgraph.graph_module
pw_subgraph = PointwiseSubgraphLowering(gm, root_graph_lowering=V.graph)
with V.set_graph_handler(pw_subgraph): # type: ignore[arg-type]
pw_subgraph.run(*inputs)
sub_outputs = pw_subgraph.graph_outputs
# group outputs by device and register as foreach
assert sub_outputs # mypy lol
groups = group_foreach_args(sub_outputs)
outputs = [None] * len(sub_outputs)
for (device, use_foreach), group in groups.items():
operation_list: list[str] = []
for (
output_ind,
output,
) in group:
outputs[output_ind] = output
if V.graph.has_feature(device, BackendFeature.FOREACH) and use_foreach:
output.realize()
operation_list.append(output.get_operation_name())
if operation_list:
V.graph.register_operation_list(operation_list)
assert all(x is not None for x in outputs)
return outputs
@register_lowering(prims.convert_element_type, type_promotion_kind=None)
def _convert_element_type(x: TensorBox, dtype: torch.dtype):
if dtype.is_complex or x.get_dtype().is_complex:
if x.get_size():
# Decompose since aa aten fallback is more friendly for c++ codegen.
# This decomposition doesn't work for empty tensor, which needs more investigation.
dst = empty_like(x, dtype=dtype)
ir.InplaceCopyFallback.create(dst, x)
return dst
else:
return fallback_handler(
prims.convert_element_type.default, add_to_fallback_set=False
)(x, dtype)
return to_dtype(x, dtype, copy=True)
def to_dtype_bitcast(x: TensorBox, dtype: torch.dtype, *, copy=False):
x_dtype = x.get_dtype()
if x_dtype == dtype:
return clone(x) if copy else x
def _get_primitive_bitwidth(dtype):
if dtype.is_floating_point:
return torch.finfo(dtype).bits
else:
return torch.iinfo(dtype).bits
src_bits = _get_primitive_bitwidth(x_dtype)
dst_bits = _get_primitive_bitwidth(dtype)
if src_bits != dst_bits:
# fallback to aten eager implementation for differing bitwidths
return fallback_handler(aten.view.dtype)(x, dtype)
else:
return TensorBox(DtypeView.create(x, dtype))
@register_lowering(aten.view.dtype, type_promotion_kind=None)
def _view_dtype(x: TensorBox, dtype: torch.dtype):
if dtype.is_complex or x.get_dtype().is_complex:
return TensorBox.create(
ir.ComplexView.create(torch.ops.aten.view.dtype, x, dtype)
)
return to_dtype_bitcast(x, dtype)
def to_device(x: TensorBox, device: torch.device, *, copy=False, non_blocking=False):
device = decode_device(device)
if x.get_device() == device:
return clone(x) if copy else x
return TensorBox.create(ir.DeviceCopy.create(x, device, non_blocking))
@register_lowering(prims.device_put, type_promotion_kind=None)
def _device_put(x: TensorBox, device: torch.device, non_blocking=False):
return to_device(x, device, copy=True, non_blocking=non_blocking)
def register_pointwise(
aten_fn,
name=None,
broadcast=True,
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
convert_input_to_bool=False,
override_return_dtype=None,
override_fn_when_input_bool=None,
allow_alpha=False,
use_libdevice_for_f64=False,
triton_fallback=None,
):
"""A pointwise function that maps ops.{name} to inputs"""
name = name or aten_fn.__name__
fn = ops_wrapper(name)
if use_libdevice_for_f64:
fn_libdevice = ops_wrapper("libdevice_" + name)
register_op_dtype_propagation_rules(
"libdevice_" + name, type_promotion_kind, override_return_dtype
)
register_op_dtype_propagation_rules(
name, type_promotion_kind, override_return_dtype
)
if override_fn_when_input_bool is not None:
override_fn_when_input_bool = ops_wrapper(override_fn_when_input_bool)
fn = make_pointwise(
fn,
override_return_dtype=override_return_dtype,
override_fn_when_input_bool=override_fn_when_input_bool,
override_fn_when_gpu_float64=fn_libdevice if use_libdevice_for_f64 else None, # type: ignore[possibly-undefined]
allow_alpha=allow_alpha,
triton_fallback=triton_fallback,
)
fn = register_lowering(
aten_fn,
broadcast=broadcast,
type_promotion_kind=type_promotion_kind,
convert_input_to_bool=convert_input_to_bool,
)(fn)
if hasattr(prims, name):
register_lowering(
getattr(prims, name),
type_promotion_kind=None,
convert_input_to_bool=convert_input_to_bool,
)(fn)
return fn
def register_frexp():
"""A pointwise function that maps ops.frexp to inputs"""
name = "frexp"
frexp = ops_wrapper("frexp")
def frexp0(*args, **kwargs):
return frexp(*args, **kwargs)[0] # type: ignore[index]
def frexp1(*args, **kwargs):
return frexp(*args, **kwargs)[1] # type: ignore[index]
pw_fns = [
make_pointwise(frexp0),
make_pointwise(frexp1, override_return_dtype=torch.int32),
]
def fn(*args, **kwargs):
return pw_fns[0](*args, **kwargs), pw_fns[1](*args, **kwargs)
fn = register_lowering(
aten.frexp,
)(fn)
if hasattr(prims, name):
register_lowering(
getattr(prims, name),
type_promotion_kind=None,
)(fn)
return fn
register_frexp()
def register_foreach_pointwise(
aten_fn,
pointwise_lowering_fn,
allow_alpha=False,
):
fn = make_foreach_pointwise(pointwise_lowering_fn, allow_alpha=allow_alpha)
fn = _register_foreach_lowering(aten_fn, fn)
return fn
@register_lowering(aten.where, broadcast=False, type_promotion_kind=None)
def where(cond, a, b):
def fn(*args):
return ops.where(*args)
if isinstance(a, (float, int)):
a = constant_like(a)(b)
if isinstance(b, (float, int)):
b = constant_like(b)(a)
args = [cond, a, b]
dtype = get_promoted_dtype(
args[1], args[2], type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
)
indices = [i for i, x in enumerate(args) if isinstance(x, TensorBox)]
for i, x in zip(indices, broadcast_tensors(*[args[i] for i in indices])):
args[i] = x
for i in range(len(args)):
if isinstance(args[i], ir.Constant):
args[i] = ExpandView.create(args[i], list(args[indices[0]].get_size()))
return make_pointwise(fn, override_return_dtype=dtype)(
args[0], to_dtype(args[1], dtype), to_dtype(args[2], dtype)
)
@register_lowering(aten.broadcast_tensors, broadcast=False, type_promotion_kind=None)
def broadcast_tensors(*inputs):
if len(inputs) == 1 and isinstance(inputs[0], (list, tuple)):
return broadcast_tensors(*inputs[0])
target: list[sympy.Expr] = functools.reduce(
broadcast_symbolic_shapes, [x.get_size() for x in inputs], []
)
outputs = []
for x in inputs:
sizes = x.get_size()
if len(sizes) != len(target) or any(
(
(
V.graph.sizevars.shape_env.evaluate_expr(
sympy.Eq(a, 1), size_oblivious=True
)
and not V.graph.sizevars.shape_env.evaluate_expr(
sympy.Eq(b, 1), size_oblivious=True
)
)
or (
not V.graph.sizevars.shape_env.evaluate_expr(
sympy.Eq(a, 1), size_oblivious=True
)
and V.graph.sizevars.shape_env.evaluate_expr(
sympy.Eq(b, 1), size_oblivious=True
)
)
)
for a, b in zip(sizes, target)
):
x = expand(x, target)
outputs.append(x)
return outputs
@register_lowering([aten.alias, aten.detach, aten.detach_, aten.lift, prims.view_of])
def nop(x):
return x # AOT autograd handles this for us
if hasattr(aten, "lift_fresh"):