File size: 9,243 Bytes
b1d4de0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# File: diffusion-fast-main/prepare_results.py
import argparse
import glob
import os
import sys
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from huggingface_hub import upload_file
sys.path.append('.')
from utils.benchmarking_utils import collate_csv
REPO_ID = 'sayakpaul/sample-datasets'

def prepare_plot(df, args):
    columns_to_drop = ['batch_size', 'num_inference_steps', 'pipeline_cls', 'ckpt_id', 'upcast_vae', 'memory (gbs)', 'actual_gpu_memory (gbs)', 'tag']
    df_filtered = df.drop(columns=columns_to_drop)
    df_filtered[['quant']] = df_filtered[['do_quant']].fillna('None')
    df_filtered.drop(columns=['do_quant'], inplace=True)
    df_filtered['settings'] = df_filtered.apply(lambda row: ', '.join([f'{col}-{row[col]}' for col in df_filtered.columns if col != 'time (secs)']), axis=1)
    df_filtered['formatted_settings'] = df_filtered['settings'].str.replace(', ', '\n', regex=False)
    df_filtered.loc[0, 'formatted_settings'] = 'default'
    plt.figure(figsize=(12, 10))
    sns.set_style('whitegrid')
    n_settings = len(df_filtered['formatted_settings'].unique())
    bar_positions = range(n_settings)
    palette = sns.color_palette('husl', n_settings)
    bar_width = 0.25
    for (i, setting) in enumerate(df_filtered['formatted_settings'].unique()):
        mean_time = df_filtered[df_filtered['formatted_settings'] == setting]['time (secs)'].mean()
        plt.bar(i, mean_time, width=bar_width, align='center', color=palette[i])
        plt.text(i, mean_time + 0.01, f'{mean_time:.2f}', ha='center', va='bottom', fontsize=14, fontweight='bold')
    plt.xticks(bar_positions, df_filtered['formatted_settings'].unique(), rotation=45, ha='right', fontsize=10)
    plt.ylabel('Time in Seconds', fontsize=14, labelpad=15)
    plt.xlabel('Settings', fontsize=14, labelpad=15)
    plt.title(args.plot_title, fontsize=18, fontweight='bold', pad=20)
    plt.grid(axis='y', linestyle='--', linewidth=0.7, alpha=0.7)
    plt.tight_layout()
    plt.subplots_adjust(top=0.9, bottom=0.2)
    plot_path = args.plot_title.replace(' ', '_') + '.png'
    plt.savefig(plot_path, bbox_inches='tight', dpi=300)
    if args.push_to_hub:
        upload_file(repo_id=REPO_ID, path_in_repo=plot_path, path_or_fileobj=plot_path, repo_type='dataset')
        print(f'Plot successfully uploaded. Find it here: https://huggingface.co/datasets/{REPO_ID}/blob/main/{args.plot_file_path}')
    plt.show()

def main(args):
    all_csvs = sorted(glob.glob(f'{args.base_path}/*.csv'))
    all_csvs = [os.path.join(args.base_path, x) for x in all_csvs]
    is_pixart = 'PixArt-alpha' in all_csvs[0]
    collate_csv(all_csvs, args.final_csv_filename, is_pixart=is_pixart)
    if args.push_to_hub:
        upload_file(repo_id=REPO_ID, path_in_repo=args.final_csv_filename, path_or_fileobj=args.final_csv_filename, repo_type='dataset')
        print(f'CSV successfully uploaded. Find it here: https://huggingface.co/datasets/{REPO_ID}/blob/main/{args.final_csv_filename}')
    if args.plot_title is not None:
        df = pd.read_csv(args.final_csv_filename)
        prepare_plot(df, args)
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--base_path', type=str, default='.')
    parser.add_argument('--final_csv_filename', type=str, default='collated_results.csv')
    parser.add_argument('--plot_title', type=str, default=None)
    parser.add_argument('--push_to_hub', action='store_true')
    args = parser.parse_args()
    main(args)

# File: diffusion-fast-main/run_benchmark.py
import torch
torch.set_float32_matmul_precision('high')
import sys
sys.path.append('.')
from utils.benchmarking_utils import benchmark_fn, create_parser, generate_csv_dict, write_to_csv
from utils.pipeline_utils import load_pipeline

def run_inference(pipe, args):
    _ = pipe(prompt=args.prompt, num_inference_steps=args.num_inference_steps, num_images_per_prompt=args.batch_size)

def main(args) -> dict:
    pipeline = load_pipeline(ckpt=args.ckpt, compile_unet=args.compile_unet, compile_vae=args.compile_vae, no_sdpa=args.no_sdpa, no_bf16=args.no_bf16, upcast_vae=args.upcast_vae, enable_fused_projections=args.enable_fused_projections, do_quant=args.do_quant, compile_mode=args.compile_mode, change_comp_config=args.change_comp_config, device=args.device)
    run_inference(pipeline, args)
    run_inference(pipeline, args)
    run_inference(pipeline, args)
    time = benchmark_fn(run_inference, pipeline, args)
    data_dict = generate_csv_dict(pipeline_cls=str(pipeline.__class__.__name__), args=args, time=time)
    img = pipeline(prompt=args.prompt, num_inference_steps=args.num_inference_steps, num_images_per_prompt=args.batch_size).images[0]
    return (data_dict, img)
