|
| 1 | +""" |
| 2 | +# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +""" |
| 16 | + |
| 17 | +import argparse |
| 18 | +import json |
| 19 | +import os |
| 20 | +import sys |
| 21 | + |
| 22 | +import matplotlib.pyplot as plt |
| 23 | +import numpy as np |
| 24 | + |
| 25 | + |
| 26 | +def load_jsonl(file_path: str) -> list[dict]: |
| 27 | + records = [] |
| 28 | + with open(file_path, encoding="utf-8") as f: |
| 29 | + for line in f: |
| 30 | + line = line.strip() |
| 31 | + if line: |
| 32 | + records.append(json.loads(line)) |
| 33 | + return records |
| 34 | + |
| 35 | + |
| 36 | +_THROUGHPUT_KEYS = ["request_throughput", "output_throughput", "total_throughput"] |
| 37 | + |
| 38 | + |
| 39 | +def detect_metrics(records: list[dict]) -> list[str]: |
| 40 | + """Detect metric names from JSONL records (throughput scalars + dict-valued keys).""" |
| 41 | + throughput_found = set() |
| 42 | + dict_metrics = [] |
| 43 | + |
| 44 | + for rec in records: |
| 45 | + for k in _THROUGHPUT_KEYS: |
| 46 | + if k in rec: |
| 47 | + throughput_found.add(k) |
| 48 | + if not dict_metrics: |
| 49 | + for k, v in rec.items(): |
| 50 | + if isinstance(v, dict): |
| 51 | + dict_metrics.append(k) |
| 52 | + if len(throughput_found) == len(_THROUGHPUT_KEYS) and dict_metrics: |
| 53 | + break |
| 54 | + |
| 55 | + metrics = [k for k in _THROUGHPUT_KEYS if k in throughput_found] |
| 56 | + metrics.extend(dict_metrics) |
| 57 | + return metrics |
| 58 | + |
| 59 | + |
| 60 | +def plot_metric(records: list[dict], metric: str, output_path: str): |
| 61 | + """Plot a single metric for a chunk of records.""" |
| 62 | + stat_keys = [] |
| 63 | + for rec in records: |
| 64 | + val = rec.get(metric) |
| 65 | + if isinstance(val, dict): |
| 66 | + stat_keys = list(val.keys()) |
| 67 | + break |
| 68 | + |
| 69 | + if not stat_keys: |
| 70 | + values = [rec.get(metric) for rec in records if rec.get(metric) is not None] |
| 71 | + if not values: |
| 72 | + return |
| 73 | + x = np.arange(len(values)) |
| 74 | + plt.figure(figsize=(12, 6)) |
| 75 | + plt.plot(x, values, linewidth=2, label=metric) |
| 76 | + plt.xlabel("Request Index") |
| 77 | + plt.ylabel(metric) |
| 78 | + plt.title(f"{metric} over requests") |
| 79 | + plt.legend() |
| 80 | + plt.grid(True, alpha=0.3) |
| 81 | + plt.tight_layout() |
| 82 | + plt.savefig(output_path, dpi=150) |
| 83 | + plt.close() |
| 84 | + print(f"Saved: {output_path}") |
| 85 | + return |
| 86 | + |
| 87 | + plt.figure(figsize=(12, 6)) |
| 88 | + |
| 89 | + for key in stat_keys: |
| 90 | + values = [] |
| 91 | + for rec in records: |
| 92 | + val = rec.get(metric) |
| 93 | + if isinstance(val, dict) and key in val: |
| 94 | + values.append(val[key]) |
| 95 | + else: |
| 96 | + values.append(None) |
| 97 | + |
| 98 | + valid_x = [i for i, v in enumerate(values) if v is not None] |
| 99 | + valid_v = [v for v in values if v is not None] |
| 100 | + |
| 101 | + if not valid_v: |
| 102 | + continue |
| 103 | + |
| 104 | + linestyle = "-" if key == "mean" else "--" |
| 105 | + lw = 2 if key == "mean" else 1.5 |
| 106 | + plt.plot(valid_x, valid_v, linewidth=lw, linestyle=linestyle, label=key) |
| 107 | + |
| 108 | + plt.xlabel("Request Index") |
| 109 | + unit = "" |
| 110 | + if metric.endswith("_ms"): |
| 111 | + unit = " (ms)" |
| 112 | + elif metric in ("s_decode",): |
| 113 | + unit = " (tok/s)" |
| 114 | + elif metric == "request_throughput": |
| 115 | + unit = " (req/s)" |
| 116 | + elif metric in ("output_throughput", "total_throughput"): |
| 117 | + unit = " (tok/s)" |
| 118 | + plt.ylabel(f"{metric}{unit}") |
| 119 | + plt.title(f"{metric} over requests") |
| 120 | + plt.legend() |
| 121 | + plt.grid(True, alpha=0.3) |
| 122 | + plt.tight_layout() |
| 123 | + plt.savefig(output_path, dpi=150) |
| 124 | + plt.close() |
| 125 | + print(f"Saved: {output_path}") |
| 126 | + |
| 127 | + |
| 128 | +def main(): |
| 129 | + parser = argparse.ArgumentParser( |
| 130 | + description="Plot benchmark metrics from JSONL file. " |
| 131 | + "Metrics and window_size are read from the data automatically. " |
| 132 | + "Records are grouped into window-sized chunks for per-step analysis." |
| 133 | + ) |
| 134 | + parser.add_argument( |
| 135 | + "--file", |
| 136 | + type=str, |
| 137 | + default=None, |
| 138 | + help="Path to benchmark_metrics.jsonl. Defaults to $FD_LOG_DIR/benchmark_metrics.jsonl", |
| 139 | + ) |
| 140 | + parser.add_argument( |
| 141 | + "--output-dir", |
| 142 | + type=str, |
| 143 | + default=None, |
| 144 | + help="Directory to save output PNG files. Defaults to $FD_LOG_DIR/benchmark_plots/", |
| 145 | + ) |
| 146 | + args = parser.parse_args() |
| 147 | + |
| 148 | + log_dir = os.environ.get("FD_LOG_DIR", "./log") |
| 149 | + |
| 150 | + if args.file: |
| 151 | + file_path = args.file |
| 152 | + else: |
| 153 | + file_path = os.path.join(log_dir, "benchmark_metrics.jsonl") |
| 154 | + |
| 155 | + if not os.path.exists(file_path): |
| 156 | + print(f"File not found: {file_path}", file=sys.stderr) |
| 157 | + sys.exit(1) |
| 158 | + |
| 159 | + output_dir = args.output_dir if args.output_dir else os.path.join(log_dir, "benchmark_plots") |
| 160 | + |
| 161 | + records = load_jsonl(file_path) |
| 162 | + if not records: |
| 163 | + print("No data in file.", file=sys.stderr) |
| 164 | + sys.exit(1) |
| 165 | + |
| 166 | + window_size = records[0].get("window_size", 0) |
| 167 | + metrics = detect_metrics(records) |
| 168 | + |
| 169 | + if not metrics: |
| 170 | + print("No plottable metrics found in data.", file=sys.stderr) |
| 171 | + sys.exit(1) |
| 172 | + |
| 173 | + print(f"Loaded {len(records)} records from {file_path}") |
| 174 | + print(f"Window size: {window_size or 'all'}") |
| 175 | + print(f"Metrics: {', '.join(metrics)}") |
| 176 | + |
| 177 | + if window_size > 0: |
| 178 | + num_chunks = (len(records) + window_size - 1) // window_size |
| 179 | + chunks = [] |
| 180 | + for i in range(num_chunks): |
| 181 | + start = i * window_size |
| 182 | + end = min(start + window_size, len(records)) |
| 183 | + chunks.append(records[start:end]) |
| 184 | + print(f"Split into {num_chunks} step(s) of size {window_size}") |
| 185 | + else: |
| 186 | + chunks = [records] |
| 187 | + |
| 188 | + os.makedirs(output_dir, exist_ok=True) |
| 189 | + |
| 190 | + for step_idx, chunk in enumerate(chunks): |
| 191 | + if len(chunks) > 1: |
| 192 | + step_dir = os.path.join(output_dir, f"step_{step_idx + 1}") |
| 193 | + os.makedirs(step_dir, exist_ok=True) |
| 194 | + else: |
| 195 | + step_dir = output_dir |
| 196 | + |
| 197 | + for metric in metrics: |
| 198 | + output_path = os.path.join(step_dir, f"{metric}.png") |
| 199 | + plot_metric(chunk, metric, output_path) |
| 200 | + |
| 201 | + |
| 202 | +if __name__ == "__main__": |
| 203 | + main() |
0 commit comments