-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathbenchmark_utils.py
More file actions
1264 lines (1082 loc) · 46.1 KB
/
benchmark_utils.py
File metadata and controls
1264 lines (1082 loc) · 46.1 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
"""Utility functions for microbenchmarking."""
import datetime
import os
from typing import Any, Dict, Tuple, Callable
import glob
import yaml
import jax
import jax.numpy as jnp
import jsonlines
import numpy as np
import random
import string
import pathlib
import gzip
import json
import re
from collections import defaultdict
import subprocess
import shutil
from common import MARKER
from enum import Enum, auto
from jax.sharding import Mesh
from jax.sharding import NamedSharding
from jax.sharding import PartitionSpec as P
import gc
import jax.extend
from tensorflow.tsl.profiler.protobuf import xplane_pb2
# The dictionary to map a JAX (collective) function to its main HLO.
TARGET_TASK_NAME_COLLECTIVES_MAP = {
"all_to_all_ici_op": r"all-to-all.[0-9]+",
"all_gather_ici_op": r"all-gather.[0-9]+",
"psum_ici_op": r"all-reduce.[0-9]+",
"ppermute_ici_op": r"collective-permute.[0-9]+",
"single_device_hbm_copy": r"copy.[0-9]+",
}
class ShardingStrategy(Enum):
"""Defines different sharding strategies for tensors."""
NO_SHARDING = auto()
SHARDING_ON_ALL_DEVICES_WITH_M = auto()
SHARDING_ON_SINGLE_CHIP_WITH_M = (
auto()
) # Only sharding on the two core of one single chip
SHARDING_ON_ALL_DEVICES_WITH_N = auto()
SHARDING_ON_SINGLE_CHIP_WITH_N = auto()
def multiple_iteration_timeit_from_trace_throttling(
compute_func: Callable,
data_generator: Callable,
matrix_dim: str = None,
tries: int = 17,
task: str = None,
trace_dir: str = None,
gap_strategy: str = None,
) -> list[float]:
"""Time a function with jax.profiler and get the run time from the trace."""
LOCAL_TRACE_DIR = "/tmp/microbenchmarks_tmptrace"
if matrix_dim is not None:
trace_name = f"{task}_dim_{matrix_dim}"
else:
trace_name = f"t_{task}_" + "".join(
random.choices(string.ascii_uppercase + string.digits, k=10)
)
trace_full_dir = f"{trace_dir}/{trace_name}"
tmp_trace_dir = trace_full_dir
# If the trace_dir isn't a local path, create one for dumping the trace for parsing and getting metrics.
if trace_dir and not is_local_directory_path(trace_dir):
tmp_trace_dir = f"{LOCAL_TRACE_DIR}/{trace_name}"
if gap_strategy == "data_gen_once_block_every_iter":
data_args = data_generator()
with jax.profiler.trace(tmp_trace_dir):
for i in range(tries):
if i % 10 == 0:
print(
f"[{task}] Running iteration {i} of {tries} with {matrix_dim}..."
)
jax.devices()
with jax.profiler.StepTraceAnnotation(task, step_num=i):
with jax.named_scope(f"{MARKER}_{i}"):
result = compute_func(*data_args)
jax.block_until_ready(result)
elif gap_strategy=='data_gen_once_noblock':
data_args = data_generator()
with jax.profiler.trace(tmp_trace_dir):
results = []
for i in range(tries):
if i % 10 == 0:
print(f"[{task}] Running iteration {i} of {tries} with {matrix_dim}...")
jax.devices()
with jax.profiler.StepTraceAnnotation(task, step_num=i):
with jax.named_scope(f"{MARKER}_{i}"):
compute_func(*data_args)
results.append(True)
if results:
jax.block_until_ready(results)
elif gap_strategy == "data_gen_every_iter_block_every_iter":
with jax.profiler.trace(tmp_trace_dir):
for i in range(tries):
if i % 10 == 0:
print(f"[{task}] Running iteration {i} of {tries} with {matrix_dim}...")
data_args = data_generator()
jax.devices()
with jax.profiler.StepTraceAnnotation(task, step_num=i):
with jax.named_scope(f"{MARKER}_{i}"):
result = compute_func(*data_args)
jax.block_until_ready(result)
else:
raise ValueError(f"Unknown gap strategy: {gap_strategy}")
trace = get_trace(tmp_trace_dir)
if trace_full_dir != tmp_trace_dir:
# Upload the traces to desired location
upload_to_storage(trace_dir=trace_full_dir, local_file=tmp_trace_dir)
return multiple_iteration_get_metrics_from_trace(trace)
def clear_jax_memory():
backend = jax.extend.backend.get_backend()
for buf in backend.live_buffers():
buf.delete()
gc.collect()
def multiple_iteration_timeit_from_trace(
compute_func: Callable,
data_generator: Callable,
matrix_dim: str = None,
tries: int = 17,
task: str = None,
trace_dir: str = None,
) -> list[float]:
"""
Time a function with jax.profiler and get the run time from the trace.
"""
LOCAL_TRACE_DIR = "/tmp/microbenchmarks_tmptrace"
if matrix_dim is not None:
trace_name = f"{task}_dim_{matrix_dim}"
else:
trace_name = f"t_{task}_" + "".join(
random.choices(string.ascii_uppercase + string.digits, k=10)
)
trace_full_dir = f"{trace_dir}/{trace_name}"
tmp_trace_dir = trace_full_dir
# If the trace_dir isn't a local path, create one for dumping the trace for parsing and getting metrics.
if trace_dir and not is_local_directory_path(trace_dir):
tmp_trace_dir = f"{LOCAL_TRACE_DIR}/{trace_name}"
# data_args = data_generator()
with jax.profiler.trace(tmp_trace_dir):
for i in range(tries):
if i % 10 == 0:
print(f"[{task}] Running iteration {i} of {tries} with {matrix_dim}...")
data_args = data_generator()
jax.devices()
with jax.profiler.StepTraceAnnotation(task, step_num=i):
with jax.named_scope(f"{MARKER}_{i}"):
result = compute_func(*data_args)
jax.block_until_ready(result)
# Commenting it out as it's causing issues with GEMM
# clear_jax_memory()
trace = get_trace(tmp_trace_dir)
if trace_full_dir != tmp_trace_dir:
# Upload the traces to desired location
upload_to_storage(trace_dir=trace_full_dir, local_file=tmp_trace_dir)
return multiple_iteration_get_metrics_from_trace(trace, task)
def multiple_iteration_get_metrics_from_trace(trace: dict[str, Any], task: str = None) -> list[float]:
marker_done_events = []
for event in trace["traceEvents"]:
args = event.get("args", {})
tf_op = args.get("tf_op", "")
if MARKER in tf_op:
marker_done_events.append(event)
# when offloaded to sparse core look for call-done events
marker_call_done_events = [
e for e in marker_done_events if e.get("name", "").endswith("call-done")
]
if marker_call_done_events:
marker_done_events = marker_call_done_events
unique_pids = set([e["pid"] for e in marker_done_events])
print(f"Unique PIDs: {unique_pids}")
if not marker_done_events:
event_matcher = re.compile(task)
if "traceEvents" not in trace:
raise KeyError("Key 'traceEvents' not found in trace.")
events = []
for e in trace["traceEvents"]:
if "name" in e and event_matcher.match(e["name"]):
events.append(e)
# For each trace, find the TPU with smallest `pid` value and consider it to be TPU-0
min_pid = min([e["pid"] for e in events])
events_from_min_pid = [e for e in events if e["pid"] == min_pid]
print(events_from_min_pid)
durations_ms = []
for e in events_from_min_pid:
if e.get("args", {}).get("device_duration_ps"):
durations_ms.append(float(e["args"]["device_duration_ps"]) / 1e9)
elif "dur" in e:
durations_ms.append(float(e["dur"]) / 1e3)
if not durations_ms and events_from_min_pid:
print("Warning: No event duration found in legacy_get_metrics_from_trace_tpu.")
return durations_ms
min_pid = min([e["pid"] for e in marker_done_events])
events_from_min_pid = [e for e in marker_done_events if e["pid"] == min_pid]
durations_ms = [
float(e["args"]["device_duration_ps"]) / 1e9 for e in events_from_min_pid
]
print(f"Collected {len(durations_ms)} events from trace for pid {min_pid}.")
print(durations_ms)
return durations_ms
def iteration_timeit_from_trace(
compute_func: Callable,
data_generator: Callable,
matrix_dim: str=None,
tries: int=10,
task: str = None,
trace_dir: str = None,
event_name_str_list: list[str] = None) -> list[float]:
"""
Time a function with jax.profiler and get the run time from the trace.
"""
LOCAL_TRACE_DIR = "/tmp/microbenchmarks_tmptrace"
if matrix_dim is not None:
trace_name = f"{task}_dim_{matrix_dim}"
else:
trace_name = f"t_{task}_" + "".join(
random.choices(string.ascii_uppercase + string.digits, k=10)
)
trace_full_dir = f"{trace_dir}/{trace_name}"
tmp_trace_dir = trace_full_dir
# If the trace_dir isn't a local path, create one for dumping the trace for parsing and getting metrics.
if trace_dir and not is_local_directory_path(trace_dir):
tmp_trace_dir = f"{LOCAL_TRACE_DIR}/{trace_name}"
with jax.profiler.trace(tmp_trace_dir):
for _ in range(tries):
data_args = data_generator()
jax.devices() # Force synchronization across devices
with jax.profiler.TraceAnnotation(task):
result = compute_func(*data_args)
jax.block_until_ready(result)
trace = get_trace(tmp_trace_dir)
if trace_full_dir != tmp_trace_dir:
# Upload the traces to desired location
upload_to_storage(trace_dir=trace_full_dir, local_file=tmp_trace_dir)
return iteration_get_metrics_from_trace(
trace=trace,
event_name_str_list=event_name_str_list)
def iteration_get_metrics_from_trace(
trace: dict[str, Any],
tf_op_str_list: list[str] = None,
event_name_str_list: list[str] = None,
) -> list[float]:
# 1. Handle default inputs
# If not provided, filter for MARKER in tf_op and no specific event names.
if tf_op_str_list is None:
tf_op_str_list = [MARKER]
if event_name_str_list is None:
event_name_str_list = []
# Rename the storage variable to reflect its contents
selected_events = []
# 2. Filtering logic
for event in trace["traceEvents"]:
# Events without 'args' or 'name' cannot be filtered, skip them.
args = event.get("args", {})
tf_op = args.get("tf_op", "")
event_name = event.get("name", "")
# Check if the event matches any of the provided filters
tf_op_matches = any(s in tf_op for s in tf_op_str_list)
event_name_matches = any(s in event_name for s in event_name_str_list)
if tf_op_matches or event_name_matches:
selected_events.append(event)
if not selected_events:
print("Collected 0 events with specified filters in the trace.")
return []
# 3. Group events by PID (device/core) and sum durations per PID
# Dictionary structure: pid -> list of events for that pid
events_by_pid = defaultdict(list)
for event in selected_events:
events_by_pid[event["pid"]].append(event)
# Calculate total duration for each unique device
durations_ms_list = []
for pid in sorted(events_by_pid.keys()):
events = events_by_pid[pid]
# Sum the device_duration_ps (picoseconds) for all events belonging to this PID
# CAVEAT: If multiple iterations of the op runs for benchmarking, then the next
# instruction will sum it for all the iterations which will not be the expected
# behavior. Find the metadata key which is different for different iteration on
# same PID. Eg: `group_id`.
total_duration_ps = sum(
float(e["args"].get("device_duration_ps", 0)) for e in events
)
# Convert picoseconds (ps) to milliseconds (ms)
total_duration_ms = total_duration_ps / 1e9
durations_ms_list.append(total_duration_ms)
# 4. Print summary and return
print(f"Collected event data for {len(events_by_pid)} unique devices/PIDs.")
for i, pid in enumerate(sorted(events_by_pid.keys())):
print(f"Device {i} (PID {pid}): {durations_ms_list[i]:.6f} ms")
# Return the list of summed durations, one for each device
return durations_ms_list
def iteration_get_event_metrics_from_trace(
trace: dict[str, Any],
event_name_str_list: list[str],
) -> list[float]:
# Rename the storage variable to reflect its contents
selected_events = []
# 1. Filtering logic
for event in trace["traceEvents"]:
# Events without 'args' or 'name' cannot be filtered, skip them.
args = event.get("args", {})
event_name = event.get("name", "")
# Check if the event matches any of the provided filters
event_name_matches = any(s in event_name for s in event_name_str_list)
if event_name_matches:
selected_events.append(event)
if not selected_events:
print("Collected 0 events with specified filters in the trace.")
return []
# 2. Group events by PID (device/core)
# Dictionary structure: pid -> list of events for that pid
events_by_pid = defaultdict(list)
for event in selected_events:
events_by_pid[event["pid"]].append(event)
# Calculate total duration for each unique device
durations_ms_lists = []
for pid in sorted(events_by_pid.keys()):
events = events_by_pid[pid]
# Collect the durarion_ms for each run
durations_ms_lists.append([
float(e["args"].get("device_duration_ps", 0)) / 1e9 for e in events
])
# 3. Print summary from the first device and return
print(f"Average Execution time: {np.mean(durations_ms_lists[0]):.6f} ms")
# Return the list of durations from the first device
return durations_ms_lists[0]
def iteration_timeit(
compute_func: Callable,
data_generator: Callable,
matrix_dim: str = None,
warmup_tries: int = 10,
tries: int = 10,
task: str = None,
trace_dir: str = None
) -> list[float]:
"""
Simple utility to time a function, ensuring no cache hits
by generating new data for each iteration.
Args:
compute_func: The jitted function to benchmark.
data_generator: A function that returns a tuple of device-placed args
for the compute_func.
warmup_tries: Number of warmup iterations.
tries: Number of timed measurement iterations.
task: Name of the task for logging.
"""
assert task is not None
print(f"[{task}] Running warmup loop with {warmup_tries} tries...")
result = None # To hold the last result for block_until_ready
for _ in range(warmup_tries):
# 1. Generate new data for each iteration
data_args = data_generator()
# 2. Run compute
result = compute_func(*data_args)
# 3. Block on the run
jax.block_until_ready(result)
print(f"[{task}] Warmup complete.")
arg_shapes = [arg.shape for arg in data_args]
arg_dtypes = [arg.dtype for arg in data_args]
if isinstance(result, list) or isinstance(result, tuple):
result_shapes = [r.shape for r in result]
result_dtypes = [r.dtype for r in result]
else:
result_shapes = result.shape
result_dtypes = result.dtype
print(f"[{task}] Verified global shapes: {arg_shapes} -> {result_shapes}")
print(f"[{task}] Verified global dtypes: {arg_dtypes} -> {result_dtypes}")
if trace_dir is not None:
if task == "rmsnorm":
# If the task is RMSNorm, we specifically target "copy-done" events.
# This is often done to capture the time of the asynchronous memory transfer
# needed for the normalization layer's input data.
event_name_str_list = ["copy-done"]
else:
# For all other tasks, use an empty list.
event_name_str_list = []
return iteration_timeit_from_trace(
compute_func,
data_generator,
matrix_dim=matrix_dim,
tries=tries,
task=task,
trace_dir=trace_dir,
event_name_str_list=event_name_str_list)
outcomes_ms = []
print(f"[{task}] Running measurement loop with {tries} tries...")
for i in range(tries):
# 1. Generate NEW random data (meets "no cache hit" rule)
data_args = data_generator()
jax.devices() # Force synchronization across devices
# Start timer just before the compute call
s_time = datetime.datetime.now()
# 2. Run the operation
result = compute_func(*data_args)
# 3. Block until operation is complete
jax.block_until_ready(result)
e_time = datetime.datetime.now()
outcomes_ms.append(1000 * (e_time - s_time).total_seconds())
return outcomes_ms
def simple_timeit(
f, *args, matrix_dim=None, tries=10, task=None, trace_dir=None
) -> float:
"""Simple utility to time a function for multiple runs."""
assert task is not None
if trace_dir:
return timeit_from_trace(
f, *args, matrix_dim=matrix_dim, tries=tries, task=task, trace_dir=trace_dir
)
outcomes_ms = []
jax.block_until_ready(f(*args)) # warm it up!
for _ in range(tries):
jax.devices() # Force synchronization across devices
s = datetime.datetime.now()
jax.block_until_ready(f(*args))
e = datetime.datetime.now()
outcomes_ms.append(1000 * (e - s).total_seconds())
return outcomes_ms
def get_trace(log_dir: str) -> dict[str, Any]:
"""Extract the trace object from the log directory.
Returns:
A trace object in JSON format.
"""
# Navigate to the folder with the latest trace dump to find `trace.json.jz`
trace_folders = (pathlib.Path(log_dir).absolute() / "plugins" / "profile").iterdir()
latest_trace_folder = max(trace_folders, key=os.path.getmtime)
trace_jsons = latest_trace_folder.glob("*.trace.json.gz")
try:
(trace_json,) = trace_jsons
except ValueError as value_error:
raise ValueError(
f"Invalid trace folder: {latest_trace_folder}"
) from value_error
with gzip.open(trace_json, "rb") as f:
trace = json.load(f)
return trace
def find_sparsecore_usage_from_xplane(log_dir: str) -> xplane_pb2.XSpace:
"""Extract the XSpace object from the log directory.
Returns:
An XSpace protobuf object.
"""
print("find_sparsecore_usage_from_xplane: ", log_dir)
# Handle partial log_dir
if not (pathlib.Path(log_dir) / "plugins" / "profile").exists():
potential_dirs = glob.glob(f"{log_dir}*")
potential_dirs = [d for d in potential_dirs if os.path.isdir(d)]
potential_dirs.sort(key=os.path.getmtime, reverse=True)
for d in potential_dirs:
d_path = pathlib.Path(d)
if (d_path / "plugins" / "profile").exists():
log_dir = d
print(f"Updated log_dir to match partial path: {log_dir}")
break
# Check subdirectories recursively
candidates = list(d_path.glob("**/plugins/profile"))
if candidates:
latest = max(candidates, key=lambda p: p.stat().st_mtime)
log_dir = str(latest.parent.parent)
print(f"Updated log_dir via recursive search: {log_dir}")
break
trace_folders = (
pathlib.Path(log_dir).absolute() / "plugins" / "profile"
).iterdir()
latest_trace_folder = max(trace_folders, key=os.path.getmtime)
# XPlane files usually end with .xplane.pb
xplane_files = list(latest_trace_folder.glob("*.xplane.pb"))
try:
(xplane_file,) = xplane_files
except ValueError as value_error:
raise ValueError(
f"Invalid trace folder: {latest_trace_folder}. Expected 1"
f" '*.xplane.pb' file, but found {len(xplane_files)}."
) from value_error
with open(xplane_file, "rb") as f:
serialized_space = f.read()
space = xplane_pb2.XSpace()
space.ParseFromString(serialized_space)
# print("space: ", space)
sparsecore_found = False
for _, plane in enumerate(space.planes):
print("plane: ", plane.name)
if "SparseCore" in plane.name:
sparsecore_found = True
break
return sparsecore_found
def get_metrics_from_trace(trace: dict[str, Any], task: str) -> list[float]:
# Check if the given task name is a collective with corresponding TPU opertion.
# This is a workaround and should be reverted or refactored in future.
if task in TARGET_TASK_NAME_COLLECTIVES_MAP:
try:
task = TARGET_TASK_NAME_COLLECTIVES_MAP[task]
return get_metrics_from_trace_tpu(trace, task)
except:
return [-1.0]
event_matcher = re.compile(task)
if "traceEvents" not in trace:
raise KeyError("Key 'traceEvents' not found in trace.")
events = []
for e in trace["traceEvents"]:
if "name" in e and event_matcher.match(e["name"]):
events.append(e)
events_by_run_id = defaultdict(list)
for e in events:
run_id = e["args"]["run_id"] if "args" in e and "run_id" in e["args"] else "0"
events_by_run_id[run_id].append(e)
durations_ms = []
try:
# Duration is in us.
durations_ms = [
max([e["dur"] for e in es]) / 1e3 for run_id, es in events_by_run_id.items()
]
except KeyError:
print("KeyError: Key 'dur' not found in the event object")
raise
return durations_ms
def get_metrics_from_trace_tpu(trace: dict[str, Any], task: str) -> list[float]:
event_matcher = re.compile(task)
if "traceEvents" not in trace:
raise KeyError("Key 'traceEvents' not found in trace.")
events = []
for e in trace["traceEvents"]:
if "name" in e and event_matcher.match(e["name"]):
events.append(e)
# For each trace, find the TPU with smallest `pid` value and consider it to be TPU-0
min_pid = min([e["pid"] for e in events])
events_from_min_pid = [e for e in events if e["pid"] == min_pid]
try:
durations_ms = [
float(e["args"]["device_duration_ps"]) / 1e9 for e in events_from_min_pid
]
except KeyError:
print("KeyError: Key 'device_duration_ps' not found in the event object")
raise
return durations_ms
def is_local_directory_path(dir: str) -> bool:
"""
Returns true if the path is a local path.
"""
if not dir: # Handle None or empty string
return False
# Heuristics for local paths
return dir.startswith("/") or dir.startswith("./") or dir.startswith("../")
def timeit_from_trace(
f, *args, matrix_dim=None, tries=10, task=None, trace_dir=None, event_name_str_list: list[str] = None
) -> float:
"""
Time a function with jax.profiler and get the run time from the trace.
"""
LOCAL_TRACE_DIR = "/tmp/microbenchmarks_tmptrace"
jax.block_until_ready(f(*args)) # warm it up!
if matrix_dim is not None:
trace_name = f"{task}_dim_{matrix_dim}"
else:
trace_name = f"t_{task}_" + "".join(
random.choices(string.ascii_uppercase + string.digits, k=10)
)
trace_full_dir = f"{trace_dir}/{trace_name}"
tmp_trace_dir = trace_full_dir
# If the trace_dir isn't a local path, create one for dumping the trace for parsing and getting metrics.
if trace_dir and not is_local_directory_path(trace_dir):
tmp_trace_dir = f"{LOCAL_TRACE_DIR}/{trace_name}"
print(trace_dir)
with jax.profiler.trace(tmp_trace_dir):
for _ in range(tries):
jax.devices() # Force synchronization across devices
with jax.profiler.TraceAnnotation(task):
jax.block_until_ready(f(*args))
trace = get_trace(tmp_trace_dir)
if trace_full_dir != tmp_trace_dir:
# Upload the traces to desired location
upload_to_storage(trace_dir=trace_full_dir, local_file=tmp_trace_dir)
if event_name_str_list is not None:
return iteration_get_event_metrics_from_trace(trace, event_name_str_list=event_name_str_list)
return iteration_get_metrics_from_trace(trace)
def maybe_write_metrics_file(
metrics_dir, metrics, metadata, test_name, test_start_time, test_end_time
):
"""Writes metrics to a JSONL file to be consumed by the XLML metrics pipeline."""
# Only write metrics from one host.
if jax.process_index() != 0:
return
jsonl_name = "metrics_report.jsonl"
jsonl_path = metrics_dir + "/" + jsonl_name
metadata.update(
{
"testsuite": "microbenchmark",
"test_name": f"{test_name}",
"test_start_timestamp": f"{test_start_time}",
"test_end_timestamp": f"{test_end_time}",
}
)
metrics_data = {
"metrics": metrics,
"dimensions": metadata,
}
# Make sure the metadata value is a string.
for key, value in metadata.items():
metadata[key] = str(value)
# Ensure the directory exists
os.makedirs(os.path.dirname(jsonl_path), exist_ok=True)
print(f"Writing metrics to JSONL file: {jsonl_path}")
with jsonlines.open(jsonl_path, mode="a") as writer:
writer.write(metrics_data)
def upload_to_storage(trace_dir: str, local_file: str):
"""
Uploads a local file to a specified storage location.
"""
if trace_dir.startswith("gs://"): # Google Cloud Storage (GCS)
try:
subprocess.run(
["gsutil", "cp", "-r", local_file, trace_dir],
check=True,
capture_output=True,
)
except subprocess.CalledProcessError as e:
print(
f"Failed to upload '{local_file}' to GCS: '{trace_dir}'. Error: {e.stderr.decode()}"
)
else:
raise KeyError(f"{trace_dir} is not a valid GCS path.")
def load_yaml_config(config_path: str) -> Dict[str, Any] | None:
"""Loads a YAML config file."""
try:
with open(config_path, "r") as f:
return yaml.safe_load(f)
except FileNotFoundError:
print(f"Warning: Config file not found at {config_path}")
return None
except yaml.YAMLError as e:
print(f"Error parsing YAML file {config_path}: {e}")
return None
class MetricsStatistics:
"""
Represents statistics for a list of metrics.
"""
def __init__(self, metrics_list, metrics_name: str):
self.metrics_list = metrics_list
self.metrics_name = metrics_name
self.statistics = self._calculate_statistics()
def _calculate_statistics(self) -> Dict[str, float]:
"""Calculates the statistics of the metrics list."""
if not self.metrics_list:
return {} # Return an empty dict if metrics_list is empty
return {
"p50": np.percentile(self.metrics_list, 50),
"p90": np.percentile(self.metrics_list, 90),
"p95": np.percentile(self.metrics_list, 95),
"p99": np.percentile(self.metrics_list, 99),
"avg": np.mean(self.metrics_list),
"max": np.max(self.metrics_list),
"num_runs": len(self.metrics_list),
"min": np.min(self.metrics_list),
# "all_values": json.dumps(self.metrics_list),
}
def __repr__(self):
return (
f"MetricsStatistics(metrics_name='{self.metrics_name}', "
f"statistics={self.statistics})"
)
def serialize_statistics(self):
serialized = {}
for stat_name, stat_value in self.statistics.items():
serialized[f"{self.metrics_name}_{stat_name}"] = stat_value
return serialized
def rename_xla_dump(
tmp_xla_dump_dir: str,
dest_xla_dump_dir: str,
benchmark_name: str,
benchmark_param: Dict[str, Any],
):
"""
Finds the latest XLA dump file matching '*jit_f*before_optimizations*.txt',
then identifies all other files that share the same 'jit_f.[unique_id]' identifier
and renames them to 'benchmark_name_serialized_params.original_suffix_with_extension'.
"""
serialized_benchmark_param = "_".join(
f"{key}_{value}" for key, value in benchmark_param.items()
)
anchor_pattern = os.path.join(tmp_xla_dump_dir, "*jit_f*before_optimizations*.txt")
matching_anchor_files = glob.glob(anchor_pattern)
if not matching_anchor_files:
print(
f"No files found for anchor pattern: '{anchor_pattern}'. No files will be renamed."
)
return
# Sort anchor files by modification time (latest first)
matching_anchor_files.sort(key=os.path.getmtime, reverse=True)
latest_anchor_file = matching_anchor_files[0]
# Example: 'module_0080.jit_f.cl_747713181.before_optimizations.txt'
# This will extract 'module_0080.jit_f.cl_747713181'
filename_base = os.path.basename(latest_anchor_file)
jit_id_match = re.search(r"(module.*jit_f\.[^.]+)", filename_base)
if not jit_id_match:
print(
f"Could not extract 'jit_f.[unique_id]' from '{filename_base}'. Cannot proceed with renaming."
)
return
common_jit_id_prefix = jit_id_match.group(1)
# Find all files in the directory that contain this specific common_jit_id_prefix
all_related_files_pattern = os.path.join(
tmp_xla_dump_dir, f"*{common_jit_id_prefix}*"
)
all_related_files = glob.glob(all_related_files_pattern)
if not all_related_files:
print(
f"No files found containing '{common_jit_id_prefix}'. This is unexpected if an anchor was found."
)
return
new_base_name = f"{benchmark_name}_{serialized_benchmark_param}"
after_optimizations_path = input_shape = output_shape = replica_groups = first_replica_group = None
for original_filepath in all_related_files:
original_filename = os.path.basename(original_filepath)
original_suffix_with_extension = ""
# Find the specific suffix part *after* the common_jit_id_prefix.
# This regex looks for the common_jit_id_prefix, then captures everything after it,
# ensuring it starts with a dot if there's more.
# Example: if original_filename is 'module_0080.jit_f.cl_747713181.after_codegen.txt'
# and common_jit_id_prefix is 'jit_f.cl_747713181'
# we want to capture '.after_codegen.txt'
suffix_match = re.search(
re.escape(common_jit_id_prefix) + r"(\..*)", original_filename
)
if suffix_match:
original_suffix_with_extension = suffix_match.group(
1
) # e.g., '.after_codegen.txt'
new_filename = f"{new_base_name}{original_suffix_with_extension}"
new_filepath = os.path.join(dest_xla_dump_dir, new_filename)
if "after_optimizations.txt" in original_suffix_with_extension:
after_optimizations_path = new_filepath
if original_filepath == new_filepath:
print(
f"Skipping: '{original_filename}' already has the desired name or path."
)
continue
# Copy the renamed files to desired location
if is_local_directory_path(dest_xla_dump_dir):
try:
os.makedirs(dest_xla_dump_dir, exist_ok=True)
shutil.copy(original_filepath, new_filepath)
except Exception as e:
print(
f"An unexpected error occurred while copy '{original_filepath}': {e}"
)
else:
upload_to_storage(trace_dir=new_filepath, local_file=original_filepath)
print(f"The XLA dump is stored in {dest_xla_dump_dir}")
if after_optimizations_path:
input_shape, output_shape, replica_groups, first_replica_group = (
extract_hlo_features_from_file(after_optimizations_path)
)
else:
print(
"No files found with 'after_optimizations.txt' suffix. "
"Please check the XLA dump directory."
)
return json.dumps({
"after_optimizations_path": after_optimizations_path,
"hlo_input_shape": input_shape,
"hlo_output_shape": output_shape,
"hlo_replica_groups": replica_groups,
"hlo_first_replica_group": first_replica_group,
})
def extract_hlo_features_from_file(hlo_file_path: str) -> Tuple[str | None, str | None, str | None, list[int] | None]:
"""
Extracts input shape, output shape, and replica groups from an HLO file.
Args:
hlo_file_path: Path to the HLO dump file (e.g., after_optimizations.txt).
Returns:
A tuple containing (input_shape, output_shape, replica_groups_str, first_replica_group),
or (None, None, None, None) if extraction fails.
"""
input_shape = None
output_shape = None
replica_groups_str = None
first_replica_group = None
try:
with open(hlo_file_path, "r") as f:
content = f.read()
except FileNotFoundError:
print(f"Error: HLO file not found at {hlo_file_path}")
return None, None, None, None
# Extract input/output shapes from HloModule line
# Example: HloModule jit_f, ..., entry_computation_layout={(f32[32,128]{...})->f32[128,128]{...}}
layout_match = re.search(r"entry_computation_layout={\((.*?)\)->(.*?)}", content)
if layout_match:
input_shape = layout_match.group(1)
output_shape = layout_match.group(2)
# Further clean shape if layout info is present, e.g., f32[1,2]{1,0} -> f32[1,2]
input_shape = re.sub(r"{.*}", "", input_shape)
output_shape = re.sub(r"{.*}", "", output_shape)
else:
print(f"Could not find entry_computation_layout in {hlo_file_path} to extract shapes.")
# Extract replica groups
# Example: replica_groups={{0,1},{2,3}}, dimensions...
rg_match = re.search(r"replica_groups=({{[0-9,]+(?:},{[0-9,]+)*}})", content, re.DOTALL)
if rg_match:
replica_groups_str = rg_match.group(1)
try:
content_rg = replica_groups_str[2:-2]
first_group_str = content_rg.split('},{')[0]
first_replica_group = [int(x) for x in first_group_str.split(',')]
except Exception as e:
print(f'Could not parse replica_groups in hlo_text: {e}')
first_replica_group = None
else:
print(f"Could not find replica_groups in {hlo_file_path}.")
return input_shape, output_shape, replica_groups_str, first_replica_group
def get_lhs_named_shading(mesh, strategy: ShardingStrategy):
match strategy:
case ShardingStrategy.NO_SHARDING:
return NamedSharding(mesh, P(None, None))
case ShardingStrategy.SHARDING_ON_ALL_DEVICES_WITH_M:
return NamedSharding(mesh, P("device", None))
case ShardingStrategy.SHARDING_ON_SINGLE_CHIP_WITH_M:
return NamedSharding(mesh, P("device", None))
case ShardingStrategy.SHARDING_ON_ALL_DEVICES_WITH_N:
return NamedSharding(mesh, P(None, None))
case ShardingStrategy.SHARDING_ON_SINGLE_CHIP_WITH_N:
return NamedSharding(mesh, P(None, None))
def get_rhs_named_shading(mesh, strategy: ShardingStrategy):
match strategy:
case ShardingStrategy.NO_SHARDING:
return NamedSharding(mesh, P(None, None))
case ShardingStrategy.SHARDING_ON_ALL_DEVICES_WITH_M:
return NamedSharding(mesh, P(None, None))
case ShardingStrategy.SHARDING_ON_SINGLE_CHIP_WITH_M:
return NamedSharding(mesh, P(None, None))
case ShardingStrategy.SHARDING_ON_ALL_DEVICES_WITH_N:
return NamedSharding(mesh, P(None, "device"))
case ShardingStrategy.SHARDING_ON_SINGLE_CHIP_WITH_N:
return NamedSharding(mesh, P(None, "device"))
def get_out_sharding(strategy: ShardingStrategy):
match strategy:
case ShardingStrategy.NO_SHARDING:
return P(None, None)
case ShardingStrategy.SHARDING_ON_ALL_DEVICES_WITH_M:
return P("device", None)
case ShardingStrategy.SHARDING_ON_SINGLE_CHIP_WITH_M:
return P("device", None)
case ShardingStrategy.SHARDING_ON_ALL_DEVICES_WITH_N:
return P(None, "device")