if __name__ == '__main__':
    parser = create_parser()
    args = parser.parse_args()
    print(args)
    (data_dict, img) = main(args)
    name = args.ckpt.replace('/', '_') + f'bf16@{not args.no_bf16}-sdpa@{not args.no_sdpa}-bs@{args.batch_size}-fuse@{args.enable_fused_projections}-upcast_vae@{args.upcast_vae}-steps@{args.num_inference_steps}-unet@{args.compile_unet}-vae@{args.compile_vae}-mode@{args.compile_mode}-change_comp_config@{args.change_comp_config}-do_quant@{args.do_quant}-tag@{args.tag}-device@{args.device}.csv'
    img.save(f"{name.replace('.csv', '')}.jpeg")
    write_to_csv(name, data_dict)

# File: diffusion-fast-main/run_benchmark_pixart.py
import torch
torch.set_float32_matmul_precision('high')
import sys
sys.path.append('.')
from utils.benchmarking_utils import benchmark_fn, create_parser, generate_csv_dict, write_to_csv
from utils.pipeline_utils_pixart import load_pipeline

def run_inference(pipe, args):
    _ = pipe(prompt=args.prompt, num_inference_steps=args.num_inference_steps, num_images_per_prompt=args.batch_size)

def main(args) -> dict:
    pipeline = load_pipeline(ckpt=args.ckpt, compile_transformer=args.compile_transformer, compile_vae=args.compile_vae, no_sdpa=args.no_sdpa, no_bf16=args.no_bf16, enable_fused_projections=args.enable_fused_projections, do_quant=args.do_quant, compile_mode=args.compile_mode, change_comp_config=args.change_comp_config, device=args.device)
    run_inference(pipeline, args)
    run_inference(pipeline, args)
    run_inference(pipeline, args)
    time = benchmark_fn(run_inference, pipeline, args)
    data_dict = generate_csv_dict(pipeline_cls=str(pipeline.__class__.__name__), args=args, time=time)
    img = pipeline(prompt=args.prompt, num_inference_steps=args.num_inference_steps, num_images_per_prompt=args.batch_size).images[0]
    return (data_dict, img)
if __name__ == '__main__':
    parser = create_parser(is_pixart=True)
    args = parser.parse_args()
    print(args)
    (data_dict, img) = main(args)
    name = args.ckpt.replace('/', '_') + f'bf16@{not args.no_bf16}-sdpa@{not args.no_sdpa}-bs@{args.batch_size}-fuse@{args.enable_fused_projections}-upcast_vae@NA-steps@{args.num_inference_steps}-transformer@{args.compile_transformer}-vae@{args.compile_vae}-mode@{args.compile_mode}-change_comp_config@{args.change_comp_config}-do_quant@{args.do_quant}-tag@{args.tag}-device@{args.device}.csv'
    img.save(f'{name}.jpeg')
    write_to_csv(name, data_dict, is_pixart=True)

# File: diffusion-fast-main/run_profile.py
import torch
torch.set_float32_matmul_precision('high')
from torch._inductor import config as inductorconfig
inductorconfig.triton.unique_kernel_names = True
import functools
import sys
sys.path.append('.')
from utils.benchmarking_utils import create_parser
from utils.pipeline_utils import load_pipeline

def profiler_runner(path, fn, *args, **kwargs):
    with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA], record_shapes=True) as prof:
        result = fn(*args, **kwargs)
    prof.export_chrome_trace(path)
    return result

def run_inference(pipe, args):
    _ = pipe(prompt=args.prompt, num_inference_steps=args.num_inference_steps, num_images_per_prompt=args.batch_size)

def main(args) -> dict:
    pipeline = load_pipeline(ckpt=args.ckpt, compile_unet=args.compile_unet, compile_vae=args.compile_vae, no_sdpa=args.no_sdpa, no_bf16=args.no_bf16, upcast_vae=args.upcast_vae, enable_fused_projections=args.enable_fused_projections, do_quant=args.do_quant, compile_mode=args.compile_mode, change_comp_config=args.change_comp_config, device=args.device)
    run_inference(pipeline, args)
    run_inference(pipeline, args)
    trace_path = args.ckpt.replace('/', '_') + f'bf16@{not args.no_bf16}-sdpa@{not args.no_sdpa}-bs@{args.batch_size}-fuse@{args.enable_fused_projections}-upcast_vae@{args.upcast_vae}-steps@{args.num_inference_steps}-unet@{args.compile_unet}-vae@{args.compile_vae}-mode@{args.compile_mode}-change_comp_config@{args.change_comp_config}-do_quant@{args.do_quant}-device@{args.device}.json'
    runner = functools.partial(profiler_runner, trace_path)
    with torch.autograd.profiler.record_function('sdxl-brrr'):
        runner(run_inference, pipeline, args)
    return trace_path
if __name__ == '__main__':
    parser = create_parser()
    args = parser.parse_args()
    if not args.compile_unet:
        args.compile_mode = 'NA'
    trace_path = main(args)
    print(f'Trace generated at: {trace_path}')