convert.py 10.1 KB
Newer Older
sunzhq2's avatar
init  
sunzhq2 committed
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
import sys
import csv
import json
import pathlib
import argparse
import logging


CUR_DIR = pathlib.Path(__file__).parent.absolute()
PRJ_ROOT_DIR = CUR_DIR.parent

sys.path.insert(0, str(PRJ_ROOT_DIR))


unique_attrs = [
    "op_name",
    "sku_name",
    "owner",
    "perf_mode"
]


def get_unique_key(
    op_name, 
    sku_name, 
    owner, 
    perf_mode, 
    *args,
    **kwargs
):
    return ".".join([
        sku_name,
        owner,
        op_name,
        perf_mode
    ]).replace(" ", "_")



arguments_map = {
    # 单目算子
    # [batch, len] --> [batch, len]
    "sin": ["dtype", "batch", "len"], 
    "cos": ["dtype", "batch", "len"],
    "exp": ["dtype", "batch", "len"],
    "exponential": ["dtype", "batch", "len"], 
    "silu": ["dtype", "batch", "len"],
    "gelu": ["dtype", "batch", "len"],
    "swiglu": ["dtype", "batch", "len"],
    # float32: float32 --> float16/bfloat16
    # float16: float16 --> float32
    # bfloat16: bfloat16 --> float32
    "cast": ["dtype", "batch", "len"],


    # 双目算子
    # [batch, len] (op) [batch, len] --> [batch, len]
    "add": ["dtype", "batch", "len"], 
    "mul": ["dtype", "batch", "len"], 
    "sub": ["dtype", "batch", "len"], 
    "div": ["dtype", "batch", "len"], 


    # 规约算子
    # [batch, len] --> [batch, len]
    "layernorm": ["dtype", "batch", "len"], 
    "softmax": ["dtype", "batch", "len"],
    # [batch, len] --> [batch, 1]
    "reduce_sum": ["dtype", "batch", "len"],
    "reduce_min": ["dtype", "batch", "len"],
    "reduce_max": ["dtype", "batch", "len"],

    # 索引算子
    # [batch, len] (op) [batch] --> [batch, len]
    "index_add": ["dtype", "batch", "len"],
    # [batch, len] --> [batch, len]
    "sort": ["dtype", "batch", "len"], 
    "unique": ["dtype", "batch", "len"], 
    "gather": ["dtype", "batch", "len"],
    "scatter": ["dtype", "batch", "len"],


    # 矩阵算子
    # [M, K] * [K, N] --> [M, N]
    "gemm": ["dtype", "M", "N", "K"], 
    # [batch, M, K] * [batch, K, N] --> [batch, M, N]
    "batch_gemm": ["dtype", "batch", "M", "N", "K"],
    # # group * {[M, K] * [K, N] = [M, N]
    "group_gemm": ["dtype", "batch", "group", "M_str", "N", "K"], 


    # 通信算子    
    # [batch, len] --> [batch, len]
    # tp_size split over batch
    "broadcast": ["dtype", "tp_size", "batch", "len"], 
    "allreduce": ["dtype", "tp_size", "batch", "len"], 
    "allgather": ["dtype", "tp_size", "batch", "len"], 
    "alltoall": ["dtype", "tp_size", "batch", "len"], 
    "reducescatter": ["dtype", "tp_size", "batch", "len"], 
    "p2p": ["dtype", "tp_size", "batch", "len"], 

    "device2host": ["dtype", "batch", "len"],
    "host2device": ["dtype", "batch", "len"]
}


target_attrs = [
    # latency in us
    "latency"
]


def get_csv_headers(op_name):
    return unique_attrs + arguments_map.get(op_name, []) + target_attrs






logger = logging.getLogger("bytemlperf_aeolus")

