Repository navigation
Expand file tree
/
Copy pathsplit_cpp_sections.py
More file actions
404 lines (379 loc) · 18.3 KB
/
Copy pathsplit_cpp_sections.py
File metadata and controls
404 lines (379 loc) · 18.3 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
import os
import re
import sys
import json
_SCRIPT = os.path.dirname(os.path.abspath(__file__))
_ROOT = os.path.dirname(_SCRIPT)
if _ROOT not in sys.path:
sys.path.insert(0, _ROOT)
from tools.log_utils import setup_logger
log = setup_logger("split_cpp")
def normalize_path(p):
return os.path.abspath(p.replace("\\", "/"))
# def split_cpp_file(path):
# p = normalize_path(path)
# with open(p, "r", encoding="utf-8") as f:
# text = f.read()
# m = re.search(r"(?m)^[^\n]*\bvoid\s+Compute\s*\([^)]*\)\s*\{", text)
# if not m:
# return text, "", ""
# header_line_start = text.rfind("\n", 0, m.start())
# header_line_start = 0 if header_line_start == -1 else header_line_start + 1
# open_brace_index = text.find("{", m.start())
# depth = 0
# end_index = None
# for i, ch in enumerate(text[open_brace_index:], start=open_brace_index):
# if ch == "{":
# depth += 1
# elif ch == "}":
# depth -= 1
# if depth == 0:
# end_index = i
# break
# if end_index is None:
# return text[:header_line_start], text[open_brace_index + 1 :], ""
# body = text[open_brace_index + 1 : end_index]
# node0 = re.search(r"(?m)//\s*node\s*0\b", body)
# if not node0:
# return text[:header_line_start], body, ""
# pre_node0_line_start = body.rfind("\n", 0, node0.start())
# pre_node0_line_start = 0 if pre_node0_line_start == -1 else pre_node0_line_start + 1
# part1 = text[:header_line_start]
# part2 = body[:pre_node0_line_start]
# part3 = body[pre_node0_line_start:]
# return part1, part2, part3
def split_cpp_file(path):
p = normalize_path(path)
with open(p, "r", encoding="utf-8") as f:
text = f.read()
m = re.search(r"(?m)^[^\n]*\bvoid\s+Compute\s*\([^)]*\)\s*\{", text)
if not m:
return text, "", ""
header_line_start = text.rfind("\n", 0, m.start())
header_line_start = 0 if header_line_start == -1 else header_line_start + 1
open_brace_index = text.find("{", m.start())
depth = 0
end_index = None
for i, ch in enumerate(text[open_brace_index:], start=open_brace_index):
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
end_index = i
break
if end_index is None:
return text[:header_line_start], text[open_brace_index + 1 :], ""
body = text[open_brace_index + 1 : end_index]
# 修改点:查找第一个 // node 标记(不限定数字)
node = re.search(r"(?m)//\s*node\b", body)
if not node:
return text[:header_line_start], body, ""
pre_node_line_start = body.rfind("\n", 0, node.start())
pre_node_line_start = 0 if pre_node_line_start == -1 else pre_node_line_start + 1
part1 = text[:header_line_start]
part2 = body[:pre_node_line_start]
part3 = body[pre_node_line_start:]
return part1, part2, part3
def find_all_calls(text, keywords=("MatMul",)):
calls = []
for m in re.finditer(r"(?mi)^[^\n]*\b(" + "|".join(keywords) + r")\s*\(", text):
le = text.find("\n", m.end())
ls = text.rfind("\n", 0, m.start())
ls = 0 if ls == -1 else ls + 1
line = text[ls:] if le == -1 else text[ls:le]
args_all = []
args_first3 = []
mm = re.search(r"\(([^)]*)\)", line)
if mm:
inside = mm.group(1)
parts = [p.strip() for p in inside.split(",")]
args_all = parts
args_first3 = parts[:3]
calls.append({
"start_line": ls,
"end_line": le if le != -1 else len(text),
"line": line,
"args_all": args_all,
"args_first3": args_first3
})
return calls
def remove_duplicate_decls(text):
"""Post-merge cleanup: remove duplicate infrastructure declarations,
keeping only the first occurrence of each. Operates on the final merged file."""
patterns = [
(re.compile(r'^\s*AscendC::LocalTensor<uint8_t>\s+tmp\s*;\s*$'), 'LocalTensor tmp'),
(re.compile(r'^\s*bool\s+ans\s*=\s*AscendC::PopStackBuffer\s*<[^>]*>\s*\(\s*tmp\s*\)\s*;\s*$'), 'PopStackBuffer'),
(re.compile(r'^\s*int\s+offset_ptr\s*=\s*0\s*;\s*$'), 'offset_ptr = 0'),
(re.compile(r'^\s*int\s+tensor_len\s*=\s*\d+\s*;\s*$'), 'int tensor_len'),
(re.compile(r'^\s*int\s+active_len\s*=\s*\d+\s*;\s*$'), 'int active_len'),
]
lines = text.splitlines(True)
result = []
seen = set()
for line in lines:
skip = False
for pat, key in patterns:
if pat.match(line):
if key in seen:
skip = True
else:
seen.add(key)
break
if not skip:
result.append(line)
return ''.join(result)
def clean_conflicting_decls(text):
"""Remove variable declarations from generated Compute() that conflict
with the baremix template (offset_ptr, tensor_len, tmp/sharedTmpBuffer,
PopStackBuffer, input1, input2Local).
Template now provides these natively, so injected code must not redeclare."""
# Rename sharedTmpBuffer → tmp so injected code uses the template's variable name
text = text.replace('sharedTmpBuffer', 'tmp')
# Remove AscendC::LocalTensor<uint8_t> tmp; — template provides this
text = re.sub(r'^\s*AscendC::LocalTensor<uint8_t>\s+tmp\s*;\s*$', '', text, flags=re.MULTILINE)
# Remove bool ans = PopStackBuffer<...>(tmp); — template calls PopStackBuffer
text = re.sub(r'^\s*bool\s+ans\s*=\s*AscendC::PopStackBuffer\s*<[^>]*>\s*\(\s*tmp\s*\)\s*;\s*$', '', text, flags=re.MULTILINE)
# Remove int offset_ptr = ...; — template declares this at kernel scope
text = re.sub(r'^\s*int\s+offset_ptr\s*=\s*[^;]*;\s*$', '', text, flags=re.MULTILINE)
# Remove int sharedTmpBufferSize = ...; — not needed in baremix template
text = re.sub(r'^\s*int\s+sharedTmpBufferSize\s*=\s*[^;]*;\s*$', '', text, flags=re.MULTILINE)
# Remove constexpr int kOutNum = ...; — not needed in baremix template
text = re.sub(r'^\s*constexpr\s+int\s+kOutNum\s*=\s*[^;]*;\s*$', '', text, flags=re.MULTILINE)
# Remove AscendC::Duplicate<float>(outputX, 0.0f, ...); zero-init (template handles this)
text = re.sub(r'^\s*AscendC::Duplicate<float>\s*\(\s*output\d+\s*,\s*0\.0f\s*,\s*[^)]*\)\s*;\s*$', '', text, flags=re.MULTILINE)
# Remove int tensor_len = ...; — template now declares both tensor_len and active_len
text = re.sub(r'^\s*int\s+tensor_len\s*=\s*[^;]*;\s*$', '', text, flags=re.MULTILINE)
# Remove int active_len = ...; — template declares this
text = re.sub(r'^\s*int\s+active_len\s*=\s*[^;]*;\s*$', '', text, flags=re.MULTILINE)
# Remove LocalTensor<float> input1; — template allocates this in AIV section
text = re.sub(r'^\s*AscendC::LocalTensor<float>\s+input1\s*;\s*$', '', text, flags=re.MULTILINE)
# Remove input1.SetAddrWithOffset(...);
text = re.sub(r'^\s*input1\.SetAddrWithOffset\s*\([^)]*\)\s*;\s*$', '', text, flags=re.MULTILINE)
# Remove input1.SetSize(...);
text = re.sub(r'^\s*input1\.SetSize\s*\([^)]*\)\s*;\s*$', '', text, flags=re.MULTILINE)
# Remove offset_ptr += input1.GetSize(); — avoid gap after removing input1 alloc
text = re.sub(r'^\s*offset_ptr\s*\+=\s*input1\.GetSize\s*\(\s*\)\s*;\s*$', '', text, flags=re.MULTILINE)
# Remove LocalTensor<int32_t> input2Local; — template allocates this in AIV section
text = re.sub(r'^\s*AscendC::LocalTensor<int32_t>\s+input2Local\s*;\s*$', '', text, flags=re.MULTILINE)
# Remove input2Local.SetAddrWithOffset(...);
text = re.sub(r'^\s*input2Local\.SetAddrWithOffset\s*\([^)]*\)\s*;\s*$', '', text, flags=re.MULTILINE)
# Remove input2Local.SetSize(...);
text = re.sub(r'^\s*input2Local\.SetSize\s*\([^)]*\)\s*;\s*$', '', text, flags=re.MULTILINE)
return text
def find_max_output_var(text):
nums = [int(n) for n in re.findall(r"\boutput(\d+)\b", text)]
if not nums:
return ""
return f"output{max(nums)}"
def inject_missing_wrappers(pre_compute_text, all_code):
"""Auto-inject vector wrappers for scalar APIs referenced in compute code
but missing from pre_compute. Returns (possibly augmented) pre_compute_text."""
wrappers = {
'ScalarGetSFFValue': ''' __aicore__ inline void ScalarGetSFFValue(const AscendC::LocalTensor<float> &output,
const AscendC::LocalTensor<float> &input0,
const int32_t data_length) {
for (int32_t i = 0; i < data_length; ++i) {
uint64_t u64 = static_cast<uint64_t>(static_cast<int64_t>(static_cast<int32_t>(input0.GetValue(i))));
int64_t pos = AscendC::ScalarGetSFFValue<1>(u64);
output.SetValue(i, static_cast<float>(pos));
}
}''',
'Muls': '''__aicore__ inline void Muls(const AscendC::LocalTensor<float> &output,
const AscendC::LocalTensor<float> &input0,
const int32_t data_length) {
// Default scalar=2.0f, to match graph generation call format
const float default_scalar = 2.0f;
AscendC::Muls(output, input0, default_scalar, data_length);
}''',
}
for name, wrapper in wrappers.items():
# 匹配任何 3 参数调用: name( arg1, arg2, arg3 ) — 第三个参数可以是任意标识符
call_3arg = re.compile(
r'\b' + re.escape(name) + r'\s*\(\s*\w+\s*,\s*\w+\s*,\s*\w+\s*\)')
# 匹配 wrapper 函数定义(不管是 __aicore__ inline void 还是单独 void)
def_pat = re.compile(
r'\bvoid\s+' + re.escape(name) + r'\s*\(')
has_call = bool(call_3arg.search(all_code))
has_def = bool(def_pat.search(pre_compute_text))
if has_call and not has_def:
log.info(f"INJECTING {name} wrapper (call_found=True, def_found=False)")
pre_compute_text = pre_compute_text.rstrip('\n') + '\n\n' + wrapper + '\n'
else:
log.info(f"SKIP {name}: call_found={has_call}, def_found={has_def}")
# Auto-inject Mask1/Mask2 wrappers from wrappers/ directory
# 注入代码可能调用 *_Mask1 / *_Mask2 但其 wrapper 未在 pre_compute 中定义
mask_call_re = re.compile(r'\b(\w+_(?:Mask1|Mask2))\s*\(')
called_masks = set(mask_call_re.findall(all_code))
_script_dir = os.path.dirname(os.path.abspath(__file__))
wrappers_dir = os.path.join(_script_dir, 'wrappers')
for mask_name in sorted(called_masks):
def_pat = re.compile(r'\bvoid\s+' + re.escape(mask_name) + r'\s*\(')
if def_pat.search(pre_compute_text):
continue # already defined
wrapper_path = os.path.join(wrappers_dir, mask_name + '.cpp')
if os.path.isfile(wrapper_path):
with open(wrapper_path, 'r', encoding='utf-8') as fw:
wrapper_code = fw.read().strip()
pre_compute_text = pre_compute_text.rstrip('\n') + '\n\n' + wrapper_code + '\n'
log.info(f"INJECTING {mask_name} wrapper from {wrapper_path}")
return pre_compute_text
def main():
_script_dir = os.path.dirname(os.path.abspath(__file__))
path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(_script_dir, "program_out.cpp")
out_dir = sys.argv[2] if len(sys.argv) > 2 else None
base = sys.argv[3] if len(sys.argv) > 3 else None
json_path = sys.argv[5] if len(sys.argv) > 5 else None
a, b, c = split_cpp_file(path)
b = clean_conflicting_decls(b)
# Auto-inject vector wrappers for scalar APIs referenced in compute code
full_compute = a + b + c
a = inject_missing_wrappers(a, full_compute)
calls = find_all_calls(c, keywords=("MatMul",))
if not calls:
cr_pre, cr_post = c, ""
matmul_args = []
matmul_args_first3 = []
else:
# 根据 JSON 中 MatMul 节点顺序,为每次 MatMul 计算一个稳定的 slot,
# 从而避免 CrossCore flag 因代码出现顺序不同而错配。
json_matmul_id_to_slot = {}
if json_path:
try:
with open(normalize_path(json_path), "r", encoding="utf-8") as jf:
data = json.load(jf)
matmul_ids = []
for nd in data.get("nodes", []):
op = str(nd.get("op", "")).lower()
if op == "matmul":
if nd.get("id") is not None:
matmul_ids.append(int(nd.get("id")))
matmul_ids_sorted = sorted(set(matmul_ids))
json_matmul_id_to_slot = {nid: i for i, nid in enumerate(matmul_ids_sorted)}
except Exception:
pass
call_slots = []
for call_idx, call in enumerate(calls):
node_id = None
m = re.search(r"//\s*node\s*(\d+)", call.get("line", ""))
if m:
try:
node_id = int(m.group(1))
except Exception:
node_id = None
slot = call_idx
if node_id is not None and node_id in json_matmul_id_to_slot:
slot = json_matmul_id_to_slot[node_id]
call_slots.append(slot)
parts = []
last = 0
for call in calls:
parts.append(c[last:call["start_line"]])
last = (call["end_line"] + 1) if call["end_line"] < len(c) else len(c)
parts.append(c[last:])
matmul_args = [call["args_all"] for call in calls]
matmul_args_first3 = [call["args_first3"] for call in calls]
blocks_pre = []
blocks_post = []
indent_pre = " "
indent_post = " "
for idx, seg in enumerate(parts[:-1]):
seg_mod = seg
if idx < len(matmul_args_first3) and len(matmul_args_first3[idx]) >= 3:
x1 = matmul_args_first3[idx][1]
x2 = matmul_args_first3[idx][2]
slot = call_slots[idx] if idx < len(call_slots) else idx
dest = matmul_args_first3[idx][0]
seg_mod = seg_mod + ("" if seg_mod.endswith("\n") else "\n") + \
f"{indent_pre}AscendC::DataCopy(aGlobal, {x1}, tensor_len);\n" + \
f"{indent_pre}AscendC::DataCopy(bGlobal, {x2}, tensor_len);\n" + \
f"{indent_pre}AscendC::CrossCoreSetFlag<0x2, PIPE_MTE3>({1 + 2*slot + 1});\n" + \
f"{indent_pre}OutputGlobal.SetGlobalBuffer(reinterpret_cast<__gm__ float *>(c) + AscendC::GetBlockIdx() * tiling.M * tiling.N);\n" + \
f"{indent_pre}AscendC::CrossCoreWaitFlag({1 + 2*slot + 2});\n" + \
f"{indent_pre}AscendC::DataCopy({dest}, cGlobal, tensor_len);\n"
blocks_pre.append(seg_mod)
cr_pre = "".join(blocks_pre)
# 仅保留「最后一次 MatMul 调用之后」的尾部。
# 若用 "".join(parts[1:]),会把 p1、p2… 与 cr_pre 中已包含的 p1、p2… 再拼一次,
# 合并进 baremix 后会在同一 ASCEND_IS_AIV 作用域内出现 loop_iter_* / cond_threshold_* 重定义。
cr_post = parts[-1] if parts else ""
full_text = open(normalize_path(path), "r", encoding="utf-8").read()
last_out = find_max_output_var(full_text)
indent_pre = " "
indent_post = " "
if cr_pre.strip():
lp = cr_pre.splitlines()
if lp:
m0 = re.match(r"^(\s*)", lp[-1])
if m0:
indent_pre = m0.group(1) or indent_pre
if cr_post.strip():
lp2 = cr_post.splitlines()
if lp2:
m1 = re.match(r"^(\s*)", lp2[0])
if m1:
indent_post = m1.group(1) or indent_post
cr_pre_mod = clean_conflicting_decls(cr_pre)
cr_post_mod = clean_conflicting_decls(cr_post)
# Inject diagnostic printf at start of compute
diag_start = (
indent_pre + 'AscendC::printf("[START] Compute begin: tensor_len=%d active_len=%d '
'input1[0]=%f input2[0]=%d\\n", '
'tensor_len, active_len, input1.GetValue(0), input2Local.GetValue(0));\n'
)
cr_pre_mod = diag_start + cr_pre_mod
if last_out:
# Add diagnostic printf before final DataCopy
diag = (
indent_post + 'AscendC::printf("[RESULT] Compute done. Final output (' + last_out + '): '
'first=%f last=%f len=%d\\n", '
+ last_out + '.GetValue(0), ' + last_out + '.GetValue(tensor_len>1?tensor_len-1:0), tensor_len);\n'
)
cr_post_mod = cr_post_mod + ("" if cr_post_mod.endswith("\n") else "\n") + diag + \
f"{indent_post}AscendC::DataCopy(OutputGlobal, {last_out}, tensor_len);\n"
try:
_script_dir2 = os.path.dirname(os.path.abspath(__file__))
tmpl_path = sys.argv[4] if len(sys.argv) > 4 else os.path.join(_script_dir2, "baremix", "baremix_custom.cpp")
tmpl_path = normalize_path(tmpl_path)
with open(tmpl_path, "r", encoding="utf-8") as tf:
ttext = tf.read()
mapping = {
"// 在这里插入program_out_pre_compute部分": a,
"// 在这里插入program_out_compute_tensors部分": b,
"// 在这里插入program_out_compute_rest_pre部分": cr_pre_mod,
"// 在这里插入program_out_compute_rest_post部分": cr_post_mod,
}
def insert_blocks(text, mapping):
lines = text.splitlines(True)
out_lines = []
for ln in lines:
replaced = False
for key, val in mapping.items():
if key in ln:
out_lines.append(val if val.endswith("\n") else val + "\n")
replaced = True
break
if not replaced:
out_lines.append(ln)
return "".join(out_lines)
new_text = insert_blocks(ttext, mapping)
new_text = remove_duplicate_decls(new_text)
out_baremix_dir = os.path.dirname(tmpl_path)
out_baremix = os.path.join(out_baremix_dir, "baremix_custom_program_out.cpp")
with open(out_baremix, "w", encoding="utf-8") as of:
of.write(new_text)
except Exception as e:
pass
json.dumps({
"pre_compute": a,
"compute_tensors": b,
"compute_rest": c,
"compute_rest_pre": cr_pre_mod,
"compute_rest_post": cr_post_mod,
"matmul_args": matmul_args,
"matmul_args_first3": matmul_args_first3,
"last_output": last_out
}, ensure_ascii=False)
print("generate successfully!")
if __name__ == "__main__":
main()