plot_comparison.py 14.5 KB
Newer Older
sharkgene@qq.com's avatar
sharkgene@qq.com 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
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import argparse
import json
import os

plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

parser = argparse.ArgumentParser(description='绘制模型性能对比图表')
parser.add_argument('--配置', '-f', type=str, default='data_config.json', help='数据配置文件路径')
parser.add_argument('--输出目录', '-d', type=str, default='charts', help='输出图表目录')
parser.add_argument('--合并分组', '-m', action='store_true', help='将第一层分组合并到一张图中')
args = parser.parse_args()

def load_data_from_files(config):
    all_data = []
    files_config = config.get('files', [])
    
    for file_config in files_config:
        file_path = file_config.get('file')
        sheets = file_config.get('sheets', [])
        column_mapping = file_config.get('column_mapping', {})
sharkgene@qq.com's avatar
sharkgene@qq.com committed
26
        column_add = file_config.get('column_add', {})
sharkgene@qq.com's avatar
sharkgene@qq.com committed
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
        
        if not os.path.exists(file_path):
            print(f"文件不存在: {file_path}, 跳过")
            continue
        
        xl = pd.ExcelFile(file_path)
        
        if sheets is None or (isinstance(sheets, list) and len(sheets) == 0):
            sheets = xl.sheet_names
        else:
            sheets = [s for s in sheets if s]
        
        for sheet in sheets:
            try:
                df = pd.read_excel(file_path, sheet_name=sheet)
                df.columns = df.columns.str.replace('\n', '').str.strip()
                
                if column_mapping:
                    df = df.rename(columns=column_mapping)
                
                column_replace = file_config.get('column_replace', {})
                for col, replace_dict in column_replace.items():
                    if col in df.columns:
                        df[col] = df[col].replace(replace_dict)
                
                df['source_file'] = file_path
                df['source_sheet'] = sheet
                all_data.append(df)
                print(f"读取: {file_path} - {sheet}, {len(df)} 行")
sharkgene@qq.com's avatar
sharkgene@qq.com committed
56
57
58
59

                for c in column_add:
                   df[c] = column_add[c]

sharkgene@qq.com's avatar
sharkgene@qq.com committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
            except Exception as e:
                print(f"读取失败: {file_path} - {sheet}: {e}")
    
    if not all_data:
        return pd.DataFrame()
    
    combined_df = pd.concat(all_data, ignore_index=True)
    return combined_df

def apply_filter(df, filter_dict):
    for filter_col, filter_values in filter_dict.items():
        if filter_col in df.columns and filter_values:
            if isinstance(filter_values, list):
                df = df[df[filter_col].isin(filter_values)]
            else:
                df = df[df[filter_col] == filter_values]
    return df

sharkgene@qq.com's avatar
sharkgene@qq.com committed
78
def generate_chart(df_subset, output_path, colkey, outer_group_cols, inner_group_cols, metric_cols, merge_groups=False):
sharkgene@qq.com's avatar
sharkgene@qq.com committed
79
    df_subset = df_subset.copy()
sharkgene@qq.com's avatar
sharkgene@qq.com committed
80
81
82
    compare_col = "ColKey"
    df_subset[compare_col] = df_subset[colkey].apply(lambda x: '_'.join(x.dropna().astype(str)), axis=1)
    #df_subset[compare_col] = df_subset['vLLM版本'].astype(str) + '_' + df_subset['V0/V1 Engine'].astype(str)
sharkgene@qq.com's avatar
sharkgene@qq.com committed
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
    
    all_group_cols = outer_group_cols + inner_group_cols
    if all_group_cols:
        df_grouped = df_subset[all_group_cols + [compare_col] + metric_cols].groupby(all_group_cols + [compare_col]).mean().reset_index()
    else:
        df_grouped = df_subset[[compare_col] + metric_cols].groupby([compare_col]).mean().reset_index()
        df_grouped[compare_col] = df_grouped.index
    
    if len(df_grouped) == 0:
        print(f"    无数据,跳过")
        return False
    
    if outer_group_cols:
        outer_values = df_grouped.groupby(outer_group_cols).size().reset_index()
    else:
        outer_values = pd.DataFrame({'': ['all']})
    
    n_outer = len(outer_values)
    engine_values = df_grouped[compare_col].unique()
    n_engines = len(engine_values)
    
