Debian Codegraph @

tensilelite/Tensile/Utilities/tensile_generator/tensile_config_generator.py

raw symbols SCIP
1 ################################################################################
2 #
3 # Copyright (C) 2024-2025 Advanced Micro Devices, Inc. All rights reserved.
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 # copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 # SOFTWARE.
22 #
23 ################################################################################
24
25 import yaml
26 import re
27 import argparse
28 import json
29 import copy
30 import os
31 import subprocess
32 import math
33 import numpy as np
34 import concurrent.futures
35
36
37 # Paths to the input and output files
38 parser = argparse.ArgumentParser(description="""Generate Tensile config file""")
39
40 parser.add_argument(
41 "--hipblaslt_log",
42 type=str,
43 help="Path to hipblaslt log file")
44
45 parser.add_argument(
46 "--tensile_config", type=str,
47 help="Path to tensile config file")
48
49 parser.add_argument(
50 "--gpus", type=int, default=1,
51 help="Number of gpus for tuning hipblaslt")
52
53 parser.add_argument(
54 "--topk", type=int, default=None,
55 help="Top k gemms for tuning")
56
57 parser.add_argument(
58 "--iters", type=int, default=100,
59 help="Max tuning iterations")
60
61 parser.add_argument(
62 "--fast", type=bool, default=False,
63 help="If enabled, only tune the matrix instruction with min tile sizes, else, tune full matrix instructions")
64
65 parser.add_argument(
66 "--groups", type=bool, default=False,
67 help="If enabled, will replace MatrixInstruction with GroupedMatrixInstruction")
68
69 parser.add_argument(
70 "--gridbase_config", type=str, default=None,
71 help="Range config path")
72
73 parser.add_argument(
74 "--full_mfma", type=bool, default=False,
75 help="If enabled, will search for all mfma instructions")
76
77 parser.add_argument(
78 "--full_stage", type=bool, default=False,
79 help="If enabled, will search for all stages instructions")
80
81 parser.add_argument(
82 "--num_stages", type=int, default=8,
83 help="How many times to divide matrix")
84
85 args = parser.parse_args()
86
87 NUM_WARM_UP = 20
88 ENQUEUES_PER_SYNC = 20
89 LibraryType = "GridBased"
90
91 CU_RE = r"Compute Unit:(?P<COMPUTE_UNIT>[\w ]+)"
92
93 NUM_STAGES = args.num_stages
94 DIV_MI = 3 # 33.3%
95 MIN_MI = 5 # min 5 solutions
96 NONTEMPORALRATIO = 8
97 MAX_MT = int(os.environ.get("MAX_MT", 256))
98
99 OFFLOAD_ARCH = "/opt/rocm/llvm/bin/offload-arch"
100 NUM_INST = "/sys/class/drm/card1/device/compute_partition_config/xcc/num_inst"
101
102 ArchitectureName = os.environ.get("GPU_TARGET", None)
103 if ArchitectureName is None:
104 if os.path.exists(OFFLOAD_ARCH):
105 res = subprocess.run(OFFLOAD_ARCH, stdout=subprocess.PIPE)
106 ArchitectureName = res.stdout.decode("utf-8").strip()
107 else:
108 raise FileNotFoundError(f"{OFFLOAD_ARCH} not found, please specific GPU_TARGET environment variable.")
109
110 CU = os.environ.get("CU", None)
111 if CU is None:
112 res = subprocess.run("rocminfo | grep Compute", stdout=subprocess.PIPE, shell=True, env={"ROCR_VISIBLE_DEVICES":"0"})
113 match = re.search(CU_RE, res.stdout.decode("utf-8").split('\n')[-2])
114 if match:
115 CU = int(match.group('COMPUTE_UNIT').strip())
116 else:
117 raise RuntimeError("Failed to get compute unit from rocminfo, please specific CU environment variable.")
118 else:
119 CU = int(CU)
120
121 XCC = os.environ.get("XCC", None)
122 if ArchitectureName == 'gfx942':
123 if XCC is None:
124 if os.path.exists(NUM_INST):
125 res = subprocess.run(["cat", NUM_INST], stdout=subprocess.PIPE)
126 XCC = int(res.stdout.decode("utf-8").strip())
127 else:
128 raise FileNotFoundError(f"{NUM_INST} not found, please specific XCC environment variable.")
129 else:
130 XCC = int(XCC)
131 DeviceNames = ["Device 0049", "Device 0050"]
132 ScheduleName = "aquavanjaram"
133 elif ArchitectureName == 'gfx90a':
134 XCC = 1
135 DeviceNames = ["Device 0050", "Device 0051", "Device 0052", "Device 0054", "Device 0062", "Device 7400", "Device 740c"]
136 ScheduleName = "aldebaran"
137
138 if args.full_mfma:
139 fp16_instructions = [[32,32,4,2], [32,32,8,1], [16,16,4,4], [16,16,16,1], [4,4,4,16]]
140 bf16_instructions = [[32,32,4,2], [32,32,8,1], [16,16,4,4], [16,16,16,1], [4,4,4,16]]
141 tf32_instructions = [[32,32,2,2], [32,32,4,1], [16,16,2,4], [16,16,8,1], [4,4,2,16]]
142 fp32_instructions = [[32,32,1,2], [32,32,2,1], [16,16,1,4], [16,16,4,1], [4,4,1,16]]
143 fp8_instructions = [[32,32,16,1], [16,16,32,1]]
144 else:
145 fp16_instructions = [[16,16,16,1], [32,32,8,1]]
146 bf16_instructions = [[16,16,16,1], [32,32,8,1]]
147 tf32_instructions = [[16,16,8,1], [32,32,4,1]]
148 fp32_instructions = [[16,16,4,1], [32,32,2,1]]
149 fp8_instructions = [[16,16,32,1]]
150
151
152 HIPBLASLT_BENCH_BASE = (
153 r"hipblaslt-bench --api_method (?P<API_METHOD>\w+) "
154 r"-m (?P<M>[\d ]+)"
155 r"-n (?P<N>[\d ]+)"
156 r"-k (?P<K>[\d ]+)"
157 r"--lda (?P<LDA>[\d ]+)"
158 r"--ldb (?P<LDB>[\d ]+)"
159 r"--ldc (?P<LDC>[\d ]+)"
160 r"--ldd (?P<LDD>[\d ]+)"
161 r"--stride_a (?P<STRIDE_A>[\d ]+)"
162 r"--stride_b (?P<STRIDE_B>[\d ]+)"
163 r"--stride_c (?P<STRIDE_C>[\d ]+)"
164 r"--stride_d (?P<STRIDE_D>[\d ]+)"
165 r"--alpha (?P<ALPHA>[\d\. ]+)"
166 r"--beta (?P<BETA>[\d\. ]+)"
167 r"--transA (?P<TRANS_A>[\w ]+)"
168 r"--transB (?P<TRANS_B>[\w ]+)"
169 r"--batch_count (?P<BATCH_COUNT>[\d ]+)"
170 r"--scaleA (?P<SCALE_A>[\d ]+)"
171 r"--scaleB (?P<SCALE_B>[\d ]+)"
172 )
173
174 # Optional patterns for scale and bias
175 BIAS_PATTERN = r"--bias_vector --bias_source (?P<BIAS_SOURCE>[\w ]+)"
176
177 # Common ending pattern
178 TYPE_PATTERN = (
179 r"--a_type (?P<A_TYPE>[\w ]+)"
180 r"--b_type (?P<B_TYPE>[\w ]+)"
181 r"--c_type (?P<C_TYPE>[\w ]+)"
182 r"--d_type (?P<D_TYPE>[\w ]+)"
183 r"--scale_type (?P<SCALE_TYPE>[\w ]+)"
184 r"--bias_type (?P<BIAS_TYPE>[\w ]+)"
185 r"--compute_type (?P<COMPUTE_TYPE>[\w ]+)"
186 r"--algo_method (?P<ALGO_METHOD>[\w ]+)"
187 r"--solution_index (?P<SOLUTION_INDEX>[\d ]+)"
188 r"--activation_type (?P<ACTIVATION_TYPE>[\w ]+)"
189 )
190
191 # Build the combined pattern with optional parts
192 def build_pattern(has_bias=False):
193 pattern = HIPBLASLT_BENCH_BASE
194 if has_bias:
195 pattern += BIAS_PATTERN
196 pattern += TYPE_PATTERN
197 return pattern
198
199 # Create the four variations
200 HIPBLASLT_BENCH_RE = build_pattern()
201 HIPBLASLT_BENCH_RE_BIAS = build_pattern(has_bias=True)
202
203 FP8_DTYPES = ["F8","F8N","B8","B8N","F8B8N","B8F8N","F8B8","B8F8"]
204
205 def is_fp8(dtype):
206 return dtype in FP8_DTYPES
207
208 # Function to extract problem sizes from a line
209 def extract_problem_size(match):
210 return [int(match.group('M').strip()), int(match.group('N').strip()), int(match.group('BATCH_COUNT').strip()), int(match.group('K').strip())]
211
212 def instruction_map(dtype_dict):
213 if dtype_dict["DataType"] == 'S' and dtype_dict["F32XdlMathOp"] == 'x':
214 return tf32_instructions
215 elif dtype_dict["DataType"] == 'S' and dtype_dict["F32XdlMathOp"] == 0:
216 return fp32_instructions
217 elif dtype_dict["DataType"] == 'H':
218 return fp16_instructions
219 elif dtype_dict["DataType"] == 'B':
220 return bf16_instructions
221 elif is_fp8(dtype_dict["DataType"]):
222 return fp8_instructions
223 else:
224 return None
225
226 def datatype_map(dtype):
227 if dtype == "f16_r":
228 return "H"
229 elif dtype == "f32_r":
230 return "S"
231 elif dtype == "xf32_r":
232 return "XS"
233 elif dtype == "bf16_r":
234 return "B"
235 elif dtype == "f8_r":
236 return "F8"
237 elif dtype == "bf8_r":
238 return "B8"
239 else:
240 return None
241
242 def trans_map(trans):
243 if trans == "T":
244 return 1
245 elif trans == "N":
246 return 0
247 else:
248 return None
249
250 def bias_datatype_map(dtype):
251 if dtype == "f16_r":
252 return [datatype_map('f32_r'), datatype_map('f16_r')]
253 elif dtype == "f32_r":
254 return [datatype_map('f32_r')]
255 elif dtype == "xf32_r":
256 return [datatype_map('xf32_r')]
257 elif dtype == "bf16_r":
258 return [datatype_map('f32_r'), datatype_map('bf16_r')]
259 elif dtype == "f8_r":
260 return [datatype_map('f32_r'), datatype_map('f8_r')]
261 else:
262 return []
263
264 def get_high_precision_accumulate(DataType):
265 if DataType in ["H", "B"] + FP8_DTYPES:
266 return True
267 else:
268 return False
269
270 def adapt_xf32(ComputeDataType):
271 if ComputeDataType == "XS":
272 return 'S', 'x'
273 else:
274 return ComputeDataType, 0
275
276 def extract_dtype(match):
277 gdict = match.groupdict()
278 DataTypeA = datatype_map(gdict.get('A_TYPE', '').strip())
279 DataTypeB = datatype_map(gdict.get('B_TYPE', '').strip())
280
281 if is_fp8(DataTypeA) and is_fp8(DataTypeB):
282 if DataTypeA != DataTypeB:
283 DataType = DataTypeA + DataTypeB
284 else:
285 DataType = DataTypeA
286
287 if ArchitectureName == "gfx942":
288 # Nanno FP8
289 DataType += "N"
290 else:
291 DataType = DataTypeA
292
293 DestDataType = datatype_map(gdict.get('C_TYPE', '').strip())
294 ComputeDataType = datatype_map(gdict.get('COMPUTE_TYPE', '').strip())
295 TransposeA = trans_map(gdict.get('TRANS_A', '').strip())
296 TransposeB = trans_map(gdict.get('TRANS_B', '').strip())
297 if None in [DataType, DestDataType, ComputeDataType, TransposeA, TransposeB]:
298 return None
299 scaleA = gdict.get("SCALE_A").strip()
300 scaleB = gdict.get("SCALE_B").strip()
301 activation_type = gdict.get("ACTIVATION_TYPE").strip()
302 bias_source = gdict.get('BIAS_SOURCE', '').strip().upper()
303 HighPrecisionAccumulate = get_high_precision_accumulate(DataType)
304 ComputeDataType, F32XdlMathOp = adapt_xf32(ComputeDataType)
305 res = {"Batched": True, "DataType": DataType, "DestDataType": DestDataType, "ComputeDataType": ComputeDataType, "TransposeA": TransposeA, "TransposeB": TransposeB, "HighPrecisionAccumulate": HighPrecisionAccumulate, "F32XdlMathOp": F32XdlMathOp, "OperationType": "GEMM", "UseBeta": True}
306
307 if bias_source:
308 res["UseBias"] = 1
309 res["BiasSrc"] = bias_source
310 res["BiasDataTypeList"] = list(bias_datatype_map(gdict.get("BIAS_TYPE", '').strip()))
311 if activation_type != "none":
312 res["Activation"] = True
313 res["ActivationType"] = "hipblaslt_all"
314 if scaleA == "1" and scaleB == "1":
315 res["UseScaleAB"] = "Scalar"
316 res["UseScaleAlphaVec"] = 1
317 elif scaleA == "2" and scaleB == "2":
318 res["UseScaleAB"] = "Vector"
319 res["UseScaleAlphaVec"] = 1
320 return res
321
322 def find_matmul_instruction(mfma_instruction, size):
323 for bm in range(int(math.log(mfma_instruction[3],2))+1):
324 for m_tiles in reversed(range(1, CU+1)):
325 m_tile_size = size[0] // m_tiles
326 # TODO:fp8 384x384
327 if m_tile_size > MAX_MT:
328 continue
329 wave_tile_m = math.ceil(m_tile_size / mfma_instruction[0])
330 if wave_tile_m <= 0:
331 continue
332 for n_tiles in reversed(range(1, CU+1)):
333 n_tile_size = size[1] // n_tiles
334 if n_tile_size > MAX_MT:
335 continue
336 wave_tile_n = math.ceil(n_tile_size / mfma_instruction[1])
337 if wave_tile_n <= 0:
338 continue
339 matmul_instruction = mfma_instruction + [2**bm, 1, 1, 1, 1]
340 for k in reversed(range(3)):
341 if wave_tile_m // (2**k) >= 1 and wave_tile_m // (2**k) <= 32:
342 matmul_instruction[-4] = wave_tile_m // (2**k)
343 matmul_instruction[-2] = 2**k
344
345 for l in reversed(range(3)):
346 if wave_tile_n // (2**l) >= 1 and wave_tile_n // (2**l) <= 32:
347 matmul_instruction[-3] = wave_tile_n // (2**l)
348 matmul_instruction[-1] = 2**l
349 yield copy.deepcopy(matmul_instruction)
350
351 def get_groups(matmul_instruction_gen):
352 # Extract skinny MTs for Groups
353 mi_groups0 = []
354 mi_groups1 = []
355 mi_left = []
356 for mi in matmul_instruction_gen:
357 if mi is not None:
358 mt = [mi[0] * mi[5] * mi[7], mi[1] * mi[6] * mi[8]]
359 ratio = mt[0] / mt[1]
360 if ratio > NONTEMPORALRATIO:
361 mi_groups0.append(mi)
362 elif ratio < (1 / NONTEMPORALRATIO):
363 mi_groups1.append(mi)
364 else:
365 mi_left.append(mi)
366 return mi_groups0, mi_groups1, mi_left
367
368 def match_pattern(line):
369 if line.startswith("hipblaslt-bench"):
370 if 'bias_vector' in line:
371 match = re.search(
372 HIPBLASLT_BENCH_RE_BIAS, line
373 )
374 else:
375 match = re.search(
376 HIPBLASLT_BENCH_RE, line
377 )
378 if match is None:
379 print("WARNING: can't find match for", line)
380 return match
381 else:
382 return None
383
384 def extract_range(data):
385 shapes = []
386 if 'Exact' in data:
387 shapes += [int(shape) for shape in data['Exact'].split(',')]
388 if 'Range' in data:
389 shape_range = data['Range'].split(':')
390 points = data['Points']
391 shapes += list(set(np.round(np.linspace(int(shape_range[0]), int(shape_range[1]), int(points))).astype(int).tolist()))
392 return shapes
393
394 def split_gemms_by_gpus(unique_gemms, gpus):
395 unique_gemms_subgroups = [None] * gpus
396 for i, (k, v) in enumerate(unique_gemms.items()):
397 if unique_gemms_subgroups[i%gpus] is not None:
398 unique_gemms_subgroups[i%gpus].append((k, v))
399 else:
400 unique_gemms_subgroups[i%gpus] = [(k, v)]
401 return unique_gemms_subgroups
402
403 def calculate_min_flops(m_sum, n_sum, batch_sum, k_sum, samples_num, iters):
404 m_avg = m_sum / samples_num
405 n_avg = n_sum / samples_num
406 batch_avg = batch_sum / samples_num
407 k_avg = k_sum / samples_num
408
409 return (ENQUEUES_PER_SYNC + iters) * m_avg * n_avg * batch_avg * k_avg / 2
410
411 def calculate_gsu(matmul_instruction, size):
412 mt0 = matmul_instruction[0] * matmul_instruction[5] * matmul_instruction[7]
413 mt1 = matmul_instruction[1] * matmul_instruction[6] * matmul_instruction[8]
414 return max(1, CU // (math.ceil(size[0] / mt0) * math.ceil(size[1] / mt1)))
415
416 def dump_yaml(gpu_idx, gemm_group, yaml_file, m_sum, n_sum, batch_sum, k_sum, samples_num, iters, groups, gsu_group, matmul_instructions):
417 MinFlopsPerSync = calculate_min_flops(m_sum, n_sum, batch_sum, k_sum, samples_num, iters)
418 # Read the YAML file
419 with open(yaml_file, 'r') as f:
420 data = yaml.safe_load(f)
421
422 data["GlobalParameters"]["EnqueuesPerSync"] = ENQUEUES_PER_SYNC
423 data["GlobalParameters"]["MaxEnqueuesPerSync"] = iters
424 data["GlobalParameters"]["NumWarmups"] = NUM_WARM_UP
425 data["GlobalParameters"]["MinFlopsPerSync"] = round(MinFlopsPerSync)
426
427 # Update the ProblemSizes
428 for i, dtype_str in enumerate(gemm_group):
429 dtype = json.loads(dtype_str)
430
431 if i >= len(data["BenchmarkProblems"]):
432 data["BenchmarkProblems"].append(copy.deepcopy(data["BenchmarkProblems"][0]))
433 data["BenchmarkProblems"][i][1]["BenchmarkFinalParameters"][0]["ProblemSizes"] = gemm_group[dtype_str]
434 if "BiasDataTypeList" in dtype:
435 data["BenchmarkProblems"][i][1]["BenchmarkFinalParameters"].append({"BiasTypeArgs": list(dtype["BiasDataTypeList"])})
436
437 # Add groupd here if needed
438 group_params = [[]]
439
440 if groups:
441 if dtype_str in groups:
442 # Add Non Temporal
443 groups[dtype_str][0]["NonTemporalB"] = [0, 4, 7]
444 groups[dtype_str][1]["NonTemporalA"] = [0, 4, 7]
445 for v in groups[dtype_str][0]["MatrixInstruction"].values():
446 for ntemp in groups[dtype_str][0]["NonTemporalB"]:
447 g = dict()
448 g["MatrixInstruction"] = list(v)
449 g["NonTemporalB"] = ntemp
450 group_params[0].append(g)
451 for v in groups[dtype_str][1]["MatrixInstruction"].values():
452 for ntemp in groups[dtype_str][1]["NonTemporalA"]:
453 g = dict()
454 g["MatrixInstruction"] = list(v)
455 g["NonTemporalA"] = ntemp
456 group_params[0].append(g)
457 for v in matmul_instructions.get(dtype_str, dict()).values():
458 g = dict()
459 g["MatrixInstruction"] = list(v)
460 group_params[0].append(g)
461 for index, item in enumerate(data["BenchmarkProblems"][i][1]["ForkParameters"]):
462 if "MatrixInstruction" in item:
463 del item["MatrixInstruction"]
464 item["Groups"] = {}
465 else:
466 for index, item in enumerate(data["BenchmarkProblems"][i][1]["ForkParameters"]):
467 if "Groups" in item:
468 del item["Groups"]
469 item["MatrixInstruction"] = {}
470
471 for item in data["BenchmarkProblems"][i][1]["ForkParameters"]:
472 if ("Groups" in item) and group_params[0]:
473 item["Groups"] = group_params
474 elif "MatrixInstruction" in item:
475 item["MatrixInstruction"] = [list(v) for v in matmul_instructions[dtype_str].values()]
476 if "WorkGroupMappingXCCGroup" in item:
477 item["WorkGroupMappingXCCGroup"] = [CU]
478 if "WorkGroupMappingXCC" in item:
479 item["WorkGroupMappingXCC"] = [XCC]
480 if "GlobalSplitU" in item:
481 item["GlobalSplitU"] = list(gsu_group[dtype_str])
482 data["BenchmarkProblems"][i][0] = dtype
483 data["LibraryLogic"]["DeviceNames"] = DeviceNames
484 data["LibraryLogic"]["ScheduleName"] = ScheduleName
485 data["LibraryLogic"]["ArchitectureName"] = {"Architecture": ArchitectureName, "CUCount": CU}
486 data["LibraryLogic"]["LibraryType"] = LibraryType
487 # Write the updated YAML file
488 yaml_file = os.path.basename(yaml_file)
489 slices = yaml_file.split('.')
490 fname = slices[0]+'.'+str(gpu_idx)+'.'+slices[1]
491 with open(fname, 'w') as f:
492 yaml.dump(data, f, default_flow_style=None)
493 print(f"Dumped yaml to {fname}")
494
495
496 if args.hipblaslt_log and args.gridbase_config is None:
497 LibraryType = "Equality"
498 unique_gemms = {}
499 # Read problem sizes from the input file
500 with open(args.hipblaslt_log, 'r') as f:
501 lines = f.readlines()
502 def _extract_gemms(line):
503 match = match_pattern(line)
504 if match:
505 size = extract_problem_size(match)
506 dtype = extract_dtype(match)
507 if dtype is None:
508 print(f"WARNING: Can't find dtype for {line}, please contact hipblaslt expert")
509 return None
510 size_str = json.dumps(size)
511 dtype_str = json.dumps(dtype)
512 return (size_str, dtype_str)
513 return None
514
515 with concurrent.futures.ProcessPoolExecutor(8) as executor:
516 results = executor.map(_extract_gemms, list(lines))
517 for res in results:
518 if res is not None:
519 (size_str, dtype_str) = res
520 if (size_str, dtype_str) in unique_gemms:
521 unique_gemms[(size_str, dtype_str)] += 1
522 else:
523 unique_gemms[(size_str, dtype_str)] = 1
524
525 unique_gemms = {k: v for k, v in sorted(unique_gemms.items(), key=lambda item: item[1], reverse=True)[:args.topk]}
526 for k, v in unique_gemms.items():
527 print("Gemm config:", k, "Number:", v)
528
529 unique_gemms_subgroups = split_gemms_by_gpus(unique_gemms, args.gpus)
530
531 def _process_gemms(item):
532 gpu_idx, unique_gemms_subgroup = item
533 gemm_group = {}
534 gsu_group = {}
535 matmul_instructions = {}
536 groups = {}
537 if unique_gemms_subgroup is None:
538 return None
539
540 m_sum = 0
541 n_sum = 0
542 batch_sum = 0
543 k_sum = 0
544 for k, v in unique_gemms_subgroup:
545 size_str, dtype_str = k
546 original_size = json.loads(size_str)
547 dtype = json.loads(dtype_str)
548 mfma_instructions = instruction_map(dtype)
549
550 if mfma_instructions is None:
551 continue
552
553 if dtype_str not in gsu_group:
554 gsu_group[dtype_str] = set()
555
556 matmul_instruction_found = False
557 for mfma_instruction in mfma_instructions:
558 size = copy.deepcopy(original_size)
559 for _ in range(NUM_STAGES):
560 matmul_instruction_gen = list(find_matmul_instruction(mfma_instruction, size))
561 if args.groups:
562 mi_groups0, mi_groups1, matmul_instruction_gen = get_groups(matmul_instruction_gen)
563 else:
564 mi_groups0 = []
565 mi_groups1 = []
566
567 total_inst = min(len(matmul_instruction_gen) // DIV_MI, MIN_MI) # At least 5 insts and max of 33.3% of insts.
568 for index, matmul_instruction in enumerate(matmul_instruction_gen):
569 if matmul_instruction is not None:
570 gsu_group[dtype_str].add(calculate_gsu(matmul_instruction, size))
571 if dtype_str not in matmul_instructions:
572 matmul_instructions[dtype_str] = dict()
573 matmul_instructions[dtype_str][str(matmul_instruction)] = matmul_instruction
574 if args.fast and (index > total_inst):
575 break
576 total_inst = min(len(mi_groups0) // DIV_MI, MIN_MI)
577 for index, mi_0 in enumerate(mi_groups0):
578 if mi_0 is not None:
579 gsu_group[dtype_str].add(calculate_gsu(mi_0, size))
580 if dtype_str not in groups:
581 groups[dtype_str] = [{},{}]
582 groups[dtype_str][0]["MatrixInstruction"] = {}
583 groups[dtype_str][1]["MatrixInstruction"] = {}
584 groups[dtype_str][0]["MatrixInstruction"][str(mi_0)] = mi_0
585 if args.fast and (index > total_inst):
586 break
587 total_inst = min(len(mi_groups1) // DIV_MI, MIN_MI)
588 for index, mi_1 in enumerate(mi_groups1):
589 if mi_1 is not None:
590 gsu_group[dtype_str].add(calculate_gsu(mi_1, size))
591 if dtype_str not in groups:
592 groups[dtype_str] = [{},{}]
593 groups[dtype_str][0]["MatrixInstruction"] = {}
594 groups[dtype_str][1]["MatrixInstruction"] = {}
595 groups[dtype_str][1]["MatrixInstruction"][str(mi_1)] = mi_1
596 if args.fast and (index > total_inst):
597 break
598 if len(matmul_instruction_gen) > 0 or len(mi_groups0) > 0 or len(mi_groups1) > 0:
599 matmul_instruction_found = True
600 if not args.full_stage:
601 break
602
603 max_dim = int(np.argmax(size[:2]))
604 size[max_dim] = size[max_dim] // 2
605
606 if not matmul_instruction_found:
607 print(f"WARNING: Can't find mfma instructions for {original_size}, please contact hipblaslt expert")
608 else:
609 if dtype_str in gemm_group:
610 gemm_group[dtype_str].append({'Exact': list(original_size)})
611 else:
612 gemm_group[dtype_str] = [{'Exact': list(original_size)}]
613 m_sum += original_size[0]
614 n_sum += original_size[1]
615 batch_sum += original_size[2]
616 k_sum += original_size[3]
617 samples_num = len(unique_gemms_subgroup)
618 return dump_yaml(gpu_idx, gemm_group, args.tensile_config, m_sum, n_sum, batch_sum, k_sum, samples_num, args.iters, groups, gsu_group, matmul_instructions)
619
620
621 elif args.gridbase_config and args.hipblaslt_log is None:
622 LibraryType = "GridBased"
623 unique_gemms = {}
624 gpus = args.gpus
625
626 with open(args.gridbase_config, 'r') as f:
627 datas = yaml.safe_load(f)
628 for data in datas:
629 m_shapes = extract_range(data['M'])
630 n_shapes = extract_range(data['N'])
631 batch_shapes = extract_range(data['Batch'])
632 k_shapes = extract_range(data['K'])
633 DataType = datatype_map(data['DataType'].strip())
634 DestDataType = datatype_map(data['DestDataType'].strip())
635 ComputeDataType = datatype_map(data['ComputeDataType'].strip())
636 TransposeA = trans_map(data['TransposeA'])
637 TransposeB = trans_map(data['TransposeB'])
638 HighPrecisionAccumulate = get_high_precision_accumulate(DataType)
639 ComputeDataType, F32XdlMathOp = adapt_xf32(ComputeDataType)
640 dtype = {"Batched": True, "DataType": DataType, "DestDataType": DestDataType, "ComputeDataType": ComputeDataType, "TransposeA": TransposeA, "TransposeB": TransposeB, "HighPrecisionAccumulate": HighPrecisionAccumulate, "F32XdlMathOp": F32XdlMathOp, "OperationType": "GEMM", "UseBeta": True, "UseBias": 1, "Activation": True, "ActivationType": "hipblaslt_all", "UseScaleAlphaVec": 1}
641 dtype_str = json.dumps(dtype)
642 for m in m_shapes:
643 for n in n_shapes:
644 for batch in batch_shapes:
645 for k in k_shapes:
646 unique_gemms[(dtype_str,m,n,batch,k)] = [m,n,batch,k]
647
648 unique_gemms_subgroups = split_gemms_by_gpus(unique_gemms, args.gpus)
649
650 def _process_gemms(item):
651 gpu_idx, unique_gemms_subgroup = item
652 gemm_group = {}
653 matmul_instructions = {}
654 gsu_group = {}
655 m_sum = 0
656 n_sum = 0
657 batch_sum = 0
658 k_sum = 0
659 for k, size in unique_gemms_subgroup:
660 original_size = list(size)
661 dtype_str = k[0]
662 dtype = json.loads(dtype_str)
663 mfma_instructions = instruction_map(dtype)
664 if mfma_instructions is None:
665 continue
666
667 if dtype_str not in gsu_group:
668 gsu_group[dtype_str] = set()
669 matmul_instruction_found = False
670 for mfma_instruction in mfma_instructions:
671 size = copy.deepcopy(original_size)
672 for _ in range(NUM_STAGES):
673 matmul_instruction_gen = list(find_matmul_instruction(mfma_instruction, size))
674 total_inst = min(len(matmul_instruction_gen) // 3, 5) # At least 5 insts and max of 33.3% of insts.
675 for index, matmul_instruction in enumerate(matmul_instruction_gen):
676 if matmul_instruction is not None:
677 gsu_group[dtype_str].add(calculate_gsu(matmul_instruction, size))
678 if dtype_str not in matmul_instructions:
679 matmul_instructions[dtype_str] = dict()
680 matmul_instructions[dtype_str][str(matmul_instruction)] = matmul_instruction
681 if args.fast and (index > total_inst):
682 break
683
684 if len(matmul_instruction_gen) > 0:
685 matmul_instruction_found = True
686 if not args.full_stage:
687 break
688
689 max_dim = int(np.argmax(size))
690 size[max_dim] = size[max_dim] // 2
691
692 if not matmul_instruction_found:
693 print(f"WARNING: Can't find mfma instructions for {original_size}, please contact hipblaslt expert")
694 else:
695 if dtype_str in gemm_group:
696 gemm_group[dtype_str].append({'Exact': list(original_size)})
697 else:
698 gemm_group[dtype_str] = [{'Exact': list(original_size)}]
699
700 m_sum += original_size[0]
701 n_sum += original_size[1]
702 batch_sum += original_size[2]
703 k_sum += original_size[3]
704 samples_num = len(unique_gemms_subgroup)
705 return dump_yaml(gpu_idx, gemm_group, args.tensile_config, m_sum, n_sum, batch_sum, k_sum, samples_num, args.iters, {}, gsu_group, matmul_instructions)
706
707 with concurrent.futures.ProcessPoolExecutor(args.gpus) as executor:
708 results = executor.map(_process_gemms, list(enumerate(unique_gemms_subgroups)))
709 for result in results:
710 if result is not None:
711 print(result)