-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmojo_backend.py
More file actions
4799 lines (4121 loc) · 184 KB
/
Copy pathmojo_backend.py
File metadata and controls
4799 lines (4121 loc) · 184 KB
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 collections
import contextlib
import dataclasses
import functools
import itertools
import logging
import math
import os
import textwrap
from collections.abc import Iterable, Sequence
from functools import lru_cache
from typing import Any, Callable, cast, Optional, TYPE_CHECKING, Union
import sympy
from sympy.printing.precedence import PRECEDENCE
import torch
import torch._logging
import torch.utils._pytree as pytree
from torch._dynamo.device_interface import get_interface_for_device
from torch._dynamo.utils import identity, preserve_rng_state
from torch._prims_common import is_integer_dtype
from torch.utils._ordered_set import OrderedSet
from torch.utils._sympy.functions import CeilDiv, FloorDiv, ModularIndexing
from torch.utils._triton import has_triton_package
from torch.utils._sympy.symbol import (free_symbol_is_type, prefix_str,
symbol_is_type, SymT)
from torch.utils._sympy.value_ranges import ValueRanges
from torch._inductor import config, ir, metrics
from torch._inductor.async_compile import AsyncCompile
from torch._inductor.codecache import code_hash, get_path, PyCodeCache, write_atomic
from torch._inductor.ops_handler import DefaultHandler
from torch._inductor.runtime import triton_heuristics
from torch._inductor.runtime.benchmarking import benchmarker
from torch._inductor.runtime.hints import (
AutotuneHint,
DeviceProperties,
TRITON_MAX_BLOCK,
TRITON_MAX_RSPLIT,
)
from torch._inductor.runtime.runtime_utils import get_max_y_grid, next_power_of_2
from torch._inductor.scheduler import (BaseSchedulerNode, FusedSchedulerNode,
Scheduler, SchedulerNode)
from torch._inductor.utils import (
cache_on_self,
DelayReplaceLine,
get_bounds_index_expr,
get_fused_kernel_name,
get_kernel_metadata,
is_welford_reduction,
Placeholder,
prefix_is_reduction,
sympy_dot,
sympy_product,
sympy_subs,
triton_type,
triton_version_uses_attrs_dict,
upcast_compute_type,
)
from torch._inductor.virtualized import _ops as ops, ReductionType, StoreMode, V
from torch._inductor.wrapper_benchmark import get_kernel_category_by_source_code
from torch._inductor.codegen.block_analysis import BlockPatternMatcher
from torch._inductor.codegen.common import (
ArgName,
BackendFeature,
ConstexprArg,
CSE,
CSEVariable,
DeferredLine,
IndentedBuffer,
InplacedBuffer,
OpOverrides,
PythonPrinter,
RemovedArg,
SizeArg,
TensorArg,
WorkspaceArg,
WorkspaceZeroMode,
)
from torch._inductor.codegen.simd import (
constant_repr,
IterationRanges,
IterationRangesEntry,
IterationRangesRoot,
SIMDKernel,
SIMDScheduling,
)
from torch._inductor.codegen.triton_utils import (
config_of,
equal_1_arg_indices,
non_constexpr_signature,
should_unwrap_unspec_arg,
signature_to_meta,
)
from torch._inductor.codegen.wrapper import SymbolicCallArg
if TYPE_CHECKING:
from types import ModuleType
from typing import TypeVar
from torch._inductor.dtype_propagation import DtypePropagationOpsHandler
from torch._inductor.ir import IRNode
from torch._inductor.codegen.simd_kernel_features import SIMDKernelFeatures
_T = TypeVar("_T")
log = logging.getLogger(__name__)
perf_hint_log = torch._logging.getArtifactLogger(__name__, "perf_hints")
schedule_log = torch._logging.getArtifactLogger(__name__, "schedule")
fusion_log = torch._logging.getArtifactLogger(__name__, "fusion")
async_compile = AsyncCompile()
def gen_mojo_args(argdefs, signature):
result_params = ""
remaining = []
constexprs = []
for arg in signature:
if isinstance(arg, ConstexprArg):
constexprs.append(arg)
else:
remaining.append(arg)
if len(constexprs) != 0:
result_params += '['
for carg in constexprs:
result_params += f"{carg.name}: UInt32, "
if len(constexprs) != 0:
result_params += ']'
result = '('
def translate_dtype(dtype):
if dtype == torch.int32:
return "Int32"
elif dtype == torch.int64:
return "Int64"
elif dtype == torch.float32:
return "Float32"
elif dtype == torch.float64:
return "Float64"
elif dtype == torch.bool:
return "Bool"
elif dtype == torch.bfloat16:
return "BFloat16"
elif dtype == torch.float16:
return "Float16"
else:
raise ValueError(f"FIXME: Unknown dtype: {dtype}")
for arg in remaining:
if isinstance(arg, TensorArg):
result += f"{arg.name}: tl.Ptr[{translate_dtype(arg.dtype)}], "
elif isinstance(arg, SizeArg):
result += f"owned {arg.name}: UInt32, "
elif isinstance(arg, WorkspaceArg):
result += f"{arg.name}: tl.Ptr[{translate_dtype(arg.dtype)}], "
elif isinstance(arg, RemovedArg):
pass
else:
raise ValueError(f"FIXME: Unknown arg type: {type(arg)}")
result += ')'
return result_params, result
def make_binding_template(kernel_name, signature):
count = 0
for i, arg in enumerate(signature):
if isinstance(arg, ConstexprArg):
continue
elif isinstance(arg, RemovedArg):
continue
elif isinstance(arg, TensorArg):
count += 1
elif isinstance(arg, SizeArg):
count += 1
elif isinstance(arg, WorkspaceArg):
count += 1
else:
raise ValueError(f"FIXME: Unknown arg type: {type(arg)}")
typedef_str = "typedef void (*fn_ptr_t)("
for i, arg in enumerate(signature):
if isinstance(arg, ConstexprArg):
continue
elif isinstance(arg, RemovedArg):
continue
elif isinstance(arg, TensorArg):
typedef_str += "void *"
elif isinstance(arg, SizeArg):
typedef_str += "unsigned"
elif isinstance(arg, WorkspaceArg):
typedef_str += "void *"
else:
raise ValueError(f"FIXME: Unknown arg type: {type(arg)}")
if i != count - 1:
typedef_str += ",\n"
typedef_str += ");\n"
template = """
#include <Python.h>
#include <dlfcn.h>
#include <stdint.h>
"""
dir = os.getcwd()
abs_so_path = dir + "/" + kernel_name + "_mojo.so"
template += typedef_str
template += """
static fn_ptr_t p_fn_ptr = NULL;
static void *p_fn_handle = NULL;
static int
load_symbol(const char *lib_name, void **handle_out, const char *sym_name, void **sym_out)
{
void *handle = dlopen(lib_name, RTLD_LAZY | RTLD_LOCAL);
if (!handle)
{
PyErr_Format(PyExc_ImportError, "Failed to load shared library '%s': %s", lib_name, dlerror());
return -1;
}
dlerror(); /* clear any existing error */
void *fn = dlsym(handle, sym_name);
const char *err = dlerror();
if (err || !fn)
{
PyErr_Format(PyExc_ImportError, "Failed to locate symbol '%s' in '%s': %s", sym_name, lib_name, err ? err : "unknown error");
dlclose(handle);
return -1;
}
*handle_out = handle; /* leak intentionally so functions remain valid */
*sym_out = fn;
return 0;
}
static int resolve_all_symbols(void) {
if (load_symbol(""" + f"\"{abs_so_path}\"" + """, &p_fn_handle, """ + f"\"{kernel_name}\"" + """, (void **)&p_fn_ptr) < 0) {
return -1;
}
return 0;
}
static PyObject *
py_fn_impl(PyObject *self, PyObject *args) {
"""
parse_str = ""
for arg in signature:
if isinstance(arg, ConstexprArg):
continue
elif isinstance(arg, RemovedArg):
continue
elif isinstance(arg, TensorArg):
template += f"unsigned long long {arg.name};\n"
parse_str += "K"
elif isinstance(arg, SizeArg):
template += f"unsigned {arg.name};\n"
parse_str += "I"
elif isinstance(arg, WorkspaceArg):
template += f"unsigned long long {arg.name};\n"
parse_str += "K"
else:
raise ValueError(f"FIXME: Unknown arg type: {type(arg)}")
template += """
if (!PyArg_ParseTuple(args, """ + f"\"{parse_str}\"" + """, """ + ", ".join(
[
f"&{arg.name}"
for arg in signature if not isinstance(arg, ConstexprArg)
and not isinstance(arg, RemovedArg)
]) + """)) {
return NULL;
}
if (!p_fn_ptr) {
PyErr_SetString(PyExc_RuntimeError, "make_4d_causal_mask_invoke symbol not resolved");
return NULL;
}
p_fn_ptr(
"""
for i, arg in enumerate(signature):
if isinstance(arg, ConstexprArg):
continue
elif isinstance(arg, RemovedArg):
continue
elif isinstance(arg, TensorArg):
template += f"(void *)(uintptr_t) {arg.name}"
elif isinstance(arg, SizeArg):
template += f"{arg.name}"
elif isinstance(arg, WorkspaceArg):
template += f"(void *)(uintptr_t) {arg.name}"
else:
raise ValueError(f"FIXME: Unknown arg type: {type(arg)}")
if i != count - 1:
template += ","
template += "\n"
template += """
);
Py_RETURN_NONE;
}
static PyMethodDef module_methods[] = {
{""" + f"\"{kernel_name}\"" + """, py_fn_impl, METH_VARARGS, "torch compile generated"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef bindings_module = {
PyModuleDef_HEAD_INIT,
""" + f"\"{kernel_name}\"" + """, /* m_name */
NULL, /* m_doc */
-1, /* m_size */
module_methods /* m_methods */
};
PyMODINIT_FUNC
PyInit_""" + kernel_name + """_bindings(void)
{
if (resolve_all_symbols() < 0)
{
return NULL; /* ImportError already set */
}
return PyModule_Create(&bindings_module);
}
"""
return template
def make_build_module(kernel_name, bindings_template, code, args, signature, args_str, self):
run_code = ""
count = 0
e = []
block_args = []
for i, arg in enumerate(signature):
if isinstance(arg, ConstexprArg):
block_args.append(arg)
continue
elif isinstance(arg, RemovedArg):
continue
if isinstance(arg, TensorArg):
run_code += f"args[{count}].data_ptr()"
elif isinstance(arg, SizeArg):
run_code += f"args[{count}]"
elif isinstance(arg, WorkspaceArg):
run_code += f"args[{count}].data_ptr()"
else:
raise ValueError(f"FIXME: Unknown arg type: {type(arg)}")
e.append(arg)
run_code += ","
count += 1
BLOCKS = ",".join("128" for arg in block_args)
grid = "("
for arg in block_args:
name = arg.name.lower()[:-len("BLOCK")]
grid += f"ceildiv({name}numel, 128),"
grid += ")"
ret = f"""
import subprocess
import tempfile
import os
def build_bindings_from_source(source_str, output_so="bindings.so"):
# Create a temporary C file
with tempfile.NamedTemporaryFile(delete=False, suffix=".c", mode="w") as c_file:
c_file.write(source_str)
c_file_path = c_file.name
try:
# Get Python include flags
includes = subprocess.check_output(
["python3-config", "--includes"],
text=True
).strip().split()
# Build the gcc command
cmd = [
"gcc",
"-shared",
"-fPIC",
*includes,
c_file_path,
"-o", output_so,
"-ldl"
]
# Run the compilation
subprocess.run(cmd, check=True)
print(f"Successfully built {{output_so}}")
finally:
# Clean up the temporary C file
pass
c_code = \"\"\"
{bindings_template}
\"\"\"
build_bindings_from_source(c_code, \"""" + kernel_name + f"""_bindings.so\")
def build_mojo_from_source(source_str):
# Create a temporary C file
with open("{kernel_name}_mojo.mojo", mode="w") as c_file:
#with tempfile.NamedTemporaryFile(delete=False, suffix=".mojo", mode="w") as c_file:
c_file.write(source_str)
c_file_path = c_file.name
try:
print(c_file_path)
# Build the gcc command
cmd = [
"magic",
"run",
"mojo",
"build",
"--emit",
"shared-lib",
"-o",
"{kernel_name}_mojo.so",
c_file_path,
]
# Run the compilation
print("BUILDING MOJO")
subprocess.run(cmd, check=True, cwd="/root/code/onegpu/mojo")
print(f"Successfully built mojo")
finally:
# Clean up the temporary C file
pass
source = \"\"\"
{code}
from gpu.host import DeviceContext
from math import ceildiv
@export
fn {kernel_name}{args_str}:
try:
with DeviceContext() as ctx:
ctx.enqueue_function[{kernel_name}[{BLOCKS}]]({",".join(arg.name for arg in e)},
grid_dim={grid}, block_dim=128
)
ctx.synchronize()
except e:
print(e)
\"\"\"
build_mojo_from_source(source)
os.environ['LD_LIBRARY_PATH'] = os.getcwd()
print(os.getcwd())
def run_fn(*args, **kwargs):
from {kernel_name}_bindings import {kernel_name} as kernel
kernel({run_code})
class {kernel_name}:
@staticmethod
def precompile(*args, **kwargs):
pass
@staticmethod
def run(*args, **kwargs):
run_fn(*args, **kwargs)
"""
return ret
class OpDtypeSupport:
"""
Some Triton ops such as libdevice and tl.math only support float32 and float64.
This class records which dtypes are supported by specific IR ops.
"""
supported_dtypes: dict[str, OrderedSet[torch.dtype]] = {}
convert_outputs: dict[str, bool] = {}
@classmethod
def register_upcast(cls, func: Callable[..., str],
convert_output: bool) -> None:
op_name = func.__name__
cls.supported_dtypes[op_name] = OrderedSet(
[torch.float32, torch.float64])
cls.convert_outputs[op_name] = convert_output
@lru_cache(None)
def gen_attr_descriptor_import() -> str:
"""
import AttrsDescriptor if the triton version is new enough to have this
class defined.
"""
if not has_triton_package():
return ""
import triton.compiler.compiler
# Note: this works because triton.compiler.compiler imports AttrsDescriptor from triton.backends.compiler
# When support for the legacy AttrsDescriptor is removed then this import path should be changed.
if hasattr(triton.compiler.compiler, "AttrsDescriptor"):
return "from triton.compiler.compiler import AttrsDescriptor"
else:
return ""
@lru_cache(None)
def gen_common_triton_imports() -> str:
imports = IndentedBuffer()
# imports.splice("""
# import triton
# import triton.language as tl
# """)
# if attr_desc := gen_attr_descriptor_import():
# imports.writeline(attr_desc)
# imports.splice("""
# from torch._inductor.runtime import triton_helpers, triton_heuristics
# from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
# from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, DeviceProperties
# """)
imports.splice("""
import triton_lite as tl
alias blocked_1d = tl.Blocked.one_d(1, num_warps=4)
""")
return imports.getvalue()
class TritonSymbols:
"""
Stores sympy.Symbol instances and constants associated with triton codegen.
"""
reduction_types = OrderedSet([SymT.R0_INDEX, SymT.R1_INDEX])
block_types = OrderedSet(
[SymT.XBLOCK, SymT.YBLOCK, SymT.ZBLOCK, *reduction_types])
block_offsets = {
symt:
sympy.Symbol(f"{prefix_str[symt]}offset",
integer=True,
nonnegative=True)
for symt in block_types
}
block_sizes = {
symt:
sympy.Symbol(f"{prefix_str[symt].upper()}BLOCK",
integer=True,
positive=True)
for symt in block_types
}
@classmethod
def get_block_size(cls, tree: IterationRanges) -> sympy.Symbol:
return cls.block_sizes[tree.symt]
@classmethod
def get_block_offset(cls, tree: IterationRanges) -> sympy.Symbol:
return cls.block_offsets[tree.symt]
@dataclasses.dataclass
class IndexingOptions:
index_str: str
mask_vars: OrderedSet[str]
expand_str: Optional[str]
_has_rindex: bool
index: sympy.Expr
def has_mask(self) -> bool:
return bool(self.mask_vars)
def has_indirect(self) -> bool:
return free_symbol_is_type(self.index, SymT.TMP)
def has_rindex(self) -> bool:
return self._has_rindex
def has_tmpmask(self) -> bool:
return any(str(mask).startswith("tmp") for mask in self.mask_vars)
def has_rmask(self) -> bool:
return any(str(mask).startswith("r") for mask in self.mask_vars)
@property
def mask_str(self) -> str:
return " & ".join(map(str,
self.mask_vars)) if self.mask_vars else "None"
@dataclasses.dataclass
class BlockPtrOptions:
params: BlockParameters
constant_offset: sympy.Expr
order: list[int]
mask_vars: OrderedSet[str]
broadcast_shape: Sequence[sympy.Expr]
broadcasting_dims: list[bool]
final_shape: Sequence[sympy.Expr]
_boundary_check: Optional[list[int]] = None
@property
def shape(self) -> list[sympy.Expr]:
return self.params.shape
@property
def block_shape(self) -> list[sympy.Expr]:
return self.params.block_shape
@property
def strides(self) -> list[sympy.Expr]:
return self.params.strides
@property
def offsets(self) -> list[sympy.Expr]:
return self.params.offsets
def codegen_broadcast_and_reshape(
self,
value: str,
initial_shape: Sequence[sympy.Expr],
final_shape: Sequence[sympy.Expr],
allow_implicit: bool,
) -> str:
"""
Generate a broadcast and a reshape for the block pointer.
This restores stride-0 dimensions which were removed from the block pointer.
"""
# Reshape to add singletons.
pre_broadcast_shape = [
sympy.S.One if is_broadcasting else dim for dim, is_broadcasting in
zip(self.broadcast_shape, self.broadcasting_dims)
]
value = triton_reshape(value, initial_shape, pre_broadcast_shape)
# Broadcast singletons.
# For loads, we can often implicitly broadcast singleton dimensions.
# We need an explicit broadcast for stores, or if the final reshape does more
# than add singletons.
sizevars = V.graph.sizevars
supports_implicit_broadcast = allow_implicit and (
len(pre_broadcast_shape) == len(final_shape) and all(
sizevars.statically_known_equals(pre_dim, 1)
or sizevars.statically_known_equals(pre_dim, post_dim)
for pre_dim, post_dim in zip(pre_broadcast_shape, final_shape))
)
if any(self.broadcasting_dims) and not supports_implicit_broadcast:
value = f"tl.broadcast_to({value}, {V.kernel.index_to_str(self.broadcast_shape)})"
# Reshape to the final shape.
value = triton_reshape(value, self.broadcast_shape, final_shape)
return value
@staticmethod
def create(
*,
params: BlockParameters,
constant_offset: sympy.Expr,
range_trees: list[IterationRangesRoot],
mask_vars: OrderedSet[str],
get_max_block: Callable[[str], int],
) -> BlockPtrOptions:
"""Helper to create a BlockPtrOptions instance"""
sizevars = V.graph.sizevars
def lookup_size(exprs: Iterable[sympy.Expr]) -> list[sympy.Expr]:
return [sizevars.lookup_precomputed_size(expr) for expr in exprs]
# Look up precomputed sizes
params.shape = lookup_size(params.shape)
params.strides = lookup_size(params.strides)
# Strip out dimensions of stride 0.
# These will be restored with tl.broadcast_to.
broadcasting_dims = [
sizevars.statically_known_equals(stride, 0)
for stride in params.strides
]
# Strip out dimensions of size 1.
# These will be restored by tl.reshape.
singleton_dims = [
sizevars.statically_known_equals(dim, 1)
for dim in params.block_shape
]
if all(singleton_dims):
# Handle a pure singletons, e.g. [1, 1]
singleton_dims[-1] = False
# Record the post-broadcast shape before broadcasting dims are removed.
# The pre-broadcast shape is identical to this, except broadcasting dims are
# replaced with 1.
broadcast_shape = [
dim
for dim, is_singleton in zip(params.block_shape, singleton_dims)
if not is_singleton
]
# Combine all removable dims.
removable_dims = [
any(dims) for dims in zip(singleton_dims, broadcasting_dims)
]
def remove_dims(it):
"""Removes any broadcasting or singleton dims from a given sequence"""
return [
item for item, is_removable in zip(it, removable_dims)
if not is_removable
]
# Drop removable dimensions from the input.
params = BlockParameters(
**{
key: remove_dims(val)
for key, val in dataclasses.asdict(params).items()
})
# Compute the final shape, adjusting for special kernel types.
final_shape = [
TritonSymbols.get_block_size(tree) for tree in range_trees
]
if V.kernel.no_x_dim:
assert range_trees[0].prefix == "x"
final_shape.pop(0)
reduction_ndim = V.kernel.num_reduction_dims
if (not V.kernel.inside_reduction and len(
params.strides) == len(V.kernel.numels) - reduction_ndim
and V.kernel.features.is_reduction()):
# Need to expand rank to match the rank used inside the reduction loop
final_shape += [sympy.S.One] * reduction_ndim
result = BlockPtrOptions(
params=params,
constant_offset=V.graph.sizevars.lookup_precomputed_size(
constant_offset),
order=list(reversed(range(len(params.shape)))),
mask_vars=mask_vars,
final_shape=final_shape,
broadcast_shape=broadcast_shape,
broadcasting_dims=broadcasting_dims,
)
result.compute_boundary_check(get_max_block)
return result
def replace_offset(self, expr: sympy.Expr, replacement: sympy.Expr,
symt: SymT) -> sympy.Expr:
"""
Replaces instances of {symt}_offset with the new expression.
"""
roffset = TritonSymbols.block_offsets[symt]
return sympy_subs(expr, {roffset: replacement})
def format(self, name: str, roffset=True) -> str:
"""
Codegen a call to tl.make_block_ptr()
Args:
name: variable name for pointer
roffset: should rn_offset be included in offsets=..., for use with tl.advance()
Returns:
"tl.make_block_ptr(...)"
"""
def remove_roffsets(expr: sympy.Expr) -> sympy.Expr:
for symt in TritonSymbols.reduction_types:
expr = self.replace_offset(expr, sympy.Integer(0), symt)
return expr
f = V.kernel.index_to_str
offsets = [*self.offsets]
if not roffset:
offsets = [remove_roffsets(offset) for offset in offsets]
args = [
(f"{name} + ({f(self.constant_offset)})"
if self.constant_offset != 0 else name),
f"shape={f(self.shape)}",
f"strides={f(self.strides)}",
f"block_shape={f(self.block_shape)}",
f"order={f(self.order)}",
f"offsets={f(offsets)}",
]
return f"tl.make_block_ptr({', '.join(args)})"
def compute_boundary_check(self, get_max_block: Callable[[str],
int]) -> None:
"""List of indices to pass to tl.load(boundary_check=...)"""
sizevars = V.graph.sizevars
# Substitute maximum block sizes in shape expressions.
# This works in multiple_of checks because block sizes are powers of 2.
block_to_max: dict[sympy.Expr, Any] = {
block_size: get_max_block(prefix_str[symt])
for symt, block_size in TritonSymbols.block_sizes.items()
}
self._boundary_check = [
idx for idx in range(len(self.shape))
if (not sizevars.statically_known_equals(self.strides[idx],
sympy.S.Zero)
and not sizevars.statically_known_multiple_of(
self.shape[idx], self.block_shape[idx])
and not sizevars.statically_known_multiple_of(
self.shape[idx],
sympy_subs(self.block_shape[idx], block_to_max))
and not (V.kernel.no_x_dim and self.block_shape[idx] ==
TritonSymbols.block_sizes[SymT.XBLOCK]))
]
def boundary_check(self) -> list[int]:
assert self._boundary_check is not None
return self._boundary_check
def advance_roffset(self, symt: SymT) -> sympy.Expr:
"""
Codegen string to pass to tl.advance(name, ...).
Advance is the difference between offsets in each loop iteration.
To compute it, we replace rN_offset with multiples of RN_BLOCK.
Since we expect rN_offset to vary in range(0, rN_numel, RN_BLOCK), the first
iteration has rN_offset=0, while the second has rN_offset=RN_BLOCK.
"""
rblock = TritonSymbols.block_sizes[symt]
advance = [(self.replace_offset(offset, rblock, symt) -
self.replace_offset(offset, sympy.S.Zero, symt))
for offset in self.offsets]
return advance
def has_indirect(self) -> bool:
return False # block_ptr can't do indirect indexing
def has_rindex(self) -> bool:
return any(
free_symbol_is_type(expr, TritonSymbols.reduction_types)
for expr in self.block_shape)
def has_rmask(self) -> bool:
return self.has_rindex()
def has_tmpmask(self) -> bool:
return False # block_ptr can't do indirect indexing
def has_mask(self) -> bool:
return bool(self.boundary_check())
def triton_reshape(value: str, old_shape: Sequence[sympy.Expr],
new_shape: Sequence[sympy.Expr]) -> str:
"""Workaround https://github.com/triton-lang/triton/issues/2836"""
assert isinstance(old_shape, list) and isinstance(new_shape, list)
old_shape_str = [V.kernel.index_to_str(shape) for shape in old_shape]
new_shape_str = [V.kernel.index_to_str(shape) for shape in new_shape]
if old_shape_str == new_shape_str:
return value
if [s for s in new_shape_str if s != "1"] != old_shape_str:
return f"tl.reshape({value}, [{', '.join(new_shape_str)}])"
# rewrite to [:, None] syntax, which is less buggy
idx = 0
expand = []
for size in new_shape_str:
if idx < len(old_shape_str) and size == old_shape_str[idx]:
expand.append(":")
idx += 1
else:
assert size == "1"
expand.append("None")
assert idx == len(old_shape_str)
return f"{value}[{', '.join(expand)}]"
# NB: Inheriting from PythonPrinter is somewhat dangerous, because there are a
# number of operators which Triton "implements", but in a way that is
# inconsistent with Python semantics (and consistent with C semantics). We
# must override all of these, or it is potential silent correctness problem
class TritonPrinter(PythonPrinter):
def _print_TruncToInt(self, expr: sympy.Expr) -> str:
assert len(expr.args) == 1
return (
f"libdevice.trunc({self._print(expr.args[0])}).to({V.kernel.index_dtype})"
)
def _print_Float(self, expr: sympy.Expr) -> str:
if config.is_fbcode() and torch.version.hip:
ret = f"Float32({expr})"
else:
ret = f"tl.full([], {expr}, tl.float64)"
return ret
def _print_ToFloat(self, expr: sympy.Expr) -> str:
assert len(expr.args) == 1
s = self.parenthesize(expr.args[0], PRECEDENCE["Atom"] - 0.5)
return f"{s}.to[tl.float64]()"
def _print_PythonMod(self, expr: sympy.Expr) -> str:
quot, div = expr.args
if quot.is_nonnegative and div.is_nonnegative:
return self.stringify(expr.args, " % ", PRECEDENCE["Atom"] - 0.5)
quot_s = self._print(quot)
div_s = self._print(div)
return f"triton_helpers.remainder_integer({quot_s}, {div_s})"
def _print_FloorDiv(self, expr: sympy.Expr) -> str:
assert expr.is_integer
quot, div = expr.args
if quot.is_nonnegative and div.is_nonnegative:
return self.stringify(expr.args, " // ", PRECEDENCE["Atom"] - 0.5)
quot_s = self._print(quot)
div_s = self._print(div)
return f"triton_helpers.div_floor_integer({quot_s}, {div_s})"
# TODO: This is wrong, when lhs, rhs > 2**53, Python does a higher
# precision algorithm, which we would need to replicate here
def _print_IntTrueDiv(self, expr: sympy.Expr) -> str:
return self.stringify(expr.args, " / ", PRECEDENCE["Atom"] - 0.5)
# NB: sympy.floor/ceiling produce integers, so we have to do the
# conversion to index dtype
def _print_floor(self, expr: sympy.Expr) -> str:
assert len(expr.args) == 1
return (
f"libdevice.floor({self._print(expr.args[0])}).to({V.kernel.index_dtype})"
)
def _print_FloorToInt(self, expr: sympy.Expr) -> str:
assert len(expr.args) == 1
return (
f"libdevice.floor({self._print(expr.args[0])}).to({V.kernel.index_dtype})"
)
def _print_ceiling(self, expr: sympy.Expr) -> str:
assert len(expr.args) == 1
return f"libdevice.ceil({self._print(expr.args[0])}).to({V.kernel.index_dtype})"
def _print_CeilToInt(self, expr: sympy.Expr) -> str:
assert len(expr.args) == 1
return f"libdevice.ceil({self._print(expr.args[0])}).to({V.kernel.index_dtype})"
def _helper_sqrt(self, expr: sympy.Expr) -> str:
return f"libdevice.sqrt(({self._print(expr)}).to[tl.float32)]()"
def _print_FloatPow(self, expr: sympy.Expr) -> str:
return (
f"libdevice.pow({self._print(expr.args[0])}, {self._print(expr.args[1])})"
)
def _print_PowByNatural(self, expr: sympy.Expr) -> str:
if expr.args[0].is_Integer:
return f"libdevice.pow({float(expr.args[0])}, {self._print(expr.args[1])})"
return (
f"libdevice.pow({self._print(expr.args[0])}, {self._print(expr.args[1])})"
)
def _print_Where(self, expr: sympy.Expr) -> str:
c = self.doprint(expr.args[0])
p = self.doprint(expr.args[1])
q = self.doprint(expr.args[2])
return f"tl.where({c}, {p}, {q})"
def _print_min_max_helper(self, expr: sympy.Expr, cmp: str) -> str:
"""
Helper for max/min code genereration.
cmp: > or <
"""
if len(expr.args) == 1:
return self._print(expr.args[0])
mid = len(expr.args) // 2
cls = type(expr)
a = self._print(cls(*expr.args[:mid]))
b = self._print(cls(*expr.args[mid:]))
# Use a macro so we can propagate constexprs.
# https://github.com/triton-lang/triton/issues/3815
a, b = tuple(f"({x})" for x in (a, b))
assert cmp in (">", "<"), f"Unexpected comparator: '{cmp}'"