|
| 1 | +import glob |
| 2 | +import os |
| 3 | +import re |
| 4 | + |
| 5 | +import matplotlib.pyplot as plt |
| 6 | +import pandas as pd |
| 7 | + |
| 8 | +# Set larger font sizes for all plot elements |
| 9 | +plt.rcParams.update( |
| 10 | + { |
| 11 | + "font.size": 14, |
| 12 | + "axes.titlesize": 18, |
| 13 | + "axes.labelsize": 16, |
| 14 | + "xtick.labelsize": 14, |
| 15 | + "ytick.labelsize": 14, |
| 16 | + "legend.fontsize": 12, |
| 17 | + "figure.titlesize": 20, |
| 18 | + } |
| 19 | +) |
| 20 | + |
| 21 | +RESULTS_DIR = "results" |
| 22 | +LOGS_DIR = "benchmark_logs" |
| 23 | +FIGURES_DIR = "figures" |
| 24 | + |
| 25 | +if not os.path.exists(FIGURES_DIR): |
| 26 | + os.makedirs(FIGURES_DIR) |
| 27 | + |
| 28 | +DATASETS = { |
| 29 | + "sift-128-euclidean": "SIFT-128-Euclidean", |
| 30 | + "glove-100-angular": "GloVe-100-Angular", |
| 31 | +} |
| 32 | + |
| 33 | +ALGORITHMS = { |
| 34 | + "jvector": "JVector", |
| 35 | + "faiss_hnsw": "FAISS HNSW Flat", |
| 36 | + "faiss_ivf_flat": "FAISS IVF Flat", |
| 37 | + "faiss_ivf_pq": "FAISS IVF PQ", |
| 38 | + "faiss_hnsw_pq": "FAISS HNSW PQ", |
| 39 | +} |
| 40 | + |
| 41 | + |
| 42 | +def parse_markdown_table(file_path): |
| 43 | + with open(file_path, "r") as f: |
| 44 | + lines = f.readlines() |
| 45 | + |
| 46 | + # Find the table |
| 47 | + table_lines = [line.strip() for line in lines if line.strip().startswith("|")] |
| 48 | + |
| 49 | + if not table_lines: |
| 50 | + return pd.DataFrame() |
| 51 | + |
| 52 | + # Parse header |
| 53 | + header = [c.strip() for c in table_lines[0].strip("|").split("|")] |
| 54 | + |
| 55 | + # Parse rows |
| 56 | + data = [] |
| 57 | + for line in table_lines[2:]: # Skip header and separator |
| 58 | + values = [c.strip() for c in line.strip("|").split("|")] |
| 59 | + if len(values) != len(header): |
| 60 | + continue |
| 61 | + row = dict(zip(header, values)) |
| 62 | + data.append(row) |
| 63 | + |
| 64 | + df = pd.DataFrame(data) |
| 65 | + |
| 66 | + # Convert numeric columns |
| 67 | + for col in df.columns: |
| 68 | + try: |
| 69 | + df[col] = pd.to_numeric(df[col]) |
| 70 | + except ValueError: |
| 71 | + pass |
| 72 | + |
| 73 | + return df |
| 74 | + |
| 75 | + |
| 76 | +def get_peak_memory(log_file): |
| 77 | + if not os.path.exists(log_file): |
| 78 | + return None |
| 79 | + try: |
| 80 | + df = pd.read_csv(log_file) |
| 81 | + return df["RSS_MB"].max() |
| 82 | + except Exception as e: |
| 83 | + print(f"Error reading log file {log_file}: {e}") |
| 84 | + return None |
| 85 | + |
| 86 | + |
| 87 | +def plot_dataset(dataset_key, dataset_name): |
| 88 | + plt.figure(figsize=(12, 8)) |
| 89 | + |
| 90 | + # Find all result files for this dataset |
| 91 | + # Pattern: benchmark_{algo}_{dataset}_{params}.md |
| 92 | + # But the filenames are like: benchmark_jvector_sift-128-euclidean_size_full.md |
| 93 | + # benchmark_faiss_sift-128-euclidean_hnsw_full.md |
| 94 | + |
| 95 | + # We need to map filename patterns to algorithms |
| 96 | + |
| 97 | + files = glob.glob(os.path.join(RESULTS_DIR, f"*{dataset_key}*.md")) |
| 98 | + |
| 99 | + colors = plt.cm.tab10.colors |
| 100 | + |
| 101 | + plot_data = [] |
| 102 | + |
| 103 | + for file_path in files: |
| 104 | + filename = os.path.basename(file_path) |
| 105 | + |
| 106 | + # Determine algorithm |
| 107 | + algo_name = "Unknown" |
| 108 | + is_jvector = False |
| 109 | + |
| 110 | + if "jvector" in filename: |
| 111 | + algo_name = "JVector" |
| 112 | + is_jvector = True |
| 113 | + log_pattern = f"jvector-*-full_*_memory.log" # Simplified pattern matching |
| 114 | + # Need to be more specific to match dataset |
| 115 | + if "euclidean" in dataset_key: |
| 116 | + log_pattern = "jvector-euclidean-full_*_memory.log" |
| 117 | + else: |
| 118 | + log_pattern = "jvector-angular-full_*_memory.log" |
| 119 | + |
| 120 | + elif "faiss" in filename: |
| 121 | + dataset_type = "euclidean" if "euclidean" in dataset_key else "angular" |
| 122 | + |
| 123 | + if "hnsw_pq" in filename: |
| 124 | + algo_name = "FAISS HNSW PQ" |
| 125 | + log_pattern = f"faiss-{dataset_type}-hnsw_pq-full_*_memory.log" |
| 126 | + elif "ivf_pq" in filename: |
| 127 | + algo_name = "FAISS IVF PQ" |
| 128 | + log_pattern = f"faiss-{dataset_type}-ivf_pq-full_*_memory.log" |
| 129 | + elif "ivf_flat" in filename: |
| 130 | + algo_name = "FAISS IVF Flat" |
| 131 | + log_pattern = f"faiss-{dataset_type}-ivf_flat-full_*_memory.log" |
| 132 | + elif "hnsw" in filename: # Check this last as hnsw_pq contains hnsw |
| 133 | + algo_name = "FAISS HNSW Flat" |
| 134 | + log_pattern = f"faiss-{dataset_type}-hnsw-full_*_memory.log" |
| 135 | + |
| 136 | + df = parse_markdown_table(file_path) |
| 137 | + if df.empty: |
| 138 | + continue |
| 139 | + |
| 140 | + # Get Peak Memory |
| 141 | + log_files = glob.glob(os.path.join(LOGS_DIR, log_pattern)) |
| 142 | + peak_mem = "N/A" |
| 143 | + if log_files: |
| 144 | + # Pick the most recent one or just the first one |
| 145 | + log_file = sorted(log_files)[-1] |
| 146 | + mem = get_peak_memory(log_file) |
| 147 | + if mem: |
| 148 | + peak_mem = f"{mem:.0f} MB" |
| 149 | + |
| 150 | + # Calculate Build Time |
| 151 | + # For JVector: Build + Warmup (Before) |
| 152 | + # For FAISS: Build |
| 153 | + # We take the mean build time if there are multiple rows, or just the first one |
| 154 | + # since build time is per index Actually, build time is constant for the same |
| 155 | + # build parameters. But here we might have different build parameters in the |
| 156 | + # same file (e.g. JVector has max_connections, beam_width). So Build Time |
| 157 | + # varies. We can't put a single Build Time in the legend if it varies. Let's |
| 158 | + # check if it varies significantly. For FAISS HNSW, Build Time depends on M and |
| 159 | + # efConstruction. So it varies. So we can't put it in the legend easily unless |
| 160 | + # we average it or show a range. Or maybe just "Avg Build: ...". |
| 161 | + |
| 162 | + if is_jvector: |
| 163 | + df["Total Build"] = 0.0 |
| 164 | + if "Build (s)" in df.columns: |
| 165 | + df["Total Build"] += df["Build (s)"] |
| 166 | + if "Warmup (s) (Before)" in df.columns: |
| 167 | + df["Total Build"] += df["Warmup (s) (Before)"] |
| 168 | + else: |
| 169 | + df["Total Build"] = 0.0 |
| 170 | + if "Build (s)" in df.columns: |
| 171 | + df["Total Build"] += df["Build (s)"] |
| 172 | + |
| 173 | + avg_build = df["Total Build"].mean() |
| 174 | + build_str = f"{avg_build:.1f}s" |
| 175 | + |
| 176 | + # Prepare data for plotting |
| 177 | + # We want the Pareto frontier (best recall for given latency or best latency for |
| 178 | + # given recall) |
| 179 | + # But simply plotting all points is also fine to see the spread. |
| 180 | + # Usually benchmarks plot the line connecting the best points. |
| 181 | + |
| 182 | + # Sort by Recall |
| 183 | + df = df.sort_values(by="Recall (Before)") |
| 184 | + |
| 185 | + recall = df["Recall (Before)"] |
| 186 | + latency = df["Latency (ms) (Before)"] |
| 187 | + |
| 188 | + # Filter out very bad points if necessary, but let's plot all first. |
| 189 | + |
| 190 | + label = f"{algo_name} (Mem: {peak_mem}, Build: ~{build_str})" |
| 191 | + |
| 192 | + print(f" {algo_name}: Peak Mem={peak_mem}, Avg Build={build_str}") |
| 193 | + |
| 194 | + plot_data.append( |
| 195 | + { |
| 196 | + "recall": recall, |
| 197 | + "latency": latency, |
| 198 | + "label": label, |
| 199 | + "avg_build": avg_build, |
| 200 | + } |
| 201 | + ) |
| 202 | + |
| 203 | + # Sort by avg_build descending |
| 204 | + plot_data.sort(key=lambda x: x["avg_build"], reverse=True) |
| 205 | + |
| 206 | + for data in plot_data: |
| 207 | + # Plot points |
| 208 | + plt.plot( |
| 209 | + data["recall"], |
| 210 | + data["latency"], |
| 211 | + "o", |
| 212 | + label=data["label"], |
| 213 | + markersize=8, |
| 214 | + alpha=0.7, |
| 215 | + ) |
| 216 | + |
| 217 | + # Add dashed lines for Recall |
| 218 | + for r in [0.80, 0.85, 0.90, 0.95]: |
| 219 | + plt.axvline(x=r, color="gray", linestyle="--", alpha=0.5) |
| 220 | + plt.text( |
| 221 | + r, plt.ylim()[1] * 0.01, f"{r}", rotation=90, verticalalignment="bottom" |
| 222 | + ) |
| 223 | + |
| 224 | + plt.title(f"Recall vs Latency - {dataset_name} Dataset") |
| 225 | + plt.xlabel("Recall@10 (Higher is Better)") |
| 226 | + plt.ylabel("Latency (ms) (Lower is Better)") |
| 227 | + plt.grid(True, which="both", ls="-", alpha=0.2) |
| 228 | + plt.legend() |
| 229 | + plt.yscale("log") # Latency often spans orders of magnitude |
| 230 | + |
| 231 | + # Save plot |
| 232 | + output_png = os.path.join(FIGURES_DIR, f"plot_{dataset_key}.png") |
| 233 | + output_pdf = os.path.join(FIGURES_DIR, f"plot_{dataset_key}.pdf") |
| 234 | + plt.savefig(output_png) |
| 235 | + plt.savefig(output_pdf) |
| 236 | + print(f"Saved plots to {output_png} and {output_pdf}") |
| 237 | + |
| 238 | + |
| 239 | +def main(): |
| 240 | + for key, name in DATASETS.items(): |
| 241 | + print(f"Processing {name} dataset...") |
| 242 | + plot_dataset(key, name) |
| 243 | + |
| 244 | + |
| 245 | +if __name__ == "__main__": |
| 246 | + main() |
0 commit comments