-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathcode_generator.py
More file actions
1759 lines (1531 loc) · 75.8 KB
/
Copy pathcode_generator.py
File metadata and controls
1759 lines (1531 loc) · 75.8 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
import ast
import builtins
import contextlib
import copy
import inspect
import re
import warnings
import textwrap
from dataclasses import dataclass
from types import ModuleType
from typing import Any, Callable, Dict, Optional, Tuple, Type, Union, Iterable, List
from .. import knobs, language
from .._C.libtriton import ir, gluon_ir
from ..language import constexpr, str_to_ty, tensor, tuple as tl_tuple
from ..language.core import _unwrap_if_constexpr, base_value, base_type
# ideally we wouldn't need any runtime component
from ..runtime.jit import get_jit_fn_file_line, get_full_name, JITCallable, BoundConstexprFunction, ConstexprFunction, JITFunction
from .._utils import find_paths_if, get_iterable_path, set_iterable_path, is_namedtuple
from .hint_manager import hint_trigger
from .errors import (CompilationError, CompileTimeAssertionFailure, UnsupportedLanguageConstruct)
def check_identifier_legality(name, type):
pattern = r'^[a-zA-Z_][a-zA-Z0-9_]*$'
if not re.match(pattern, name):
raise CompilationError(f"invalid {type} identifier: {name}", name)
return name
def mangle_fn(name, arg_tys, constants, caller_context):
# doesn't mangle ret type, which must be a function of arg tys
mangled_arg_names = '_'.join([ty.mangle() for ty in arg_tys])
mangled_constants = '_'.join([f'{i}c{repr(constants[i])}' for i in sorted(constants)])
mangled_constants = mangled_constants.replace('.', '_d_')
mangled_constants = mangled_constants.replace("'", '_sq_')
# [ and ] are not allowed in LLVM identifiers
mangled_constants = mangled_constants.replace('[', '_').replace(']', '_')
ret = f'{name}__{mangled_arg_names}__{mangled_constants}'
if caller_context is not None:
ret += caller_context.mangle()
return ret
def _is_triton_value(o: Any) -> bool:
return isinstance(o, base_value)
def _is_triton_tensor(o: Any) -> bool:
return isinstance(o, tensor)
def _is_constexpr(o: Any) -> bool:
return o is None or isinstance(o, (constexpr, language.core.dtype, JITCallable))
def _is_non_scalar_tensor(o: Any) -> bool:
return _is_triton_tensor(o) and (o.type.is_block() and o.type.numel != 1)
def _is_list_like(o: Any) -> bool:
return isinstance(o, (list, tuple))
def _check_fn_args(node, fn, args):
if fn.noinline:
for idx, arg in enumerate(args):
if not _is_constexpr(arg) and _is_non_scalar_tensor(arg):
raise UnsupportedLanguageConstruct(
fn.src, node,
f'Function {fn.__name__} is marked noinline, but was called with non-scalar argument {fn.arg_names[idx]}:{arg}'
)
def _apply_to_tuple_values(value, fn):
if is_namedtuple(type(value)):
fields = value._fields
elif isinstance(value, language.tuple):
fields = value.type.fields
else:
assert False, f"Unsupported type {type(value)}"
vals = [fn(v) for v in value]
vals = [constexpr(v) if v is None else v for v in vals]
types = [v.type for v in vals]
return language.tuple(vals, language.tuple_type(types, fields))
def flatten_values_to_ir(values: Iterable[base_value]):
handles = []
for v in values:
v._flatten_ir(handles)
return handles
def unflatten_ir_values(handles: List[ir.value], types: List[base_type]):
cursor = 0
for ty in types:
value, cursor = ty._unflatten_ir(handles, cursor)
yield value
assert cursor == len(handles)
_condition_types = {bool, int, type(None)} # Python types accepted for conditionals inside kernels
def _clone_triton_value(val):
handles = []
val._flatten_ir(handles)
clone, _ = val.type._unflatten_ir(handles, 0)
# begin flagtree tle
# Preserve TLE compile-time metadata across scope cloning (if/loop
# live-ins). Value-level metadata can otherwise be dropped by unflatten.
if hasattr(val, "__dict__"):
for key, attr in val.__dict__.items():
if key.startswith("_tle_"):
try:
setattr(clone, key, attr)
except Exception:
pass
if hasattr(val.type, "__dict__"):
for key, attr in val.type.__dict__.items():
if key.startswith("_tle_"):
try:
setattr(clone.type, key, attr)
except Exception:
pass
# end flagtree tle
return clone
def _clone_scope(scope):
return {name: _clone_triton_value(val) if _is_triton_value(val) else val for name, val in scope.items()}
class enter_sub_region:
def __init__(self, generator):
self.generator = generator
def __enter__(self):
# record lscope & local_defs in the parent scope
self.liveins = _clone_scope(self.generator.lscope)
self.prev_defs = _clone_scope(self.generator.local_defs)
self.generator.local_defs = {}
self.insert_block = self.generator.builder.get_insertion_block()
self.insert_point = self.generator.builder.get_insertion_point()
return self.liveins, self.insert_block
def __exit__(self, *args, **kwargs):
self.generator.builder.restore_insertion_point(self.insert_point)
self.generator.lscope = self.liveins
self.generator.local_defs = self.prev_defs
# Check if the given syntax node has an "early" return
class ContainsReturnChecker(ast.NodeVisitor):
def __init__(self, gscope):
self.gscope = gscope
def _visit_stmts(self, body) -> bool:
return any(self.visit(s) for s in body)
def _visit_function(self, fn) -> bool:
# No need to check within the function as it won't cause an early return.
# If the function itself has unstructured control flow we may not be able to inline it causing poor performance,
# we should check for this and emit a warning.
return False
def generic_visit(self, node) -> bool:
ret = False
for _, value in ast.iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, ast.AST):
ret = ret or self.visit(item)
elif isinstance(value, ast.AST):
ret = ret or self.visit(value)
return ret
def visit_Attribute(self, node: ast.Attribute) -> bool:
# If the left part is a name, it's possible that
# we call triton native function or a jit function from another module.
# If the left part is not a name, it must return a tensor or a constexpr
# whose methods do not contain return statements
# e.g., (tl.load(x)).to(y)
# So we only check if the expressions within value have return or not
if isinstance(node.value, ast.Name):
if node.value.id in self.gscope:
value = self.gscope[node.value.id]
fn = getattr(value, node.attr)
return self._visit_function(fn)
return False
return self.visit(node.value)
def visit_Name(self, node: ast.Name) -> bool:
if type(node.ctx) is ast.Store:
return False
if node.id in self.gscope:
fn = self.gscope[node.id]
return self._visit_function(fn)
return False
def visit_Return(self, node: ast.Return) -> bool:
return True
def visit_Assign(self, node: ast.Assign) -> bool:
# There couldn't be an early return
# x = ...
return False
def visit_AugAssign(self, node: ast.AugAssign) -> bool:
# There couldn't be an early return
# x += ...
return False
def visit_Module(self, node: ast.Module) -> bool:
return self._visit_stmts(node.body)
def visit_FunctionDef(self, node: ast.FunctionDef) -> bool:
return self._visit_stmts(node.body)
def visit_If(self, node: ast.If) -> bool:
# TODO: optimize the following case in which we actually don't have
# a return when static_cond is false:
# if dynamic_cond
# if static_cond
# func_with_return
# else
# func_without_return
ret = self._visit_stmts(node.body)
if node.orelse:
ret = ret or self._visit_stmts(node.orelse)
return ret
def visit_IfExp(self, node: ast.IfExp) -> bool:
return self.visit(node.body) or self.visit(node.orelse)
def visit_Call(self, node: ast.Call) -> bool:
return self.visit(node.func)
class ASTFunction:
def __init__(self, ret_types, arg_types, constants, attrs):
self.ret_types = ret_types
self.arg_types = arg_types
self.constants = constants
self.attrs = attrs
def flatten_ir_types(self, builder: ir.builder, types: List[base_type]) -> List[ir.type]:
ir_types = []
for ty in types:
if ty is None:
continue
ty._flatten_ir_types(builder, ir_types)
return ir_types
def return_types_ir(self, builder: ir.builder) -> List[ir.type]:
return self.flatten_ir_types(builder, self.ret_types)
def serialize(self, builder: ir.builder):
# fill up IR values in template
# > build function
is_val = lambda path, _: path not in self.constants and _ is not None
val_paths = list(find_paths_if(self.arg_types, is_val))
arg_types = [get_iterable_path(self.arg_types, path) for path in val_paths]
arg_types_ir = self.flatten_ir_types(builder, arg_types)
ret_types_ir = self.return_types_ir(builder)
return builder.get_function_ty(arg_types_ir, ret_types_ir)
def deserialize(self, fn):
# create "template"
def make_template(ty):
if isinstance(ty, (list, tuple, language.tuple_type)):
return language.tuple([make_template(x) for x in ty], ty)
return language.constexpr(None)
vals = make_template(self.arg_types)
is_val = lambda path, _: path not in self.constants and _ is not None
val_paths = list(find_paths_if(self.arg_types, is_val))
# > add IR values to the template
cursor = 0
handles = [fn.args(i) for i in range(fn.get_num_args())]
for path in val_paths:
ty = get_iterable_path(self.arg_types, path)
# > set attributes
attr_specs = self.attrs.get(path, [])
for attr_name, attr_val in attr_specs:
fn.set_arg_attr(cursor, attr_name, attr_val)
# > build frontend value
val, cursor = ty._unflatten_ir(handles, cursor)
set_iterable_path(vals, path, val)
# > add constexpr values to the template
constants = self.constants
for path, val in constants.items():
set_iterable_path(vals, path, language.constexpr(val))
return vals
@dataclass(frozen=True)
class BoundJITMethod:
__self__: base_value
__func__: JITFunction
# begin flagtree tle
class LambdaFunction:
def __init__(self, generator, node: ast.Lambda, signature: inspect.Signature, captured_scope: Dict[str, Any]):
self._generator = generator
self._node = node
self._signature = signature
self._captured_scope = captured_scope
self.__name__ = "<lambda>"
def __call__(self, *args, **kwargs):
bound = self._signature.bind(*args, **kwargs)
bound.apply_defaults()
previous_scope = self._generator.lscope
previous_defs = self._generator.local_defs
try:
lscope = dict(self._captured_scope)
lscope.update(bound.arguments)
self._generator.lscope = lscope
self._generator.local_defs = previous_defs
return self._generator.visit(self._node.body)
finally:
self._generator.lscope = previous_scope
self._generator.local_defs = previous_defs
# end flagtree tle
class CodeGenerator(ast.NodeVisitor):
def __init__(self, context, prototype, gscope, function_name, jit_fn: JITFunction, *, options, codegen_fns,
module_map, is_gluon, module=None, is_kernel=False, function_types: Optional[Dict] = None,
noinline=False, caller_context=None, file_name: Optional[str] = None, begin_line=0):
self.context = context
self.is_gluon = is_gluon
if is_gluon:
from triton.experimental.gluon.language._semantic import GluonSemantic
self.builder = gluon_ir.GluonOpBuilder(context)
self.semantic = GluonSemantic(self.builder)
else:
from triton.language.semantic import TritonSemantic
self.builder = ir.builder(context)
self.semantic = TritonSemantic(self.builder)
self.name_loc_as_prefix = None
self.file_name = file_name
# node.lineno starts from 1, so we need to subtract 1
self.begin_line = begin_line - 1
self.builder.set_loc(file_name, begin_line, 0)
self.builder.options = options
# dict of functions provided by the backend. Below are the list of possible functions:
# Convert custom types not natively supported on HW.
# convert_custom_types(input_tensor, dtype, fp_downcast_rounding=None, _builder=None)
self.builder.codegen_fns = codegen_fns
self.builder.module_map = {} if module_map is None else module_map
self.module = self.builder.create_module() if module is None else module
self.function_ret_types = {} if function_types is None else function_types
self.prototype = prototype
self.gscope = {}
for k, v in gscope.items():
if isinstance(v, ModuleType):
self.gscope[k] = module_map.get(v.__name__, v)
continue
module_name = getattr(v, "__module__", "")
if module_name in module_map:
self.gscope[k] = getattr(module_map[module_name], v.__name__)
else:
self.gscope[k] = v
self.lscope = {}
self.jit_fn = jit_fn
self.flagtree_line_hints = {}
# TODO: we currently generate illegal names for non-kernel functions involving constexprs!
if is_kernel:
function_name = function_name[function_name.rfind('.') + 1:]
function_name = check_identifier_legality(function_name, "function")
self.function_name = function_name
self.is_kernel = is_kernel
self.cur_node = None
self.noinline = noinline
self.caller_context = caller_context
self.scf_stack = []
self.ret_type = None
# SSA-construction
# name => language.tensor
self.local_defs: Dict[str, tensor] = {}
self.dereference_name: Callable[[str], Any] = self._define_name_lookup()
self.fn = None
# Are we currently visiting an ast.arg's default value? These have some
# special handling.
self.visiting_arg_default_value = False
builtin_namespace: Dict[str, Any] = {
_.__name__: _
for _ in (len, list, range, float, int, isinstance, getattr, hasattr)
}
builtin_namespace.update((
('print', language.core.device_print),
('min', language.core.builtin_min),
('max', language.core.builtin_max),
))
def _unsupported(self, node, message):
return UnsupportedLanguageConstruct(self.jit_fn.src, node, message)
def _is_constexpr_global(self, name):
absent_marker = object()
val = self.gscope.get(name, absent_marker)
if val is absent_marker:
return False
if _is_constexpr(val):
return True
return False
def _define_name_lookup(self):
def local_lookup(name: str, absent):
# this needs to be re-fetched from `self` every time, because it gets switched occasionally
return self.lscope.get(name, absent)
def global_lookup(name: str, absent):
val = self.gscope.get(name, absent)
# The high-level rule is that only constexpr globals are allowed.
# But actually a bunch of other things, such as module imports, are
# technically Python globals. We have to allow these too!
if any([
val is absent,
name in self.builtin_namespace, #
type(val) is ModuleType, #
isinstance(val, JITCallable), #
getattr(val, "__triton_builtin__", False), #
getattr(val, "__triton_aggregate__", False), #
getattr(val, "__module__", "").startswith("triton.language"), #
getattr(val, "__module__", "").startswith("triton.experimental.gluon.language"), #
isinstance(val, language.dtype), #
is_namedtuple(val),
self._is_constexpr_global(name), #
# Allow accesses to globals while visiting an ast.arg
# because you should be able to do
# @triton.jit def fn(x: tl.constexpr = GLOBAL): ...
self.visiting_arg_default_value, #
knobs.compilation.allow_non_constexpr_globals,
]):
return val
raise NameError(
textwrap.dedent(f"""\
Cannot access global variable {name} from within @jit'ed
function. Triton kernels can only access global variables that
are instanstiated as constexpr (`x = triton.language.constexpr(42)`). Note that this is different from
annotating a variable as constexpr (`x: triton.language.constexpr = 42`), which is not supported. Alternatively, set the
envvar TRITON_ALLOW_NON_CONSTEXPR_GLOBALS=1, but we do not
promise to support this forever.""").replace("\n", " "))
absent_marker = object()
def name_lookup(name: str) -> Any:
absent = absent_marker
for lookup_function in local_lookup, global_lookup, self.builtin_namespace.get:
value = lookup_function(name, absent)
if value is not absent:
return value
raise NameError(f'{name} is not defined')
return name_lookup
@contextlib.contextmanager
def _name_loc_prefix(self, prefix):
self.name_loc_as_prefix = prefix
yield
self.name_loc_as_prefix = None
def _maybe_set_loc_to_name(self, val, name):
if isinstance(val, (ir.value, ir.block_argument)):
val.set_loc(self.builder.create_name_loc(name, val.get_loc()))
elif _is_triton_value(val):
handles = []
val._flatten_ir(handles)
for handle in handles:
handle.set_loc(self.builder.create_name_loc(name, handle.get_loc()))
def set_value(self, name: str, value: Union[base_value, constexpr]) -> None:
''' This function:
called by visit_Assign() & visit_FunctionDef() to store left value (lvalue)
1. record local defined name (FIXME: should consider control flow)
2. store tensor in self.lvalue
'''
self.lscope[name] = value
self.local_defs[name] = value
def _get_insertion_point_and_loc(self):
# XXX: this is a hack to get the location of the insertion point.
# The insertion point's location could be invalid sometimes,
# so we need to explicitly set the location
loc = self.builder.get_loc()
ip = self.builder.get_insertion_point()
return ip, loc
def _set_insertion_point_and_loc(self, ip, loc):
self.builder.restore_insertion_point(ip)
self.builder.set_loc(loc)
def _find_carries(self, node, liveins, ignore: set[str] = set()):
# create loop body block
block = self.builder.create_block()
self.builder.set_insertion_point_to_start(block)
# dry visit loop body
self.scf_stack.append(node)
self.visit_compound_statement(node.body)
self.scf_stack.pop()
block.erase()
# If a variable (name) has changed value within the loop, then it's
# a loop-carried variable. (The new and old value must be of the
# same type)
init_tys = []
init_handles = []
names = []
for name, live_val in liveins.items():
if name in ignore:
continue
if _is_triton_value(live_val):
loop_val = self.lscope[name]
self._verify_loop_carried_variable(name, loop_val, live_val)
live_handles = flatten_values_to_ir([live_val])
loop_handles = flatten_values_to_ir([loop_val])
if live_handles != loop_handles:
names.append(name)
init_tys.append(live_val.type)
init_handles.extend(live_handles)
else:
assert name not in self.local_defs, f'Loop carried variable {name} is not a triton value'
# reset local scope to not pick up local defs from the dry run.
self.lscope = liveins.copy()
self.local_defs = {}
return names, init_handles, init_tys
#
# AST visitor
#
def visit_compound_statement(self, stmts):
# Ensure that stmts is iterable
if not _is_list_like(stmts):
stmts = [stmts]
for stmt in stmts:
self.visit(stmt)
# Stop parsing as soon as we hit a `return` statement; everything
# after this is dead code.
if isinstance(stmt, ast.Return):
break
def visit_Module(self, node):
ast.NodeVisitor.generic_visit(self, node)
def visit_List(self, node):
ctx = self.visit(node.ctx)
assert ctx is None
elts = language.tuple([self.visit(elt) for elt in node.elts])
return elts
def visit_ListComp(self, node: ast.ListComp):
if len(node.generators) != 1:
raise ValueError("nested comprehensions are not supported")
comp = node.generators[0]
iter = self.visit(comp.iter)
if not isinstance(iter, tl_tuple):
raise NotImplementedError("only tuple comprehensions are supported")
results = []
for item in iter:
self.set_value(comp.target.id, item)
results.append(self.visit(node.elt))
return tl_tuple(results)
# By design, only non-kernel functions can return
def visit_Return(self, node):
ret_value = self.visit(node.value)
handles = []
def decay(value):
if isinstance(value, language.tuple):
return _apply_to_tuple_values(value, decay)
elif isinstance(value, (language.constexpr, int, float)):
return self.semantic.to_tensor(value)
return value
ret_value = decay(ret_value)
if ret_value is None:
ret_ty = language.void
else:
assert isinstance(ret_value, language.core.base_value)
ret_value._flatten_ir(handles)
ret_ty = ret_value.type
self.builder.ret(handles)
if self.ret_type is None:
self.ret_type = ret_ty
elif self.ret_type != ret_ty:
raise TypeError(f'Inconsistent return types: {self.ret_type} and {ret_ty}')
# A return op must always terminate the basic block, so we create a dead
# basic block in case there are any ops after the return.
post_ret_block = self.builder.create_block()
self.builder.set_insertion_point_to_end(post_ret_block)
def visit_FunctionDef(self, node):
arg_names, kwarg_names = self.visit(node.args)
if self.fn:
raise self._unsupported(node, "nested function definition is not supported.")
# initialize defaults
for i, default_value in enumerate(node.args.defaults[::-1]):
arg_node = node.args.args[-i - 1]
annotation = arg_node.annotation
name = arg_node.arg
st_target = ast.Name(id=name, ctx=ast.Store())
if annotation is None:
init_node = ast.Assign(targets=[st_target], value=default_value)
else:
init_node = ast.AnnAssign(target=st_target, value=default_value, annotation=annotation)
try:
assert not self.visiting_arg_default_value
self.visiting_arg_default_value = True
self.visit(init_node)
finally:
self.visiting_arg_default_value = False
# initialize function
visibility = "public" if self.is_kernel else "private"
fn_ty = self.prototype.serialize(self.builder)
self.fn = self.builder.get_or_insert_function(self.module, self.function_name, fn_ty, visibility, self.noinline)
self.module.push_back(self.fn)
entry = self.fn.add_entry_block()
arg_values = self.prototype.deserialize(self.fn)
if self.caller_context is not None:
self.caller_context.initialize_callee(self.fn, self.builder)
# bind arguments to symbols
for arg_name, arg_value in zip(arg_names, arg_values):
self._maybe_set_loc_to_name(arg_value, arg_name)
self.set_value(arg_name, arg_value)
insert_pt = self.builder.get_insertion_block()
self.builder.set_insertion_point_to_start(entry)
# visit function body
self.visit_compound_statement(node.body)
# finalize function
assert not self.builder.get_insertion_block().has_terminator()
if self.ret_type is None or self.ret_type == language.void:
self.ret_type = language.void
self.builder.ret([])
else:
if isinstance(self.ret_type, language.tuple_type):
self.prototype.ret_types = self.ret_type.types
else:
self.prototype.ret_types = [self.ret_type]
self.fn.reset_type(self.prototype.serialize(self.builder))
self.builder.ret([self.builder.create_poison(ty) for ty in self.prototype.return_types_ir(self.builder)])
self.fn.finalize()
if insert_pt:
self.builder.set_insertion_point_to_end(insert_pt)
def visit_arguments(self, node):
arg_names = []
for arg in node.args:
arg_names += [self.visit(arg)]
kwarg_names = self.visit(node.kwarg)
return arg_names, kwarg_names
def visit_arg(self, node):
ast.NodeVisitor.generic_visit(self, node)
param = next(p for p in self.jit_fn.params if p.name == node.arg)
if param.is_constexpr and (param.do_not_specialize or param.do_not_specialize_on_alignment):
raise CompilationError(
self.jit_fn.src, node,
f"{node.arg} marked as constexpr and listed in do_not_specialize/do_not_specialize_on_alignment. "
"Remove constexpr designation to skip specialization.")
return node.arg
def visit_AnnAssign(self, node):
# extract attributes
annotation = self.visit(node.annotation)
target = self.visit(node.target)
value = self.visit(node.value)
# constexpr
if annotation == constexpr:
if target in self.lscope:
raise ValueError(f'{target} is already defined.'
f' constexpr cannot be reassigned.')
value = constexpr(value)
self.lscope[target] = value
return self.lscope[target]
# default: call visit_Assign
return self.visit_Assign(node)
def assignTarget(self, target, value):
assert isinstance(target.ctx, ast.Store)
if isinstance(target, ast.Subscript):
return self.visit_Subscript_Store(target, value)
if isinstance(target, ast.Tuple):
for i, target in enumerate(target.elts):
self.assignTarget(target, value.values[i])
return
if isinstance(target, ast.Attribute):
raise NotImplementedError("Attribute assignment is not supported in triton")
assert isinstance(target, ast.Name)
self.set_value(self.visit(target), value)
def visit_Assign(self, node):
# construct values to assign
def _sanitize_value(value):
if isinstance(value, language.tuple):
return _apply_to_tuple_values(value, _sanitize_value)
native_nontensor_types = (language.dtype, language.tuple)
value = _unwrap_if_constexpr(value)
if value is not None and \
not _is_triton_value(value) and \
not isinstance(value, native_nontensor_types):
value = self.semantic.to_tensor(value)
return value
targets = [node.target] if isinstance(node, ast.AnnAssign) else node.targets
assert len(targets) == 1
target = targets[0]
if isinstance(target, ast.Name):
with self._name_loc_prefix(target.id):
values = _sanitize_value(self.visit(node.value))
else:
values = _sanitize_value(self.visit(node.value))
self.assignTarget(target, values)
def visit_AugAssign(self, node):
lhs = copy.deepcopy(node.target)
lhs.ctx = ast.Load()
rhs = ast.BinOp(lhs, node.op, node.value)
assign = ast.Assign(targets=[node.target], value=rhs)
for x in ['lineno', 'col_offset', 'end_lineno', 'end_col_offset']:
if hasattr(node, x):
y = getattr(node, x)
setattr(rhs, x, y)
setattr(assign, x, y)
self.visit(assign)
return self.visit(lhs)
# begin flagtree tle
def _evaluate_lambda_default(self, node):
if node is None:
return inspect._empty
try:
assert not self.visiting_arg_default_value
self.visiting_arg_default_value = True
return self.visit(node)
finally:
self.visiting_arg_default_value = False
def _build_lambda_signature(self, node: ast.Lambda) -> inspect.Signature:
args = node.args
posonly = list(args.posonlyargs)
pos_or_kw = list(args.args)
total_pos = len(posonly) + len(pos_or_kw)
defaults = [inspect._empty] * total_pos
if args.defaults:
start = total_pos - len(args.defaults)
for i, default_node in enumerate(args.defaults):
defaults[start + i] = self._evaluate_lambda_default(default_node)
params: List[inspect.Parameter] = []
for i, arg in enumerate(posonly):
default = defaults[i]
params.append(inspect.Parameter(arg.arg, inspect.Parameter.POSITIONAL_ONLY, default=default))
for i, arg in enumerate(pos_or_kw):
default = defaults[len(posonly) + i]
params.append(inspect.Parameter(arg.arg, inspect.Parameter.POSITIONAL_OR_KEYWORD, default=default))
if args.vararg is not None:
params.append(inspect.Parameter(args.vararg.arg, inspect.Parameter.VAR_POSITIONAL))
for i, arg in enumerate(args.kwonlyargs):
default = self._evaluate_lambda_default(args.kw_defaults[i])
params.append(inspect.Parameter(arg.arg, inspect.Parameter.KEYWORD_ONLY, default=default))
if args.kwarg is not None:
params.append(inspect.Parameter(args.kwarg.arg, inspect.Parameter.VAR_KEYWORD))
return inspect.Signature(params)
def visit_Lambda(self, node: ast.Lambda):
signature = self._build_lambda_signature(node)
captured_scope = dict(self.lscope)
return LambdaFunction(self, node, signature, captured_scope)
# end flagtree tle
def visit_Name(self, node):
if type(node.ctx) is ast.Store:
return node.id
return self.dereference_name(node.id)
def visit_Store(self, node):
ast.NodeVisitor.generic_visit(self, node)
def visit_Load(self, node):
ast.NodeVisitor.generic_visit(self, node)
def visit_Tuple(self, node):
args = [self.visit(x) for x in node.elts]
return language.tuple(args)
def _apply_binary_method(self, node, method_name, lhs, rhs):
# TODO: raise something meaningful if getattr fails below, esp for reverse method
if _is_triton_tensor(lhs):
return getattr(lhs, method_name)(rhs, _semantic=self.semantic)
if _is_triton_tensor(rhs):
reverse_method_name = re.sub(r"__(.*)__", r"__r\1__", method_name)
return getattr(rhs, reverse_method_name)(lhs, _semantic=self.semantic)
if not isinstance(lhs, (constexpr, language.tuple)) and isinstance(rhs, constexpr):
lhs = constexpr(lhs)
if isinstance(lhs, constexpr):
fn = getattr(lhs, method_name)
else:
fn = self.get_Attribute(lhs, method_name)
return self.call_Function(node, fn, [rhs], {})
def visit_BinOp(self, node):
lhs = self.visit(node.left)
rhs = self.visit(node.right)
method_name = self._method_name_for_bin_op.get(type(node.op))
if method_name is None:
raise self._unsupported(node,
"AST binary operator '{}' is not (currently) implemented.".format(node.op.__name__))
return self._apply_binary_method(node, method_name, lhs, rhs)
_method_name_for_bin_op: Dict[Type[ast.operator], str] = {
ast.Add: '__add__',
ast.Sub: '__sub__',
ast.Mult: '__mul__',
ast.Div: '__truediv__',
ast.FloorDiv: '__floordiv__',
ast.Mod: '__mod__',
ast.Pow: '__pow__',
ast.LShift: '__lshift__',
ast.RShift: '__rshift__',
ast.BitAnd: '__and__',
ast.BitOr: '__or__',
ast.BitXor: '__xor__',
}
def visit_then_else_blocks(self, node, liveins, then_block, else_block):
# then block
self.builder.set_insertion_point_to_start(then_block)
self.visit_compound_statement(node.body)
then_block = self.builder.get_insertion_block()
then_defs = self.local_defs.copy()
then_vals = self.lscope.copy()
# else block
else_defs = {}
else_vals = liveins.copy()
if node.orelse:
self.builder.set_insertion_point_to_start(else_block)
self.lscope = liveins.copy()
self.local_defs = {}
self.visit_compound_statement(node.orelse)
else_defs = self.local_defs.copy()
else_block = self.builder.get_insertion_block()
else_vals = self.lscope.copy()
# update block arguments
names = []
# variables in livein whose value is updated in `if`
for name, value in liveins.items():
# livein variable changed value in either then or else
if not _is_triton_value(value):
continue
then_handles = flatten_values_to_ir([then_vals[name]])
else_handles = flatten_values_to_ir([else_vals[name]])
if then_handles == else_handles:
continue
names.append(name)
then_defs[name] = then_vals[name]
else_defs[name] = else_vals[name]
# check type
for defs, block_name in [(then_defs, 'then'), (else_defs, 'else')]:
type_equal = type(defs[name]) == type(value) # noqa: E721
assert type_equal and defs[name].type == value.type, \
f'initial value for `{name}` is of type {value}, '\
f'but the {block_name} block redefines it as {defs[name]}'
# variables that are both in then and else but not in liveins
# TODO: could probably be cleaned up
for name in sorted(then_defs.keys() & else_defs.keys()):
if name in names:
continue
then_val = then_defs[name]
then_ty = then_val.type
else_val = else_defs[name]
else_ty = else_val.type
type_equal = type(then_val) == type(else_val) # noqa: E721
assert type_equal and then_ty == else_ty, \
f'Mismatched type for {name} between then block ({then_ty}) '\
f'and else block ({else_ty})'
names.append(name)
return then_defs, else_defs, then_block, else_block, names
def visit_if_top_level(self, cond, node):
with enter_sub_region(self) as sr:
liveins, ip_block = sr
then_block = self.builder.create_block()
else_block = self.builder.create_block()
# create branch
self.builder.set_insertion_point_to_end(ip_block)
self.builder.create_cond_branch(cond.handle, then_block, else_block)
# visit then and else blocks
then_defs, else_defs, then_block, else_block, names = \
self.visit_then_else_blocks(node, liveins, then_block, else_block)
# create basic-block after conditional
endif_block = self.builder.create_block()
# then terminator
self.builder.set_insertion_point_to_end(then_block)
assert not then_block.has_terminator(), f"{then_block}"
then_handles = flatten_values_to_ir(then_defs[name] for name in names)
self.builder.create_branch(endif_block, then_handles)
# else terminator
self.builder.set_insertion_point_to_end(else_block)
assert not else_block.has_terminator(), f"{else_block}"
else_handles = flatten_values_to_ir(else_defs[name] for name in names)
self.builder.create_branch(endif_block, else_handles)
assert len(then_handles) == len(else_handles)
for then_h, else_h in zip(then_handles, else_handles):
ty = then_h.get_type()
assert ty == else_h.get_type()
endif_block.add_argument(ty)
# change block
self.builder.set_insertion_point_to_start(endif_block)
# update value
res_handles = [endif_block.arg(i) for i in range(len(then_handles))]
types = [then_defs[name].type for name in names]
new_values = unflatten_ir_values(res_handles, types)
for name, new_value in zip(names, new_values):
self.set_value(name, new_value)
# TODO: refactor
def visit_if_scf(self, cond, node):
with enter_sub_region(self) as sr:
liveins, _ = sr
ip, last_loc = self._get_insertion_point_and_loc()
then_block = self.builder.create_block()
else_block = self.builder.create_block() if node.orelse else None
then_defs, else_defs, then_block, else_block, names = \
self.visit_then_else_blocks(node, liveins, then_block, else_block)
# create if op
then_handles = flatten_values_to_ir(then_defs[name] for name in names)
for name, val in zip(names, then_handles):
self._maybe_set_loc_to_name(val, name)
self._set_insertion_point_and_loc(ip, last_loc)
if_op = self.builder.create_if_op([h.get_type() for h in then_handles], cond.handle, True)
then_block.merge_block_before(if_op.get_then_block())
self.builder.set_insertion_point_to_end(if_op.get_then_block())
if len(names) > 0:
self.builder.create_yield_op(then_handles)
if not node.orelse:
else_block = if_op.get_else_block()
else:
else_block.merge_block_before(if_op.get_else_block())
self.builder.set_insertion_point_to_end(if_op.get_else_block())
if len(names) > 0:
else_handles = flatten_values_to_ir(else_defs[name] for name in names)
for name, val in zip(names, else_handles):
self._maybe_set_loc_to_name(val, name)
self.builder.create_yield_op(else_handles)
# update values
res_handles = [if_op.get_result(i) for i in range(len(then_handles))]
types = [then_defs[name].type for name in names]
new_values = unflatten_ir_values(res_handles, types)
for name, new_value in zip(names, new_values):
self.set_value(name, new_value)
def visit_If(self, node):
cond = self.visit(node.test)
if _is_triton_tensor(cond):
if _is_non_scalar_tensor(cond):
raise self._unsupported(node, "Boolean value of Tensor with more than one value is ambiguous")
if cond.type.is_block():
warnings.warn(