104
    # 设置配色
sharkgene@qq.com's avatar
sharkgene@qq.com committed
105
106
    color_palette = ['#2E86AB', '#A23B72', '#F18F01', '#C73E1D', '#3B1F2B', '#95C623', '#7B2D26']
    colors = [color_palette[i % len(color_palette)] for i in range(n_engines)]
107
108
109
110
111
112
113

    #seaborn_pastel = ['#a1c9f4', '#ffb482', '#8de5a1', '#ff9f9b', '#d0bbff', '#debb9b', '#fab0e4', '#cfcfcf', '#fffea3', '#b9f2f0' ]
    #colors = [seaborn_pastel[i % len(seaborn_pastel)] for i in range(n_engines)]

    #seaborn_default = ['#4c72b0', '#dd8452', '#55a868', '#c44e52', '#8172b3', '#937860', '#da8bc3', '#8c8c8c', '#ccb974', '#64b5cd' ]
    #colors = [seaborn_default[i % len(seaborn_default)] for i in range(n_engines)]

sharkgene@qq.com's avatar
sharkgene@qq.com committed
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
    if merge_groups and n_outer > 1:
        fig, axes = plt.subplots(1, 4, figsize=(8 * n_outer + 20, 10))
        
        bar_width = 0.12
        bar_spacing = 0.05
        group_gap = 3
        
        x_labels_all = None
        
        for col, metric in enumerate(metric_cols):
            ax = axes[col]
            
            current_x = 0
            
            for row_idx, (_, outer_row) in enumerate(outer_values.iterrows()):
                df_outer = df_grouped.copy()
                for gcol in outer_group_cols:
                    df_outer = df_outer[df_outer[gcol] == outer_row[gcol]]
                
                outer_label_value = '-'.join([str(outer_row[gcol]) for gcol in outer_group_cols])
                
                pt = df_outer.pivot_table(
                    index=inner_group_cols, 
                    columns=compare_col, 
                    values=metric
                ).fillna(0)
                
                n_bars_per_group = len(pt)
                group_width = n_bars_per_group * n_engines * (bar_width + bar_spacing) + group_gap
                group_center = current_x + group_width / 2
                
                x_labels = ['/'.join([str(v) for v in idx]) for idx in pt.index]
                if x_labels_all is None:
                    x_labels_all = x_labels
                
                x = np.arange(len(x_labels)) * (n_engines * (bar_width + bar_spacing)) + current_x
                
                for i, engine in enumerate(engine_values):
                    if engine in pt.columns:
                        values = pt[engine].values
                        offset = i * bar_width
                        label = f"{engine} ({outer_label_value})"
                        bars = ax.bar(x + offset, values, bar_width, label=label, color=colors[i], edgecolor='white', linewidth=0.5)
                        
                        for bar, val in zip(bars, values):
                            if val > 0:
                                y_pos = bar.get_height() + bar.get_height()*0.02 if bar.get_height() > 0 else 1
                                ax.text(bar.get_x() + bar.get_width()/2, y_pos, 
                                        f'{val:.1f}', ha='center', va='bottom', fontsize=5, fontweight='bold')
                
                ax.axvline(x=current_x + n_bars_per_group * n_engines * (bar_width + bar_spacing) + group_gap/2, color='gray', linestyle='--', linewidth=1)
                
                ax.text(group_center, ax.get_ylim()[1] * 0.95, outer_label_value, 
                        ha='center', va='top', fontsize=9, fontweight='bold', 
                        bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
                
                current_x = current_x + n_bars_per_group * n_engines * (bar_width + bar_spacing) + group_gap
            
            total_inner_labels = len(x_labels_all)
            inner_positions = []
            inner_labels = []
            for gi in range(len(outer_values)):
                base_x = gi * (total_inner_labels * n_engines * (bar_width + bar_spacing) + group_gap)
                for xi in range(total_inner_labels):
                    center_pos = base_x + xi * n_engines * (bar_width + bar_spacing) + (n_engines * bar_width + (n_engines-1) * bar_spacing) / 2
                    inner_positions.append(center_pos)
                    inner_labels.append(x_labels_all[xi])
            
            ax.set_xticks(inner_positions)
            ax.set_xticklabels(inner_labels, rotation=45, ha='right', fontsize=6)
            
            ax.set_xlabel('/'.join(inner_group_cols), fontsize=9)
            ax.set_ylabel(metric, fontsize=10)
            ax.set_title(f'{metric}', fontsize=12, fontweight='bold')
            ax.grid(axis='y', alpha=0.3, linestyle='--')
            ax.legend(fontsize=5, loc='upper right', framealpha=0.9, ncol=1)
    else:
        fig, axes = plt.subplots(n_outer, 4, figsize=(24, 5 * n_outer))
        
        if n_outer == 1:
            axes = axes.reshape(1, -1)
        
        bar_width = 0.2
        
        outer_label = '/'.join(outer_group_cols) if outer_group_cols else '全部'
        
        for row_idx, (_, outer_row) in enumerate(outer_values.iterrows()):
            df_outer = df_grouped.copy()
            for col in outer_group_cols:
                df_outer = df_outer[df_outer[col] == outer_row[col]]
            
            outer_label_value = '-'.join([str(outer_row[col]) for col in outer_group_cols])
            
            for col, metric in enumerate(metric_cols):
                ax = axes[row_idx, col]
                
                pt = df_outer.pivot_table(
                    index=inner_group_cols, 
                    columns=compare_col, 
                    values=metric
                ).fillna(0)
                
                x_labels = ['/'.join([str(v) for v in idx]) for idx in pt.index]
                x = np.arange(len(x_labels))
                
                for i, engine in enumerate(engine_values):
                    if engine in pt.columns:
                        values = pt[engine].values
                        offset = (i - n_engines/2 + 0.5) * bar_width
                        bars = ax.bar(x + offset, values, bar_width, label=engine, color=colors[i], edgecolor='white', linewidth=0.5)
                        
                        for bar, val in zip(bars, values):
                            if val > 0:
                                y_pos = bar.get_height() + bar.get_height()*0.02 if bar.get_height() > 0 else 1
                                ax.text(bar.get_x() + bar.get_width()/2, y_pos, 
                                        f'{val:.1f}', ha='center', va='bottom', fontsize=7, fontweight='bold')
                
                ax.set_xlabel('/'.join(inner_group_cols), fontsize=9)
                ax.set_ylabel(metric, fontsize=10)
                ax.set_title(f'{outer_label}={outer_label_value} - {metric}', fontsize=11, fontweight='bold')
                ax.set_xticks(x)
                ax.set_xticklabels(x_labels, rotation=45, ha='right', fontsize=7)
                ax.grid(axis='y', alpha=0.3, linestyle='--')
                
                ax.legend(fontsize=6, loc='upper right', framealpha=0.9, ncol=1)
    
    plt.tight_layout()
    plt.savefig(output_path, dpi=150, bbox_inches='tight', facecolor='white')
    plt.close()
    return True

print(f"从配置文件加载数据: {args.配置}")

with open(args.配置, 'r', encoding='utf-8') as f:
    config = json.load(f)

df = load_data_from_files(config)

if df.empty:
    print("未加载到数据")
    exit(1)

print(f"\n可用列名: {df.columns.tolist()}")

col_mapping = {}
for std_col, alt_cols in [
    ('模型', ['模型', 'model', 'Model']),
    ('卡类型', ['卡类型', 'card_type', '卡']),
    ('卡数', ['卡数', 'num_cards', '卡数', 'GPU数量']),
    ('vLLM版本', ['vLLM版本', 'vllm_version', 'vLLM版本']),
    ('V0/V1 Engine', ['V0/V1 Engine', 'Engine', 'engine']),
    ('输入长度(tokens)', ['输入长度(tokens)', 'input_length', 'input length', '输入长度']),
    ('输出长度(tokens)', ['输出长度(tokens)', 'output_length', 'output length', '输出长度']),
    ('并发数', ['并发数', 'concurrency', '并发', 'num_concurrent']),
    ('平均首字延时TTFT(ms)', ['平均首字延时TTFT(ms)', 'ttft', 'TTFT', '首字延时']),
    ('平均生成时间TPOT(ms)', ['平均生成时间TPOT(ms)', 'tpot', 'TPOT', '生成时间']),
    ('生成吞吐量(tokens/s)', ['生成吞吐量(tokens/s)', 'gen_throughput', '生成吞吐']),
    ('总吞吐量(tokens/s)', ['总吞吐量(tokens/s)', 'total_throughput', '总吞吐'])
]:
    for alt in alt_cols:
        if alt in df.columns:
            col_mapping[std_col] = alt

print(f"\n列映射: {col_mapping}")
df_renamed = df.rename(columns=col_mapping)

filter_config = config.get('filter', {})
df_renamed = apply_filter(df_renamed, filter_config)

print(f"过滤后数据量: {len(df_renamed)}")


286
dist_cols_config = config.get('dist_cols', ['模型', '卡数'])
sharkgene@qq.com's avatar
sharkgene@qq.com committed
287
288
289
290
291
dist_cols = [col_mapping.get(c, c) for c in dist_cols_config]
dist_cols = [c for c in dist_cols if c in df_renamed.columns]

os.makedirs(args.输出目录, exist_ok=True)

292
293
294
295
group_cols = config.get('group_cols', [[], []])
if isinstance(group_cols[0], list):
    outer_group = group_cols[0] if len(group_cols) > 0 else []
    inner_group = group_cols[1] if len(group_cols) > 1 else []
sharkgene@qq.com's avatar
sharkgene@qq.com committed
296
297
else:
    outer_group = []
298
299
300
    inner_group = group_cols
key_cols = config.get('key_cols', [])
if len(key_cols) == 0:
sharkgene@qq.com's avatar
sharkgene@qq.com committed
301
    print(f"column key error")
sharkgene@qq.com's avatar
sharkgene@qq.com committed
302

303
304
305
306
307
308
309
metric_cols = config.get('metric_cols', [
    '平均首字延时TTFT(ms)', 
    '平均生成时间TPOT(ms)', 
    '生成吞吐量(tokens/s)', 
    '总吞吐量(tokens/s)' 
    ])

sharkgene@qq.com's avatar
sharkgene@qq.com committed
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
dist_combinations = df_renamed.groupby(dist_cols).size().reset_index()
print(f"\n将生成 {len(dist_combinations)} 个图表...")

chart_count = 0

for idx, (_, dist_row) in enumerate(dist_combinations.iterrows()):
    df_subset = df_renamed.copy()
    for dist_col in dist_cols:
        df_subset = df_subset[df_subset[dist_col] == dist_row[dist_col]]
    
    filter_parts = []
    for dist_col in dist_cols:
        val = dist_row[dist_col]
        safe_col_name = dist_col.replace('/', '_').replace('\\', '_')[:10]
        filter_parts.append(f"{safe_col_name}_{val}")
    
    output_filename = '_'.join(filter_parts) + ".png"
    output_path = os.path.join(args.输出目录, output_filename)
    
    print(f"[{idx+1}/{len(dist_combinations)}] 生成图表: {output_filename}")
sharkgene@qq.com's avatar
sharkgene@qq.com committed
330
    for c in metric_cols:
331
332
333
334
335
        df_subset[c] = pd.to_numeric(df_subset[c], errors='coerce').fillna(0)
        #try:
        #    df_subset[c] = df_subset[c].astype('float64')
        #except Exception as e:
        #    print(f"数据转换错误, 列名{c}, 错误信息{e}")
336
    success = generate_chart(df_subset, output_path, key_cols, outer_group, inner_group, metric_cols, args.合并分组)
sharkgene@qq.com's avatar
sharkgene@qq.com committed
337
338
339
340
341
    
    if success:
        chart_count += 1

print(f"\n完成!共生成 {chart_count} 个图表,保存到目录: {args.输出目录}")