forked from nyu-systems/Grendel-GS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalyze_statistic.py
4468 lines (3890 loc) · 169 KB
/
analyze_statistic.py
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
import json
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
from matplotlib.ticker import MultipleLocator
import re
import ast
from scipy.signal import savgol_filter
from scipy.interpolate import interp1d
folder = None
file_names = None
num_render_file_names = None
def delete_all_file_paths(file_paths):
for file_path in file_paths:
if os.path.exists(file_path):
os.remove(file_path)
def read_file(file_name, num_render_file_name=None):
file_path = folder + file_name
# get rk and ws
rk = int(file_name[file_name.find("rk=") + 3])
ws = int(file_name[file_name.find("ws=") + 3])
prefix = file_name[: file_name.find("ws=")]
print("rk: ", rk, "ws: ", ws)
with open(file_path, "r") as file:
file_contents = file.readlines()
# Function to parse each line and extract the statistic and its value
def parse_line(line):
# 10 preprocess time: 0.291950 ms
parts = line.split(":")
if len(parts) != 2:
print("Error parsing line: ", line)
return None
# Extracting the statistic name and its value
stat_name = parts[0]
stat_value = float(parts[1].strip().split("ms")[0].strip())
return stat_name, stat_value
# Parsing the file and constructing the JSON object
stats_json = []
last_iteration = -1
for line in file_contents:
if line.startswith("it="):
iteration = int(line[3 : line.find(",")])
if iteration != last_iteration:
last_iteration = iteration
else:
continue
stats_json.append(
{"iteration": iteration, "prefix": prefix, "rk": rk, "ws": ws}
)
continue
print(line)
parsed_data = parse_line(line)
if parsed_data:
stat_name, stat_value = parsed_data
stats_json[-1][stat_name] = stat_value
if num_render_file_name is not None:
with open(folder + num_render_file_name, "r") as file:
num_render_file_contents = file.readlines()
idx = 0
for line in num_render_file_contents:
# line format:`iteration: 251, num_local_tiles: 398, local_tiles_left_idx: 742, local_tiles_right_idx: 1139, last_local_num_rendered_end: 336199, local_num_rendered_end: 672398, num_rendered: 335791, num_rendered_from_distState: 335791`
# extract iteration, num_local_tiles, num_rendered
iteration = int(
line[line.find("iteration:") + len("iteration: ") : line.find(",")]
)
num_local_tiles = int(
line[
line.find("num_local_tiles:")
+ len("num_local_tiles: ") : line.find(", local_tiles_left_idx:")
]
)
num_rendered = int(
line[
line.find("num_rendered:")
+ len("num_rendered: ") : line.find(
", num_rendered_from_distState:"
)
]
)
assert iteration == stats_json[idx]["iteration"]
stats_json[idx]["num_local_tiles"] = num_local_tiles
stats_json[idx]["num_rendered"] = num_rendered
idx += 1
# Converting the JSON object to a string for display
json_data = json.dumps(stats_json, indent=4)
print(json_data)
return stats_json
def extract_stats_from_file():
file2stats = {}
assert len(file_names) == len(
num_render_file_names
), "file_names and num_render_file_names should have same length"
for file_name, num_render_file_name in zip(file_names, num_render_file_names):
if not os.path.exists(folder + file_name):
continue
file2stats[file_name] = read_file(file_name, num_render_file_name)
# save in file
with open(folder + file_name.removesuffix(".log") + ".json", "w") as f:
json.dump(file2stats[file_name], f, indent=4)
def draw_graph(file_name, iteration):
file_path = folder + file_name
stats = []
with open(file_path, "r") as f:
stats = json.load(f)
data = None
for stat in stats:
if stat["iteration"] == iteration:
data = stat
break
del data["iteration"]
del data["rk"]
del data["ws"]
del data["00 forward time"]
del data["b00 backward time"]
del data["21 updateDistributedStatLocally.getGlobalGaussianOnTiles time"]
del data["22 updateDistributedStatLocally.InclusiveSum time"]
del data["23 updateDistributedStatLocally.getComputeLocally time"]
del data["24 updateDistributedStatLocally.updateTileTouched time"]
# draw a pie chart for the data
labels = data.keys()
sizes = data.values()
# make character smaller
plt.rc("font", size=6)
fig1, ax1 = plt.subplots()
ax1.pie(sizes, labels=labels, autopct="%1.1f%%", shadow=True)
ax1.axis("equal")
plt.title(file_name)
fig_name = file_name.split(".json")[0] + "_it=" + str(iteration) + ".png"
plt.savefig(folder + fig_name)
def extract_excel(iteration, provided_file_names=None):
# extract frame from all data
if provided_file_names is not None:
file_names = provided_file_names
df = None
for file_name in file_names:
if not os.path.exists(folder + file_name):
continue
file_path = folder + file_name.removesuffix(".log") + ".json"
stats = []
with open(file_path, "r") as f:
stats = json.load(f)
data = None
for stat in stats:
if stat["iteration"] == iteration:
data = stat
break
# del data["rk"]
# del data["ws"]
data_for_save = {}
data_for_save["rk"] = data["rk"]
data_for_save["ws"] = data["ws"]
for key in data.keys():
if key == "iteration" or key == "rk" or key == "ws":
continue
data_for_save[key] = data[key]
# print(data)
if df is None:
df = pd.DataFrame(data_for_save, index=[0])
else:
df = pd.concat([df, pd.DataFrame([data_for_save])], ignore_index=True)
# df = df.append(data, ignore_index=True)
df.to_csv(folder + "time_stat_it=" + str(iteration) + ".csv", index=False)
def extract_stats_from_file_bench_num_tiles():
global folder
global file_names
global num_render_file_names
base_folder = "experiments/bench_tile_num2/"
file_names = [
"gpu_time_ws=1_rk=0.log",
]
num_render_file_names = [
"num_rendered_ws=1_rk=0.log",
]
x = os.listdir(base_folder)
# filter out non-folders
x = [t for t in x if os.path.isdir(base_folder + t)]
x.sort(key=lambda x: int(x))
iterations = [1, 301, 601, 901]
for t in x:
folder = base_folder + t + "/"
print(folder)
extract_stats_from_file()
for it in iterations:
extract_excel(it)
stats = None
try:
# load
path = "experiments/n_contributors_3/n_contrib_ws=1_rk=0.json"
with open(path, "r") as f:
stats = json.load(f)
except:
pass
# merge all csv together
for i in iterations:
df = None
stat_iteration = None
if stats is not None:
stat_iteration = []
for data in stats:
if data["mode"] == "local" and data["iteration"] == str(i):
stat_iteration.append(data)
assert len(stat_iteration) == 2170
# print("len stat_iteration: ", len(stat_iteration))
# print("stat_iteration", stat_iteration[:10])
for t in x:
folder = base_folder + t + "/"
df_t = pd.read_csv(folder + "time_stat_it=" + str(i) + ".csv")
# add a columne for tile size
df_t["tile_size"] = t
df_t["b10 render time/tile_size*100"] = (
float(df_t.loc[0, "b10 render time"])
/ float(df_t.loc[0, "tile_size"])
* 100
)
df_t["b10 render time/num_rendered*100000"] = (
float(df_t.loc[0, "b10 render time"])
/ float(df_t.loc[0, "num_rendered"])
* 100000
)
df_t["70 render time/tile_size*100"] = (
float(df_t.loc[0, "70 render time"])
/ float(df_t.loc[0, "tile_size"])
* 100
)
df_t["70 render time/num_rendered*100000"] = (
float(df_t.loc[0, "70 render time"])
/ float(df_t.loc[0, "num_rendered"])
* 100000
)
if df is None:
df = df_t
else:
df = pd.concat([df, df_t], ignore_index=True)
# new rendered
df["new_tile:num_rendered"] = 0.0
df["new_tile:num_real_contributed"] = 0.0
df["new_tile:b10 render time"] = 0.0
df["new_tile:70 render time"] = 0.0
for k in range(1, len(df)):
df.loc[k, "new_tile:num_rendered"] = (
df.loc[k, "num_rendered"] - df.loc[k - 1, "num_rendered"]
)
df.loc[k, "new_tile:b10 render time"] = (
df.loc[k, "b10 render time"] - df.loc[k - 1, "b10 render time"]
)
df.loc[k, "new_tile:70 render time"] = (
df.loc[k, "70 render time"] - df.loc[k - 1, "70 render time"]
)
tile_range = (int(df.loc[k - 1, "tile_size"]), int(df.loc[k, "tile_size"]))
num_real_contributed = 0
ave_contrib_ratio = 0
if stats is not None:
for data in stat_iteration:
if data["iteration"] == str(i) and data["mode"] == "local":
tile_str = data["tile"]
tile_xy = (int(tile_str[0]), int(tile_str[1]))
tile_id = tile_xy[0] * 62 + tile_xy[1]
if tile_range[0] <= tile_id and tile_id < tile_range[1]:
num_real_contributed += float(data["local_real_n_contrib"])
ave_contrib_ratio += float(data["contrib_ratio"])
ave_contrib_ratio = ave_contrib_ratio / float(tile_range[1] - tile_range[0])
df.loc[k, "new_tile:num_real_contributed"] = num_real_contributed
df.loc[k, "new_tile:ave_contrib_ratio"] = ave_contrib_ratio
# print("tile_range: ", tile_range, "num_real_contributed: ", num_real_contributed, "ave_contrib_ratio: ", ave_contrib_ratio)
df.to_csv(base_folder + "time_stat_it=" + str(i) + ".csv", index=False)
def gpu_timer_0():
global folder
global file_names
global num_render_file_names
folder = "experiments/gpu_timer_0/"
file_names = [
"gpu_time_ws=1_rk=0.log",
"gpu_time_ws=2_rk=0.log",
"gpu_time_ws=2_rk=1.log",
"gpu_time_ws=4_rk=0.log",
"gpu_time_ws=4_rk=1.log",
"gpu_time_ws=4_rk=2.log",
"gpu_time_ws=4_rk=3.log",
]
num_render_file_names = [None for i in range(len(file_names))]
extract_stats_from_file()
extract_excel(301)
############################################################################################################
# New tools for analyzing: extract stats from python time log
############################################################################################################
def extract_data_from_list_by_iteration(data_list, iteration):
for stat in data_list:
if stat["iteration"] == iteration:
return stat
return None
def get_suffix_in_folder(folder):
if not os.path.exists(folder):
return None
if not folder.endswith("/"):
folder += "/"
# suffix_list_candidates = [
# "ws=1_rk=0",
# "ws=2_rk=0",
# "ws=2_rk=1",
# "ws=4_rk=0",
# "ws=4_rk=1",
# "ws=4_rk=2",
# "ws=4_rk=3",
# ]
suffix_list_candidates = []
for ws in [1, 2, 4, 8, 16, 32]:
for rk in range(ws):
suffix_list_candidates.append(f"ws={ws}_rk={rk}")
suffix_list = []
for suffix in suffix_list_candidates:
# python_ws=1_rk=0.log
if os.path.exists(folder + "python_" + suffix + ".log"):
suffix_list.append(suffix)
return suffix_list
def get_end2end_stats(file_path):
if not os.path.exists(file_path):
return None
with open(file_path, "r") as f:
lines = f.readlines()
# end2end total_time: 5473.110746 ms, iterations: 30000, throughput 5.48 it/s
# Max Memory usage: 8.000114917755127 GB.
line_for_time = lines[-2]
line_for_memory = lines[-1]
if not line_for_time.startswith("end2end total_time"):
return {"expe_name": file_path.strip("experiments")}
print("line_for_time: ", line_for_time)
print("line_for_memory: ", line_for_memory)
stats = {}
stats["expe_name"] = file_path.strip("experiments")
stats["total_time"] = float(line_for_time.split("total_time: ")[1].split(" ms")[0])
stats["throughput"] = float(line_for_time.split("throughput ")[1].split(" it/s")[0])
stats["max_memory_usage"] = float(
line_for_memory.split("Max Memory usage: ")[1].split(" GB")[0]
)
# round to 3 digits
stats["total_time"] = round(stats["total_time"], 3)
stats["throughput"] = round(stats["throughput"], 3)
stats["max_memory_usage"] = round(stats["max_memory_usage"], 3)
# stats["iterations"] = int(line_for_time.split("iterations: ")[1].split(",")[0])
return stats
def extract_time_excel_from_json(
folder, file_paths, iteration, mode="python"
): # mode = "python" or "gpu"
# extract frame from all data
df = None
for file_path in file_paths:
if not os.path.exists(file_path):
continue
stats = []
with open(file_path, "r") as f:
stats = json.load(f)
# gpu_time_ws=2_rk=0.json, python_time_ws=2_rk=0.log
ws = int(file_path.split("/")[-1].split("_")[2].split("=")[1])
rk = int(file_path.split("/")[-1].split("_")[3].split("=")[1].split(".")[0])
data = extract_data_from_list_by_iteration(stats, iteration)
# assert data is not None, "Queried iteration statistics should be in the log file."
if data is None:
print("Queried iteration statistics is not in the log file.")
continue
data_for_save = {}
data_for_save["rk"] = rk
data_for_save["ws"] = ws
for key in data.keys():
if key == "iteration" or key == "rk" or key == "ws":
continue
data_for_save[key] = data[key]
if df is None:
df = pd.DataFrame(data_for_save, index=[0])
else:
df = pd.concat([df, pd.DataFrame([data_for_save])], ignore_index=True)
if df is None:
print("No data to save in csv.")
return
print("extract_time_excel_from_json at iteration: ", iteration)
df.to_csv(folder + f"{mode}_time_it=" + str(iteration) + ".csv", index=False)
def merge_csv_which_have_same_columns(file_paths, output_file_path):
# add another column for file_path
df = None
for file_path in file_paths:
if not os.path.exists(file_path):
continue
df_t = pd.read_csv(file_path)
df_t["file_path"] = file_path
if df is None:
df = df_t
else:
df = pd.concat([df, df_t], ignore_index=True)
# add an empty row for better visualization
empty_row = {col: None for col in df.columns}
df = df._append(empty_row, ignore_index=True)
if df is None:
return
df.to_csv(output_file_path, index=False)
# iter 1001, TimeFor 'forward': 3.405571 ms
# iter 1001, TimeFor 'image_allreduce': 0.006914 ms
# iter 1001, TimeFor 'loss': 2.740145 ms
# iter 1001, TimeFor 'backward': 15.798092 ms
# iter 1001, TimeFor 'sync_gradients': 0.006199 ms
# iter 1001, TimeFor 'optimizer_step': 2.892017 ms
def extract_json_from_python_time_log(file_path, load_genereated_json=False):
file_name = file_path.split("/")[-1]
ws, rk = (
file_name.split("_")[2].split("=")[1],
file_name.split("_")[3].split("=")[1].split(".")[0],
)
ws, rk = int(ws), int(rk)
# print(file_name, " wk: ", wk, "rk: ", rk)
if load_genereated_json and os.path.exists(
file_path.removesuffix(".log") + ".json"
):
print("load from file" + file_path.removesuffix(".log") + ".json")
with open(file_path.removesuffix(".log") + ".json", "r") as f:
return json.load(f)
with open(file_path, "r") as f:
lines = f.readlines()
stats = []
for line in lines:
if line.startswith("iter"):
parts = line.split(",")
iteration = int(parts[0].split(" ")[1])
if not stats or stats[-1]["iteration"] != iteration:
stats.append({"iteration": iteration, "ws": ws, "rk": rk})
# extract key and time from `TimeFor 'forward': 3.405571 ms`
key = parts[1].split("'")[1]
time = float(parts[1].split("': ")[1].split(" ")[0])
stats[-1][key] = time
# save in file
with open(file_path.removesuffix(".log") + ".json", "w") as f:
json.dump(stats, f, indent=4)
print("return data from file" + file_path.removesuffix(".log") + ".json")
return stats
def extract_3dgs_count_from_python_log(folder):
suffixes = get_suffix_in_folder(folder)
stats = {}
iterations = []
start_iteration = 0
for rk, suffix in enumerate(suffixes):
file = f"python_{suffix}.log"
file_path = folder + file
with open(file_path, "r") as f:
lines = f.readlines()
stats[f"n_3dgs_rk={rk}"] = []
for line in lines:
# start_checkpoint: /pscratch/sd/j/jy-nyu/mat_expes/mat_ball2_4g_dp_2/checkpoints/79997
if line.startswith("start_checkpoint:"):
if "checkpoints/" in line:
start_iteration = int(line.split("checkpoints/")[1].split("/")[0])
else:
start_iteration = 0
# xyz shape: torch.Size([182686, 3])
if line.startswith("xyz shape:"):
# example
# xyz shape: torch.Size([182686, 3])
n_3dgs = int(line.split("[")[1].split(",")[0])
stats[f"n_3dgs_rk={rk}"].append(n_3dgs)
if rk == 0:
iterations.append(start_iteration)
if "Now num of 3dgs:" in line:
# example
# iteration[600,601) densify_and_prune. Now num of 3dgs: 183910. Now Memory usage: 0.23658323287963867 GB. Max Memory usage: 0.399813175201416 GB.
iteration = int(line.split("iteration[")[1].split(",")[0])
n_3dgs = int(line.split("Now num of 3dgs: ")[1].split(".")[0])
if rk == 0:
iterations.append(iteration)
stats[f"n_3dgs_rk={rk}"].append(n_3dgs)
return stats, iterations
def extract_comm_count_from_i2jsend_log(folder):
expe_name = folder.split("/")[-2]
file_path = folder + "i2jsend_ws=4_rk=0.txt"
with open(file_path, "r") as f:
lines = f.readlines()
stats = {"total_comm_count": [], "i2jsend": []}
iterations = []
for line in lines:
# example
# iteration 851:[[511, 6817, 22924, 10372], [534, 5954, 24520, 10415], [1525, 7140, 15090, 11255], [945, 4812, 17584, 9013]]
if line.startswith("iteration"):
parts = line.split(":")
iteration = int(parts[0].split(" ")[1])
iterations.append(iteration)
i2jsend_json_data = json.loads(parts[1])
# stats["i2jsend"].append(i2jsend_json_data)
stats["total_comm_count"].append(
sum(
[
sum(i2jsend_json_data[i]) - i2jsend_json_data[i][i]
for i in range(len(i2jsend_json_data))
]
)
)
return stats, iterations
def extract_json_from_i2jsend_log(file_path):
file_name = file_path.split("/")[-1]
ws, rk = (
file_name.split("_")[1].split("=")[1],
file_name.split("_")[2].split("=")[1].split(".")[0],
)
ws, rk = int(ws), int(rk)
with open(file_path, "r") as f:
lines = f.readlines()
stats = []
for line in lines:
# example
# iteration 851:[[511, 6817, 22924, 10372], [534, 5954, 24520, 10415], [1525, 7140, 15090, 11255], [945, 4812, 17584, 9013]]
if line.startswith("iteration"):
parts = line.split(":")
iteration = int(parts[0].split(" ")[1])
if not stats or stats[-1]["iteration"] != iteration:
stats.append({"iteration": iteration, "ws": ws})
i2jsend_json_data = json.loads(parts[1])
stats[-1]["i2jsend"] = i2jsend_json_data
stats[-1]["total_comm_count"] = sum(
[
sum(i2jsend_json_data[i]) - i2jsend_json_data[i][i]
for i in range(len(i2jsend_json_data))
]
)
# save in file
with open(file_path.removesuffix(".txt") + ".json", "w") as f:
json.dump(stats, f, indent=4)
return stats
def extract_csv_from_forward_all_to_all_communication_json(
folder, time_data, suffix_list, all2all_stats, process_iterations
):
# save results in csv: i2jsend.csv
columns = [
"iteration",
"ws",
"rk",
"send_volume",
"recv_volume",
"forward_all_to_all_communication",
]
df = pd.DataFrame(columns=columns)
ws = int(suffix_list[0].split("_")[0].split("=")[1])
for iteration in process_iterations:
python_time_rks = []
for rk, suffix in enumerate(suffix_list):
data = time_data[suffix]["python_time"]
data = extract_data_from_list_by_iteration(data, iteration)
python_time_rks.append(data["forward_all_to_all_communication"])
stat = extract_data_from_list_by_iteration(all2all_stats, iteration)
i2jsend = stat["i2jsend"]
i2jsend = np.array(i2jsend)
send_volume = np.sum(i2jsend, axis=1)
recv_volume = np.sum(i2jsend, axis=0)
# print experiment name and iteration
with open(folder + f"i2jsend_ws={ws}.txt", "a") as f:
f.write(f"experiment: {folder}\n")
f.write(f"iteration: {iteration}\n")
f.write(f"send_volume: {send_volume}\n")
f.write(f"recv_volume: {recv_volume}\n")
f.write(f"python_time_rks: {python_time_rks}\n")
f.write("\n")
for i, suffix in enumerate(suffix_list):
this_ws = int(suffix.split("_")[0].split("=")[1])
rk = int(suffix.split("_")[1].split("=")[1])
assert rk == i, "rk should be the same as index!"
assert ws == this_ws, "ws should be the same!"
df = df._append(
{
"iteration": int(iteration),
"ws": int(ws),
"rk": int(rk),
"send_volume": int(send_volume[rk]),
"recv_volume": int(recv_volume[rk]),
"forward_all_to_all_communication": python_time_rks[i],
},
ignore_index=True,
)
# append an empty row for better visualization
df = df._append(
{
"iteration": "",
"ws": "",
"rk": "",
"send_volume": "",
"recv_volume": "",
"forward_all_to_all_communication": "",
},
ignore_index=True,
)
# save in file
df.to_csv(folder + f"i2jsend_ws={ws}.csv", index=False)
def extract_memory_json_from_log(folder, file):
file_path = folder + file
with open(file_path, "r") as f:
lines = f.readlines()
stats = []
for line in lines:
if "densify_and_prune. Now num of 3dgs:" in line:
# example
# iteration 1000 densify_and_prune. Now num of 3dgs: 54539. Now Memory usage: 0.45931053161621094 GB. Max Memory usage: 4.580923080444336 GB.
iteration = int(line.split("iteration ")[1].split(" ")[0])
n_3dgs = int(line.split("Now num of 3dgs: ")[1].split(".")[0])
now_memory_usage = float(
line.split("Now Memory usage: ")[1].split(" GB")[0]
)
max_memory_usage = float(
line.split("Max Memory usage: ")[1].split(" GB")[0]
)
stats.append(
{
"iteration": iteration,
"n_3dgs": n_3dgs,
"now_memory_usage": now_memory_usage,
"max_memory_usage": max_memory_usage,
}
)
# save in file
memory_log_path = folder + file.removesuffix(".log") + "_mem.json"
with open(memory_log_path, "w") as f:
json.dump(stats, f, indent=4)
return stats
def extract_all_memory_json_from_log(folder):
files = [
"python_ws=1_rk=0.log",
"python_ws=2_rk=0.log",
"python_ws=2_rk=1.log",
"python_ws=4_rk=0.log",
"python_ws=4_rk=1.log",
"python_ws=4_rk=2.log",
"python_ws=4_rk=3.log",
]
stats = []
for file in files:
if os.path.exists(folder + file):
stats.append(extract_memory_json_from_log(folder, file))
return stats
def extract_json_from_gpu_time_log(file_path, load_genereated_json=False):
file_name = file_path.split("/")[-1]
ws, rk = (
file_name.split("_")[2].split("=")[1],
file_name.split("_")[3].split("=")[1].split(".")[0],
)
ws, rk = int(ws), int(rk)
if load_genereated_json and os.path.exists(
file_path.removesuffix(".log") + ".json"
):
print("load from file" + file_path.removesuffix(".log") + ".json")
with open(file_path.removesuffix(".log") + ".json", "r") as f:
return json.load(f)
if not os.path.exists(file_path):
return {}
with open(file_path, "r") as file:
file_contents = file.readlines()
# Function to parse each line and extract the statistic and its value
def parse_line(line):
# 10 preprocess time: 0.291950 ms
parts = line.split(":")
if len(parts) != 2:
# print("Error parsing line: ", line)
return None
# Extracting the statistic name and its value
stat_name = parts[0]
stat_value = float(parts[1].strip().split("ms")[0].strip())
return stat_name, stat_value
# Parsing the file and constructing the JSON object
stats_json = []
last_iteration = -1
for line in file_contents:
if line.startswith("it="):
iteration = int(line[3 : line.find(",")])
if iteration != last_iteration:
last_iteration = iteration
else:
continue
stats_json.append({"iteration": iteration})
continue
# print(line)
parsed_data = parse_line(line)
if parsed_data:
stat_name, stat_value = parsed_data
stats_json[-1][stat_name] = stat_value
# save in file
with open(file_path.removesuffix(".log") + ".json", "w") as f:
json.dump(stats_json, f, indent=4)
print("return data from file" + file_path.removesuffix(".log") + ".json")
return stats_json
def get_number_prefix(s):
# the number may have multiple digits
# example: s = "123abc", return 123
# example: s = "123", return 123
is_float = False
for i in range(len(s)):
if not s[i].isdigit():
if s[i] == "-" and s[i + 1].isdigit():
continue
if s[i] == ".":
is_float = True
continue
# print(s[i], i)
number = float(s[:i]) if is_float else int(s[:i])
return number, s[i:]
assert False, "s should have a number prefix"
def get_number_tuple_prefix(s):
# the number may have multiple digits
# example: s = "(0, 0)abc", return (0,0)
left = s.find("(")
right = s.find(")")
assert left != -1 and right != -1, "s should have a number tuple prefix"
tuple_str = s[left + 1 : right]
tuple_str = tuple_str.split(",")
assert len(tuple_str) == 2, "tuple_str should have 2 elements"
return (int(tuple_str[0].strip()), int(tuple_str[1].strip())), s[right + 1 :]
def extract_json_from_n_contrib_log(file_path):
file_name = file_path.split("/")[-1]
ws, rk = (
file_name.split("_")[2].split("=")[1],
file_name.split("_")[3].split("=")[1].split(".")[0],
)
ws, rk = int(ws), int(rk)
print(file_name, " ws: ", ws, "rk: ", rk)
# if os.path.exists(file_path.removesuffix(".log") + ".json"):
# with open(file_path.removesuffix(".log") + ".json", 'r') as f:
# return json.load(f)
with open(file_path, "r") as f:
lines = f.readlines()
stats = []
last_iteration = None
for line in lines:
# an example
# iteration: 1, iteration: 1, local_rank: 0, world_size: 1, num_tiles: 62, num_pixels: 534100, num_rendered: 23574, global_ave_n_rendered_per_pix: 380.225800, global_ave_n_considered_per_pix: 11.138024, global_ave_n_contrib2loss_per_pix: 4.609777
if "world_size" in line:
tmp_line = line
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix("iteration: ")
iteration, tmp_line = get_number_prefix(tmp_line)
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix("local_rank: ")
local_rank, tmp_line = get_number_prefix(tmp_line)
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix("world_size: ")
world_size, tmp_line = get_number_prefix(tmp_line)
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix("num_tiles: ")
num_tiles, tmp_line = get_number_prefix(tmp_line)
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix("num_pixels: ")
num_pixels, tmp_line = get_number_prefix(tmp_line)
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix("num_rendered: ")
num_rendered, tmp_line = get_number_prefix(tmp_line)
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix(
"global_ave_n_rendered_per_pix: "
)
global_ave_n_rendered_per_pix, tmp_line = get_number_prefix(tmp_line)
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix(
"global_ave_n_considered_per_pix: "
)
global_ave_n_considered_per_pix, tmp_line = get_number_prefix(tmp_line)
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix(
"global_ave_n_contrib2loss_per_pix: "
)
global_ave_n_contrib2loss_per_pix, tmp_line = get_number_prefix(tmp_line)
assert iteration == last_iteration, "iteration should be the same"
stats[-1]["stats"] = {
"iteration": iteration,
"local_rank": local_rank,
"world_size": world_size,
"num_tiles": num_tiles,
"num_pixels": num_pixels,
"num_rendered": num_rendered,
"global_ave_n_rendered_per_pix": global_ave_n_rendered_per_pix,
"global_ave_n_considered_per_pix": global_ave_n_considered_per_pix,
"global_ave_n_contrib2loss_per_pix": global_ave_n_contrib2loss_per_pix,
}
continue
# an example
# iteration: 1, tile: (0, 12), range: (1639, 1501), num_rendered_this_tile: 138, n_considered_per_pixel: 138.000000, n_contrib2loss_per_pixel: 77.437500, contrib2loss_ratio: 0.302490
if line.startswith("iteration:"):
tmp_line = line
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix("iteration: ")
iteration, tmp_line = get_number_prefix(tmp_line)
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix("tile: ")
tile, tmp_line = get_number_tuple_prefix(tmp_line)
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix("range: ")
range, tmp_line = get_number_tuple_prefix(tmp_line)
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix("num_rendered_this_tile: ")
num_rendered_this_tile, tmp_line = get_number_prefix(tmp_line)
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix("n_considered_per_pixel: ")
n_considered_per_pixel, tmp_line = get_number_prefix(tmp_line)
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix("n_contrib2loss_per_pixel: ")
n_contrib2loss_per_pixel, tmp_line = get_number_prefix(tmp_line)
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix("contrib2loss_ratio: ")
contrib2loss_ratio, tmp_line = get_number_prefix(tmp_line)
if iteration != last_iteration:
stats.append({"iteration": iteration, "data": []})
last_iteration = iteration
stats[-1]["data"].append(
{
"iteration": iteration,
"tile": tile,
"range": range,
"num_rendered_this_tile": num_rendered_this_tile,
"n_considered_per_pixel": n_considered_per_pixel,
"n_contrib2loss_per_pixel": n_contrib2loss_per_pixel,
# "contrib2loss_ratio": contrib2loss_ratio,
}
)
# save in file
with open(file_path.removesuffix(".log") + ".json", "w") as f:
json.dump(stats, f, indent=4)
return stats
def extract_json_from_num_rendered_log(file_path):
file_name = file_path.split("/")[-1]
ws, rk = (
file_name.split("_")[2].split("=")[1],
file_name.split("_")[3].split("=")[1].split(".")[0],
)
ws, rk = int(ws), int(rk)
# if os.path.exists(file_path.removesuffix(".log") + ".json"):
# with open(file_path.removesuffix(".log") + ".json", 'r') as f:
# return json.load(f)
with open(file_path, "r") as file:
file_contents = file.readlines()
stats = []
for line in file_contents:
# example
# iteration: 1, iteration: 1, num_local_tiles: 62, local_tiles_left_idx: 0, local_tiles_right_idx: 61, last_local_num_rendered_end: 0, local_num_rendered_end: 62, num_rendered: 23574, num_rendered_from_distState: 23574
if line.startswith("iteration:"):
tmp_line = line
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix("iteration: ")
iteration, tmp_line = get_number_prefix(tmp_line)
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix("num_local_tiles: ")
num_local_tiles, tmp_line = get_number_prefix(tmp_line)
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix("local_tiles_left_idx: ")
local_tiles_left_idx, tmp_line = get_number_prefix(tmp_line)
# print(tmp_line)
tmp_line = tmp_line.strip(", ").removeprefix("local_tiles_right_idx: ")
local_tiles_right_idx, tmp_line = get_number_prefix(tmp_line)
# print(tmp_line)