def setup_logger(loglevel: str):
    fmt = logging.Formatter(
        fmt="%(asctime)s.%(msecs)03d %(filename)s:%(lineno)d [%(levelname)s]: %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )
    handler = logging.StreamHandler(stream=sys.stdout)
    handler.setFormatter(fmt)
    logger.addHandler(handler)
    logger.setLevel(loglevel.upper())
    logger.propagate = False


sku_name_mapping = {
    "MLU590-M9": "MLU590 M9",
    "MLU590-M9D": "MLU590 M9D",
    "MLU590-M9DK": "MLU590 M9D",
    "Iluvatar BI-V150": "BI-V150",
    "NVIDIA A800-SXM4-80GB": "A800 80GB SXM", 
    "NVIDIA H800": "H800 80GB SXM", 
    "NVIDIA H20": "H20 96GB SXM", 
    "Ascend910B2C": "Ascend910B2"
}

dtype_map = {
    "float": "float32", 
    "half": "float16", 
    "int": "int32"
}
















def normal_ops_func(op, sku_name, frame, perf_mode, json_data):
    if not json_data or "Error" in json_data:
        return
    dtype = json_data["Dtype"]
    if dtype in dtype_map:
        dtype = dtype_map[dtype]

    batch = json_data["Tensor Shapes"][0][0]
    len = json_data["Tensor Shapes"][0][1]
    latency = json_data["Avg latency(us)"]

    return [op, sku_name, frame, perf_mode, dtype, batch, len, latency]



def gemm_func(op, sku_name, frame, perf_mode, json_data):
    if not json_data or "Error" in json_data:
        return
    dtype = json_data["Dtype"]
    if dtype in dtype_map:
        dtype = dtype_map[dtype]

    M = json_data["Tensor Shapes"][0][0]
    K = json_data["Tensor Shapes"][0][1]
    N = json_data["Tensor Shapes"][1][1]
    latency = json_data["Avg latency(us)"]

    return [op, sku_name, frame, perf_mode, dtype, M, N, K, latency]


def batch_gemm_func(op, sku_name, frame, perf_mode, json_data):
    if not json_data or "Error" in json_data:
        return
    dtype = json_data["Dtype"]
    if dtype in dtype_map:
        dtype = dtype_map[dtype]

    batch_size = json_data["Tensor Shapes"][0][0]
    M = json_data["Tensor Shapes"][0][1]
    K = json_data["Tensor Shapes"][0][2]
    N = json_data["Tensor Shapes"][1][2]
    latency = json_data["Avg latency(us)"]

    return [op, sku_name, frame, perf_mode, dtype, batch_size, M, N, K, latency]

def group_gemm_func(op, sku_name, frame, perf_mode, json_data):
    if not json_data or "Error" in json_data:
        return
    dtype = json_data["Dtype"]
    if dtype in dtype_map:
        dtype = dtype_map[dtype]

    batch_size = json_data["Tensor Shapes"][0][0][0]
    group = len(json_data["Tensor Shapes"])

    M_list = [int(json_data["Tensor Shapes"][i][0][0]) // batch_size for i in range(group)]
    M_list_str = "/".join([str(m) for m in M_list])
    K = json_data["Tensor Shapes"][0][0][1]
    N = json_data["Tensor Shapes"][0][1][1]
    latency = json_data["Avg latency(us)"]

    return [op, sku_name, frame, perf_mode, dtype, batch_size, group, M_list_str,N, K, latency]



def ccl_ops_func(op, sku_name, frame, perf_mode, json_data):
    if not json_data or "Error" in json_data:
        return
    dtype = json_data["Dtype"]
    if dtype in dtype_map:
        dtype = dtype_map[dtype]

    tp_size = json_data["Group"]
    batch = json_data["Tensor Shapes"][0][0]
    len = json_data["Tensor Shapes"][0][1]
    latency = json_data["Avg latency(us)"]

    return [op, sku_name, frame, perf_mode, dtype, tp_size, batch, len, latency]

def d2h_h2d_func(op, sku_name, frame, perf_mode, json_data):
    if not json_data or "Error" in json_data:
        return
    dtype = json_data["Dtype"]
    if dtype in dtype_map:
        dtype = dtype_map[dtype]

    batch = json_data["Tensor Shapes"][0][0]
    len = json_data["Tensor Shapes"][0][1]
    latency = json_data["Avg latency(us)"]

    return [op, sku_name, frame, perf_mode, dtype, batch, len, latency]


post_func_map = {
    "sin": normal_ops_func,
    "cos": normal_ops_func,
    "exp": normal_ops_func,
    "exponential": normal_ops_func,
    "silu": normal_ops_func,
    "gelu": normal_ops_func,
    "swiglu": normal_ops_func,
    "cast": normal_ops_func,

    "add": normal_ops_func,
    "mul": normal_ops_func,
    "sub": normal_ops_func,
    "div": normal_ops_func,

    "layernorm": normal_ops_func,
    "softmax": normal_ops_func,
    "reduce_sum": normal_ops_func,
    "reduce_min": normal_ops_func,
    "reduce_max": normal_ops_func,

    "index_add": normal_ops_func,
    "sort": normal_ops_func,
    "unique": normal_ops_func,
    "gather": normal_ops_func,
    "scatter": normal_ops_func,

    "gemm": gemm_func,
    "batch_gemm": batch_gemm_func,
    "group_gemm": group_gemm_func,

    "broadcast": ccl_ops_func,
    "allreduce": ccl_ops_func,
    "allgather": ccl_ops_func,
    "alltoall": ccl_ops_func,
    "reducescatter": ccl_ops_func,
    "p2p": ccl_ops_func,

    "device2host": d2h_h2d_func,
    "host2device": d2h_h2d_func
}




def postprocess(op, file_list, dst_dir):
    json_data_list = [json.load(open(file)) for file in file_list]
    if not json_data_list:
        logger.error(f"no data found in {file_list}")
        return
    
    sku_name = json_data_list[0]["Device Info"]
    sku_name = sku_name_mapping.get(sku_name, sku_name)
    perf_datas = []
    for json_data in json_data_list:
        if "Performance" not in json_data:
            logger.error(f"no performance data")
            continue
        perf_data = json_data["Performance"]
        if not perf_datas:
            perf_datas = perf_data
        else:
            perf_datas.extend(perf_data)
    
    unique_name = get_unique_key(op, sku_name, "torch", "host")
    unique_csv_file = f"{unique_name}.csv"
    unique_csv_path = dst_dir / unique_csv_file
    
    with open(unique_csv_path, "w") as f:
        writer = csv.writer(f)
        writer.writerow(get_csv_headers(op))

        for perf_data in perf_datas:
            if op in post_func_map:
                row = post_func_map[op](op, sku_name, "torch", "host", perf_data)
                if row:
                  writer.writerow(row)



def convert_src(src, dst):
    logger.info(f"src: {src}")
    logger.info(f"dst: {dst}")

    op_data_map = {}
    for file in src.rglob("*.json"):
        dir_name = file.parent.name
        if dir_name == "gemv":
            dir_name = "gemm"
        if not dir_name in op_data_map:
            op_data_map[dir_name] = []
        op_data_map[dir_name].append(file)
    
    for op, files in op_data_map.items():
        logger.info(f"op: {op}")
        if op not in arguments_map and op != "gemv":
            logger.error(f"invalid op: {op}")
            continue
        postprocess(op, files, dst)



if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--src", type=str, required=True)

    parser.add_argument("--output_dir", type=str, default="./temp")
    parser.add_argument("--log_level", type=str, default="INFO")
    args = parser.parse_args()
    setup_logger(args.log_level)

    src_dir = pathlib.Path(args.src).absolute()
    if not src_dir.exists():
        logger.error(f"{args.src} does not exist")
        exit(1)
    elif not src_dir.is_dir():
        logger.error(f"{args.src} is not a directory")
        exit(1)

    output_dir = pathlib.Path(args.output_dir).absolute()
    if not output_dir.exists():
        output_dir.mkdir(parents=True, exist_ok=True)
    elif not output_dir.is_dir():
        logger.error(f"{args.output_dir} is not a directory")
        exit(1)

    convert_src(src_dir, output_dir)