-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplit_kernel.py
More file actions
2012 lines (1759 loc) · 73.2 KB
/
Copy pathsplit_kernel.py
File metadata and controls
2012 lines (1759 loc) · 73.2 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
#!/usr/bin/env python3
"""
Script to split kernel.cpp into separate files based on comment markers.
Each function section (identified by a comment line like "// foo__compute")
will be written to its own file.
"""
import argparse
import json
import os
import re
from pathlib import Path
MATMUL_MERGE_B_READER_OPTION = "matmul-merge-b-reader-into-writer"
MATMUL_SPLIT_HALF_DM_CORES_OPTION = "matmul-split-half-dm-cores"
def tileloom_option_enabled(option_name):
options = os.environ.get("TILELOOM_TO_TTKERNEL_OPTIONS", "")
for token in re.split(r"[\s,]+", options):
token = token.strip()
if not token:
continue
key, sep, value = token.partition("=")
if key != option_name:
continue
if not sep:
return True
return value.lower() not in {"0", "false", "off", "no"}
return False
def insert_include_if_missing(lines, include_line):
if any(line.strip() == include_line.strip() for line in lines):
return lines
insert_idx = 0
for i, line in enumerate(lines):
if line.startswith("#include"):
insert_idx = i + 1
lines.insert(insert_idx, include_line)
return lines
def insert_line_after_includes_if_missing(lines, new_line):
if any(line.strip() == new_line.strip() for line in lines):
return lines
insert_idx = 0
for i, line in enumerate(lines):
if line.startswith("#include"):
insert_idx = i + 1
lines.insert(insert_idx, new_line)
return lines
def insert_block_after_includes_if_missing(lines, block_lines):
stripped_block = [line.strip() for line in block_lines]
joined_window = "\n".join(line.strip() for line in lines)
if "\n".join(stripped_block) in joined_window:
return lines
insert_idx = 0
for i, line in enumerate(lines):
if line.startswith("#include"):
insert_idx = i + 1
for offset, line in enumerate(block_lines):
lines.insert(insert_idx + offset, line)
return lines
def is_flash_attention_section(lines, section_name=None):
haystacks = []
if section_name:
haystacks.append(section_name)
if lines:
haystacks.append(lines[0])
for text in haystacks:
normalized = text.lower().replace("-", "_")
normalized = re.sub(r"_+", "_", normalized)
if "flash_attention" in normalized:
return True
return False
def replace_second_flash_attention_exp_templates(lines):
seen = {"exp_tile_init": 0, "exp_tile": 0}
def repl(match):
name = match.group(1)
spacing = match.group(2)
seen[name] += 1
if seen[name] == 2:
if name == "exp_tile":
return f"{name}<true,{spacing}false,{spacing}true,{spacing}true>"
return f"{name}<true,{spacing}false>"
return match.group(0)
return [
re.sub(r"\b(exp_tile_init|exp_tile)<true,(\s*)true>", repl, line)
for line in lines
]
def insert_compute_trace_markers(lines):
"""
Insert DPRINT markers before cb_wait_front calls.
N is a running counter across both call kinds in source order.
"""
marker_pattern = re.compile(r"^\s*(cb_wait_front\s*\()")
dprint_pattern = re.compile(r'^\s*DPRINT\s*<<\s*"compute"\s*<<')
instrumented = []
counter = 0
for line in lines:
if marker_pattern.search(line):
if not (instrumented and dprint_pattern.search(instrumented[-1])):
indent = line[: len(line) - len(line.lstrip())]
if counter > 0:
instrumented.append(
f'{indent}DPRINT << "compute {counter}" << ENDL();\n'
)
counter += 1
instrumented.append(line)
return instrumented
def _try_parse_u32_for_header(line):
match = re.match(
r"^\s*for\s*\(\s*uint32_t\s+(\w+)\s*=\s*([^;]+);\s*\1\s*<\s*([^;]+);\s*\1\s*\+=\s*([^)]+)\)\s*\{\s*$",
line,
)
if not match:
return None
return {
"var": match.group(1).strip(),
"start": match.group(2).strip(),
"limit": match.group(3).strip(),
"step": match.group(4).strip(),
}
def _extract_uint32_constant_map(lines):
values = {}
for line in lines:
match = re.match(
r"^\s*uint32_t\s+(\w+)\s*=\s*(-?(?:0[xX][0-9a-fA-F]+|\d+))\s*;\s*$",
line,
)
if not match:
continue
symbol = match.group(1)
literal = match.group(2)
try:
values[symbol] = int(literal, 0)
except ValueError:
continue
return values
def _resolve_int_token(token, constants):
tok = token.strip()
if tok in constants:
return constants[tok]
try:
return int(tok, 0)
except ValueError:
return None
def _is_zero_token(token, constants):
value = _resolve_int_token(token, constants)
return value == 0
def _is_one_token(token, constants):
value = _resolve_int_token(token, constants)
return value == 1
def _match_copy_block(lines, start_idx, constants):
if start_idx + 10 >= len(lines):
return None
m_reserve = re.match(
r"^(\s*)cb_reserve_back\(([^,]+),\s*([^)]+)\);\s*$", lines[start_idx]
)
if not m_reserve:
return None
indent = m_reserve.group(1)
reserved_out_cb = m_reserve.group(2).strip()
reserved_tile_count = m_reserve.group(3).strip()
init_idx = start_idx + 1
m_init = re.match(r"^\s*copy_tile_init\(([^)]+)\);\s*$", lines[init_idx])
if not m_init:
return None
in_cb = m_init.group(1).strip()
loop = _try_parse_u32_for_header(lines[init_idx + 1])
if not loop:
return None
if loop["limit"] != reserved_tile_count:
return None
if not _is_zero_token(loop["start"], constants) or not _is_one_token(
loop["step"], constants
):
return None
if lines[init_idx + 2].strip() != "tile_regs_acquire();":
return None
m_copy = re.match(
r"^\s*copy_tile\(([^,]+),\s*([^,]+),\s*([^)]+)\);\s*$", lines[init_idx + 3]
)
if not m_copy:
return None
copy_in_cb = m_copy.group(1).strip()
copy_tile_idx = m_copy.group(2).strip()
dst_idx = m_copy.group(3).strip()
if copy_in_cb != in_cb or copy_tile_idx != loop["var"]:
return None
if lines[init_idx + 4].strip() != "tile_regs_commit();":
return None
if lines[init_idx + 5].strip() != "tile_regs_wait();":
return None
m_pack = re.match(
r"^\s*pack_tile<true>\(([^,]+),\s*([^,]+),\s*([^)]+)\);\s*$",
lines[init_idx + 6],
)
if not m_pack:
return None
pack_dst = m_pack.group(1).strip()
out_cb = m_pack.group(2).strip()
pack_tile_idx = m_pack.group(3).strip()
if (
pack_dst != dst_idx
or pack_tile_idx != loop["var"]
or out_cb != reserved_out_cb
):
return None
if lines[init_idx + 7].strip() != "tile_regs_release();":
return None
if lines[init_idx + 8].strip() != "}":
return None
m_push = re.match(
r"^\s*cb_push_back\(([^,]+),\s*([^)]+)\);\s*$", lines[init_idx + 9]
)
if not m_push:
return None
push_out = m_push.group(1).strip()
push_tiles = m_push.group(2).strip()
if push_out != out_cb or push_tiles != loop["limit"]:
return None
replacement = (
f"{indent}loom_copy_block({in_cb}, {out_cb}, {loop['limit']}, {dst_idx});\n"
)
return {"end_idx": init_idx + 10, "replacement": replacement}
def _match_fill_block(lines, start_idx, constants):
if start_idx + 11 >= len(lines):
return None
m_reserve = re.match(
r"^(\s*)cb_reserve_back\(([^,]+),\s*([^)]+)\);\s*$", lines[start_idx]
)
if not m_reserve:
return None
indent = m_reserve.group(1)
out_cb = m_reserve.group(2).strip()
tile_count = m_reserve.group(3).strip()
m_init = re.match(
r"^\s*init_sfpu\(([^,]+),\s*([^)]+)\);\s*$", lines[start_idx + 1]
)
if not m_init:
return None
if m_init.group(1).strip() != out_cb or m_init.group(2).strip() != out_cb:
return None
if lines[start_idx + 2].strip() != "fill_tile_init();":
return None
loop = _try_parse_u32_for_header(lines[start_idx + 3])
if not loop:
return None
if (
loop["limit"] != tile_count
or not _is_zero_token(loop["start"], constants)
or not _is_one_token(loop["step"], constants)
):
return None
if lines[start_idx + 4].strip() != "tile_regs_acquire();":
return None
m_fill = re.match(
r"^\s*fill_tile\(([^,]+),\s*([^)]+)\);\s*$", lines[start_idx + 5]
)
if not m_fill:
return None
dst_idx = m_fill.group(1).strip()
fill_val = m_fill.group(2).strip()
if lines[start_idx + 6].strip() != "tile_regs_commit();":
return None
if lines[start_idx + 7].strip() != "tile_regs_wait();":
return None
m_pack = re.match(
r"^\s*pack_tile<true>\(([^,]+),\s*([^,]+),\s*([^)]+)\);\s*$", lines[start_idx + 8]
)
if not m_pack:
return None
pack_dst = m_pack.group(1).strip()
pack_out = m_pack.group(2).strip()
pack_tile_idx = m_pack.group(3).strip()
if pack_dst != dst_idx or pack_out != out_cb or pack_tile_idx != loop["var"]:
return None
if lines[start_idx + 9].strip() != "tile_regs_release();":
return None
if lines[start_idx + 10].strip() != "}":
return None
m_push = re.match(
r"^\s*cb_push_back\(([^,]+),\s*([^)]+)\);\s*$", lines[start_idx + 11]
)
if not m_push:
return None
if m_push.group(1).strip() != out_cb or m_push.group(2).strip() != tile_count:
return None
replacement = (
f"{indent}loom_fill_block({out_cb}, {tile_count}, {fill_val}, {dst_idx});\n"
)
return {"end_idx": start_idx + 12, "replacement": replacement}
def _match_unary_bcast_block(lines, start_idx, constants):
if start_idx + 11 >= len(lines):
return None
m_wait = re.match(
r"^(\s*)cb_wait_front\(([^,]+),\s*([^)]+)\);\s*$", lines[start_idx]
)
if not m_wait:
return None
indent = m_wait.group(1)
in_cb = m_wait.group(2).strip()
tile_count = m_wait.group(3).strip()
m_reserve = re.match(
r"^\s*cb_reserve_back\(([^,]+),\s*([^)]+)\);\s*$", lines[start_idx + 1]
)
if not m_reserve:
return None
out_cb = m_reserve.group(1).strip()
reserve_tiles = m_reserve.group(2).strip()
if reserve_tiles != tile_count:
return None
m_init = re.match(
r"^\s*unary_bcast_init<BroadcastType::(ROW|COL)>\(([^,]+),\s*([^)]+)\);\s*$",
lines[start_idx + 2],
)
if not m_init:
return None
kind = m_init.group(1)
init_in_cb = m_init.group(2).strip()
init_out_cb = m_init.group(3).strip()
if init_in_cb != in_cb or init_out_cb != out_cb:
return None
loop = _try_parse_u32_for_header(lines[start_idx + 3])
if not loop:
return None
if loop["limit"] != tile_count:
return None
if not _is_zero_token(loop["start"], constants) or not _is_one_token(
loop["step"], constants
):
return None
if lines[start_idx + 4].strip() != "tile_regs_acquire();":
return None
m_bcast = re.match(
r"^\s*unary_bcast<BroadcastType::(ROW|COL)>\(([^,]+),\s*([^,]+),\s*([^)]+)\);\s*$",
lines[start_idx + 5],
)
if not m_bcast:
return None
tile_kind = m_bcast.group(1)
tile_in_cb = m_bcast.group(2).strip()
tile_idx = m_bcast.group(3).strip()
dst_idx = m_bcast.group(4).strip()
if tile_kind != kind or tile_in_cb != in_cb or tile_idx != loop["var"]:
return None
if lines[start_idx + 6].strip() != "tile_regs_commit();":
return None
if lines[start_idx + 7].strip() != "tile_regs_wait();":
return None
m_pack = re.match(
r"^\s*pack_tile<true>\(([^,]+),\s*([^,]+),\s*([^)]+)\);\s*$",
lines[start_idx + 8],
)
if not m_pack:
return None
pack_dst = m_pack.group(1).strip()
pack_out_cb = m_pack.group(2).strip()
pack_tile_idx = m_pack.group(3).strip()
if pack_dst != dst_idx or pack_out_cb != out_cb or pack_tile_idx != loop["var"]:
return None
if lines[start_idx + 9].strip() != "tile_regs_release();":
return None
if lines[start_idx + 10].strip() != "}":
return None
m_push = re.match(
r"^\s*cb_push_back\(([^,]+),\s*([^)]+)\);\s*$", lines[start_idx + 11]
)
if not m_push:
return None
if m_push.group(1).strip() != out_cb or m_push.group(2).strip() != loop["limit"]:
return None
kind_token = (
"LOOM_BCAST_KIND_ROW" if kind == "ROW" else "LOOM_BCAST_KIND_COL"
)
replacement = (
f"{indent}loom_unary_bcast_block({in_cb}, {out_cb}, {loop['limit']}, {dst_idx}, {kind_token});\n"
)
return {"end_idx": start_idx + 12, "replacement": replacement}
def _match_inplace_cb_advance_block(lines, start_idx):
if start_idx + 2 >= len(lines):
return None
m_pop = re.match(
r"^(\s*)cb_pop_front\(([^,]+),\s*([^)]+)\);\s*$", lines[start_idx]
)
if not m_pop:
return None
indent = m_pop.group(1)
cb_id = m_pop.group(2).strip()
tile_count = m_pop.group(3).strip()
m_reserve = re.match(
r"^\s*cb_reserve_back\(([^,]+),\s*([^)]+)\);\s*$", lines[start_idx + 1]
)
if not m_reserve:
return None
reserve_cb = m_reserve.group(1).strip()
reserve_tiles = m_reserve.group(2).strip()
if reserve_cb != cb_id or reserve_tiles != tile_count:
return None
m_push = re.match(
r"^\s*cb_push_back\(([^,]+),\s*([^)]+)\);\s*$", lines[start_idx + 2]
)
if not m_push:
return None
push_cb = m_push.group(1).strip()
push_tiles = m_push.group(2).strip()
if push_cb != cb_id or push_tiles != tile_count:
return None
replacement = f"{indent}loom_inplace_cb_advance({cb_id}, {tile_count});\n"
return {"end_idx": start_idx + 3, "replacement": replacement}
def _match_commit_wait_pack_release_block(lines, start_idx):
if start_idx + 3 >= len(lines):
return None
if lines[start_idx].strip() != "tile_regs_commit();":
return None
if lines[start_idx + 1].strip() != "tile_regs_wait();":
return None
m_pack = re.match(
r"^(\s*)pack_tile<true>\(([^,]+),\s*([^,]+),\s*([^)]+)\);\s*$",
lines[start_idx + 2],
)
if not m_pack:
return None
indent = m_pack.group(1)
dst_idx = m_pack.group(2).strip()
out_cb = m_pack.group(3).strip()
tile_idx = m_pack.group(4).strip()
if lines[start_idx + 3].strip() != "tile_regs_release();":
return None
replacement = (
f"{indent}loom_commit_wait_pack_release({dst_idx}, {out_cb}, {tile_idx});\n"
)
return {"end_idx": start_idx + 4, "replacement": replacement}
def _compact_compute_blocks(lines):
constants = _extract_uint32_constant_map(lines)
compacted = []
usage = {
"copy": False,
"fill": False,
"bcast": False,
"inplace": False,
"pack_release": False,
}
i = 0
while i < len(lines):
fill = _match_fill_block(lines, i, constants)
if fill:
compacted.append(fill["replacement"])
usage["fill"] = True
i = fill["end_idx"]
continue
copy = _match_copy_block(lines, i, constants)
if copy:
compacted.append(copy["replacement"])
usage["copy"] = True
i = copy["end_idx"]
continue
bcast = _match_unary_bcast_block(lines, i, constants)
if bcast:
compacted.append(bcast["replacement"])
usage["bcast"] = True
i = bcast["end_idx"]
continue
inplace = _match_inplace_cb_advance_block(lines, i)
if inplace:
compacted.append(inplace["replacement"])
usage["inplace"] = True
i = inplace["end_idx"]
continue
pack_release = _match_commit_wait_pack_release_block(lines, i)
if pack_release:
compacted.append(pack_release["replacement"])
usage["pack_release"] = True
i = pack_release["end_idx"]
continue
compacted.append(lines[i])
i += 1
return compacted, usage
def _build_compute_helper_block(usage):
block = []
block.append("\n")
if usage.get("bcast"):
block.extend(
[
"constexpr uint32_t LOOM_BCAST_KIND_ROW = 0;\n",
"constexpr uint32_t LOOM_BCAST_KIND_COL = 1;\n",
"\n",
"template <BroadcastType BcastKind>\n",
"__attribute__((noinline)) void loom_unary_bcast_block_impl(\n",
" uint32_t in_cb, uint32_t out_cb, uint32_t tile_count,\n",
" uint32_t dst_idx) {\n",
" cb_wait_front(in_cb, tile_count);\n",
" cb_reserve_back(out_cb, tile_count);\n",
" unary_bcast_init<BcastKind>(in_cb, out_cb);\n",
" for (uint32_t i = 0; i < tile_count; i += 1) {\n",
" tile_regs_acquire();\n",
" unary_bcast<BcastKind>(in_cb, i, dst_idx);\n",
" tile_regs_commit();\n",
" tile_regs_wait();\n",
" pack_tile<true>(dst_idx, out_cb, i);\n",
" tile_regs_release();\n",
" }\n",
" cb_push_back(out_cb, tile_count);\n",
"}\n",
"\n",
"__attribute__((noinline)) void loom_unary_bcast_block(\n",
" uint32_t in_cb, uint32_t out_cb, uint32_t tile_count,\n",
" uint32_t dst_idx, uint32_t bcast_kind) {\n",
" if (bcast_kind == LOOM_BCAST_KIND_ROW) {\n",
" loom_unary_bcast_block_impl<BroadcastType::ROW>(in_cb, out_cb,\n",
" tile_count, dst_idx);\n",
" return;\n",
" }\n",
" loom_unary_bcast_block_impl<BroadcastType::COL>(in_cb, out_cb,\n",
" tile_count, dst_idx);\n",
"}\n",
"\n",
]
)
if usage.get("copy"):
block.extend(
[
"__attribute__((noinline)) void loom_copy_block(\n",
" uint32_t in_cb, uint32_t out_cb, uint32_t tile_count,\n",
" uint32_t dst_idx) {\n",
" cb_reserve_back(out_cb, tile_count);\n",
" copy_tile_init(in_cb);\n",
" for (uint32_t i = 0; i < tile_count; i += 1) {\n",
" tile_regs_acquire();\n",
" copy_tile(in_cb, i, dst_idx);\n",
" tile_regs_commit();\n",
" tile_regs_wait();\n",
" pack_tile<true>(dst_idx, out_cb, i);\n",
" tile_regs_release();\n",
" }\n",
" cb_push_back(out_cb, tile_count);\n",
"}\n",
"\n",
]
)
if usage.get("fill"):
block.extend(
[
"__attribute__((noinline)) void loom_fill_block(\n",
" uint32_t out_cb, uint32_t tile_count, float fill_val,\n",
" uint32_t dst_idx) {\n",
" cb_reserve_back(out_cb, tile_count);\n",
" init_sfpu(out_cb, out_cb);\n",
" fill_tile_init();\n",
" for (uint32_t i = 0; i < tile_count; i += 1) {\n",
" tile_regs_acquire();\n",
" fill_tile(dst_idx, fill_val);\n",
" tile_regs_commit();\n",
" tile_regs_wait();\n",
" pack_tile<true>(dst_idx, out_cb, i);\n",
" tile_regs_release();\n",
" }\n",
" cb_push_back(out_cb, tile_count);\n",
"}\n",
"\n",
]
)
if usage.get("inplace"):
block.extend(
[
"__attribute__((noinline)) void loom_inplace_cb_advance(\n",
" uint32_t cb_id, uint32_t tile_count) {\n",
" cb_pop_front(cb_id, tile_count);\n",
" cb_reserve_back(cb_id, tile_count);\n",
" cb_push_back(cb_id, tile_count);\n",
"}\n",
"\n",
]
)
if usage.get("pack_release"):
block.extend(
[
"__attribute__((noinline)) void loom_commit_wait_pack_release(\n",
" uint32_t dst_idx, uint32_t out_cb, uint32_t tile_idx) {\n",
" tile_regs_commit();\n",
" tile_regs_wait();\n",
" pack_tile<true>(dst_idx, out_cb, tile_idx);\n",
" tile_regs_release();\n",
"}\n",
"\n",
]
)
return block
def _split_top_level_args(args_text):
args = []
current = []
depth = 0
for char in args_text:
if char in "([{<":
depth += 1
elif char in ")]}>":
depth = max(depth - 1, 0)
elif char == "," and depth == 0:
args.append("".join(current).strip())
current = []
continue
current.append(char)
last_arg = "".join(current).strip()
if last_arg:
args.append(last_arg)
return args
def _restore_multicast_bool_args(line):
multicast_ops = {
"noc_async_write_multicast": 4
}
match = re.match(
r"^(\s*)(noc_async_write_multicast)\((.*)\)(\s*;\s*(?://.*)?\n?)$",
line,
)
if not match:
return line
indent, op_name, args_text, suffix = match.groups()
args = _split_top_level_args(args_text)
expected_args_without_attrs = multicast_ops[op_name]
if len(args) != expected_args_without_attrs:
return line
return f"{indent}{op_name}({args_text}, true){suffix}"
def process_source_content(lines, section_name=None):
"""
Process source file content by applying necessary replacements.
Args:
lines: List of source code lines
Returns:
List of processed lines with replacements applied
"""
processed = [
line.replace("::tt::CB", "uint32_t")
.replace('uint32_t', 'int32_t')
.replace('int32_t', 'uint32_t')
.replace('pack_tile<false>', 'pack_tile<true>')
.replace("tt_metal/programming_examples/", '')
.replace('"api/dataflow/circular_buffer.h"', '"circular_buffer.h"')
.replace('"api/dataflow/dataflow_api.h"', '"dataflow_api.h"')
.replace("INFINITY", '__builtin_inff()')
for line in lines
]
processed = [_restore_multicast_bool_args(line) for line in processed]
if section_name and section_name.startswith("host_pybind"):
processed = [
line
for line in processed
if line.strip()
not in {
'#include "tools/profiler/kernel_profiler.hpp"',
'#include "firmware_common.h"',
'#include "dataflow_api.h"',
}
]
processed = [line.replace(" tt_metal::", " tt::tt_metal::").replace('CBIndex::', 'tt::CBIndex::') for line in lines]
if section_name and section_name.startswith("reader"):
processed = insert_include_if_missing(processed, '#include "ttnn/operations/ccl/kernel_common/worker_sync_utils.hpp"\n')
if section_name and section_name.startswith("host"):
processed = insert_include_if_missing(
processed, "#include <tt-metalium/host_api.hpp>\n"
)
processed = insert_include_if_missing(
processed, "#include <tt-metalium/tensor_accessor_args.hpp>\n"
)
processed = insert_include_if_missing(
processed, "#include <tt-metalium/buffer.hpp>\n"
)
processed = insert_block_after_includes_if_missing(
processed,
[
"#ifndef OVERRIDE_KERNEL_PREFIX\n",
'#define OVERRIDE_KERNEL_PREFIX ""\n',
"#endif\n",
],
)
if section_name and section_name.startswith("host_pybind"):
processed = insert_include_if_missing(
processed, "#include <tt-metalium/constants.hpp>\n"
)
processed = insert_include_if_missing(
processed, '#include "ttnn/operation.hpp"\n'
)
processed = insert_include_if_missing(processed, "#include <optional>\n")
processed = insert_include_if_missing(processed, "#include <utility>\n")
processed = insert_include_if_missing(processed, "#include <vector>\n")
processed = insert_line_after_includes_if_missing(
processed, "using namespace tt::constants;\n"
)
processed = insert_line_after_includes_if_missing(
processed, "using namespace tt::tt_metal;\n"
)
processed = insert_line_after_includes_if_missing(
processed, "namespace tt_metal = tt::tt_metal;\n"
)
if section_name and (
section_name.startswith("host_cpp") or section_name == "host.cpp"
):
processed = insert_include_if_missing(processed, "#include <vector>\n")
if section_name and section_name.startswith("compute"):
#it seems that math.h is not needed for compute kernels on blackhole machine
#processed = insert_include_if_missing(processed, '#include "math.h"\n')
processed = insert_include_if_missing(processed, '#include "debug/dprint.h"\n')
processed = insert_include_if_missing(processed, '#include "debug/dprint_pages.h"\n')
processed = insert_include_if_missing(processed, '#include "debug/dprint_tensix.h"\n')
processed = [i.replace("mm_init", "ckernel::mm_init").replace("mm_block_init_short", "ckernel::mm_block_init_short") for i in processed]
#for performance and correctness of exp_tile
processed = [i.replace("exp_tile(", "exp_tile<true, true>(").replace("exp_tile_init(", "exp_tile_init<true, true>(") for i in processed]
# TMP: FlashAttention exp lowering currently needs these template flags off.
if is_flash_attention_section(lines, section_name):
processed = replace_second_flash_attention_exp_templates(processed)
processed, compaction_usage = _compact_compute_blocks(processed)
if any(compaction_usage.values()):
helper_block = _build_compute_helper_block(compaction_usage)
processed = insert_block_after_includes_if_missing(processed, helper_block)
#Don't need it now
#processed = insert_compute_trace_markers(processed)
return processed
def extract_marker_symbol(comment_line):
name = comment_line.strip()
if name.startswith("//"):
name = name[2:].strip()
return name
def make_program_factory_name(comment_line):
name = extract_marker_symbol(comment_line)
if name.endswith("__host_pybind"):
name = name[: -len("__host_pybind")]
name = re.sub(r"[^\w]", "_", name)
return f"{name}_program_factory"
def transform_host_pybind_source(lines):
if not lines:
return lines
signature_pattern = re.compile(r"^(\s*)void\s+kernel_main\s*\(")
return_pattern = re.compile(r"^(\s*)return;\s*$")
factory_name = make_program_factory_name(lines[0])
transformed = []
signature_rewritten = False
return_indices = []
for line in lines:
if not signature_rewritten and signature_pattern.search(line):
line = signature_pattern.sub(
rf"\1tt::tt_metal::operation::ProgramWithCallbacks {factory_name}(",
line,
count=1,
)
signature_rewritten = True
transformed.append(line)
if return_pattern.match(line):
return_indices.append(len(transformed) - 1)
if return_indices:
last_return_idx = return_indices[-1]
indent = return_pattern.match(transformed[last_return_idx]).group(1)
transformed[last_return_idx] = (
f"{indent}return {{.program = std::move(program), "
f".override_runtime_arguments_callback = "
f"override_runtime_arguments_callback}};\n"
)
return transformed
def make_host_ttnn_filename(section_cpp_filename):
if not section_cpp_filename.startswith("host_pybind") or not section_cpp_filename.endswith(".cpp"):
return None
suffix = section_cpp_filename[len("host_pybind") : -len(".cpp")]
return f"host_ttnn{suffix}.py"
def _safe_eval_u32_expr(expr, symbols):
rewritten = expr
for name, value in symbols.items():
pattern = r"\b" + re.escape(name) + r"\b"
rewritten = re.sub(pattern, str(value), rewritten)
rewritten = rewritten.replace("/", "//")
if not re.fullmatch(r"[0-9\(\)\+\-\*\/\s]+", rewritten):
raise ValueError(f"unsupported expression: {expr}")
return int(eval(rewritten, {"__builtins__": {}}, {}))
def _parse_noc_index(noc_token):
token = noc_token.split("::")[-1]
if token in {"RISCV_0_default", "NOC_0"}:
return 0
if token in {"RISCV_1_default", "NOC_1"}:
return 1
return None
def _parse_data_movement_processor(processor_token):
token = processor_token.split("::")[-1]
if token == "RISCV_0":
return 0
if token == "RISCV_1":
return 1
return None
def _uses_swapped_reader_writer_nocs(metadata):
configs = metadata.get("kernel_dm_configs", {})
reader = configs.get("reader", {})
writer = configs.get("writer", {})
return (
reader.get("processor") == 1
and reader.get("noc") == 1
and writer.get("processor") == 0
and writer.get("noc") == 0
)
def _normalize_token(token):
tok = token.strip()
if tok.endswith(","):
tok = tok[:-1].strip()
return tok
def _strip_outer_cpp_casts(expr):
rewritten = expr.strip()
while True:
prev = rewritten
static_cast_match = re.match(r"^static_cast<\s*[^>]+\s*>\((.*)\)$", rewritten)
if static_cast_match:
rewritten = static_cast_match.group(1).strip()
continue
c_style_cast_match = re.match(
r"^\(\s*(?:std::)?(?:u?int\d+_t|size_t)\s*\)\s*(.*)$", rewritten
)
if c_style_cast_match:
rewritten = c_style_cast_match.group(1).strip()
continue
if rewritten == prev:
break
return rewritten
def _translate_cpp_expr_to_python(expr):
rewritten = expr.strip().rstrip(";").strip()
rewritten = _strip_outer_cpp_casts(rewritten)
rewritten = re.sub(r"\b(\d+)[uUlL]+\b", r"\1", rewritten)
rewritten = rewritten.replace("core.x", "core_x").replace("core.y", "core_y")
rewritten = re.sub(r"\b([A-Za-z_]\w*)\.(x|y)\b", r"\1_\2", rewritten)
rewritten = re.sub(r"\btrue\b", "True", rewritten)
rewritten = re.sub(r"\bfalse\b", "False", rewritten)
rewritten = re.sub(r"\bstd::", "", rewritten)
rewritten = rewritten.replace("/", "//")
return rewritten
def _extract_runtime_loop_indices(lines):
runtime_blocks = {}
runtime_decl_re = re.compile(
r"std::vector<\s*uint32_t\s*>\s+"
r"((?:reader|writer|compute)_runtime_args_for_core|runtime_args_for_core)"
r"\s*=\s*\{"
)
idx = 0
while idx < len(lines):
match = runtime_decl_re.search(lines[idx])
if not match:
idx += 1
continue
var_name = match.group(1)
end_idx = idx + 1
while end_idx < len(lines) and lines[end_idx].strip() != "};":
end_idx += 1
if end_idx >= len(lines):
raise ValueError(f"runtime args block for {var_name} is unterminated")
runtime_blocks.setdefault(var_name, (idx, end_idx))
idx = end_idx + 1