|
| 1 | +import json |
| 2 | +import os |
| 3 | +from dataclasses import dataclass |
| 4 | +from datetime import datetime |
| 5 | +from pathlib import Path |
| 6 | +from time import time |
| 7 | + |
| 8 | +import requests |
| 9 | +from tqdm import tqdm |
| 10 | +from valor_lite.classification import DataLoader, MetricType |
| 11 | + |
| 12 | + |
| 13 | +def time_it(fn): |
| 14 | + def wrapper(*args, **kwargs): |
| 15 | + start = time() |
| 16 | + results = fn(*args, **kwargs) |
| 17 | + return (time() - start, results) |
| 18 | + |
| 19 | + return wrapper |
| 20 | + |
| 21 | + |
| 22 | +def download_data_if_not_exists( |
| 23 | + file_name: str, |
| 24 | + file_path: Path, |
| 25 | + url: str, |
| 26 | +): |
| 27 | + """Download the data from a public bucket if it doesn't exist locally.""" |
| 28 | + |
| 29 | + if not os.path.exists(file_path): |
| 30 | + response = requests.get(url, stream=True) |
| 31 | + if response.status_code == 200: |
| 32 | + total_size = int(response.headers.get("content-length", 0)) |
| 33 | + with open(file_path, "wb") as f: |
| 34 | + with tqdm( |
| 35 | + total=total_size, |
| 36 | + unit="B", |
| 37 | + unit_scale=True, |
| 38 | + unit_divisor=1024, |
| 39 | + desc=file_name, |
| 40 | + ) as pbar: |
| 41 | + for chunk in response.iter_content(chunk_size=1024): |
| 42 | + if chunk: |
| 43 | + f.write(chunk) |
| 44 | + pbar.update(1024) |
| 45 | + else: |
| 46 | + raise RuntimeError(response) |
| 47 | + else: |
| 48 | + print(f"{file_name} already exists locally.") |
| 49 | + |
| 50 | + |
| 51 | +def write_results_to_file(write_path: Path, results: list[dict]): |
| 52 | + """Write results to results.json""" |
| 53 | + current_datetime = datetime.now().strftime("%d/%m/%Y %H:%M:%S") |
| 54 | + if os.path.isfile(write_path): |
| 55 | + with open(write_path, "r") as file: |
| 56 | + file.seek(0) |
| 57 | + data = json.load(file) |
| 58 | + else: |
| 59 | + data = {} |
| 60 | + |
| 61 | + data[current_datetime] = results |
| 62 | + |
| 63 | + with open(write_path, "w+") as file: |
| 64 | + json.dump(data, file, indent=4) |
| 65 | + |
| 66 | + |
| 67 | +@time_it |
| 68 | +def ingest( |
| 69 | + loader: DataLoader, |
| 70 | + gt_path: Path, |
| 71 | + pd_path: Path, |
| 72 | + limit: int, |
| 73 | + chunk_size: int, |
| 74 | +): |
| 75 | + accumulated_time = 0.0 |
| 76 | + with open(gt_path, "r") as gf: |
| 77 | + with open(pd_path, "r") as pf: |
| 78 | + count = 0 |
| 79 | + groundtruths = [] |
| 80 | + predictions = [] |
| 81 | + for gline, pline in zip(gf, pf): |
| 82 | + |
| 83 | + # groundtruth |
| 84 | + gt_dict = json.loads(gline) |
| 85 | + groundtruths.append(gt_dict) |
| 86 | + |
| 87 | + # prediction |
| 88 | + pd_dict = json.loads(pline) |
| 89 | + predictions.append(pd_dict) |
| 90 | + |
| 91 | + count += 1 |
| 92 | + if count >= limit and limit > 0: |
| 93 | + break |
| 94 | + elif len(groundtruths) < chunk_size or chunk_size == -1: |
| 95 | + continue |
| 96 | + |
| 97 | + timer, _ = time_it(loader.add_data_from_valor_dict)( |
| 98 | + zip(groundtruths, predictions), True |
| 99 | + ) |
| 100 | + accumulated_time += timer |
| 101 | + groundtruths = [] |
| 102 | + predictions = [] |
| 103 | + |
| 104 | + if groundtruths: |
| 105 | + timer, _ = time_it(loader.add_data_from_valor_dict)( |
| 106 | + zip(groundtruths, predictions), True |
| 107 | + ) |
| 108 | + accumulated_time += timer |
| 109 | + |
| 110 | + return accumulated_time |
| 111 | + |
| 112 | + |
| 113 | +@dataclass |
| 114 | +class Benchmark: |
| 115 | + limit: int |
| 116 | + n_datums: int |
| 117 | + n_groundtruths: int |
| 118 | + n_predictions: int |
| 119 | + n_labels: int |
| 120 | + chunk_size: int |
| 121 | + ingestion: float |
| 122 | + preprocessing: float |
| 123 | + precomputation: float |
| 124 | + evaluation: float |
| 125 | + detailed_evaluation: list[tuple[int, float]] |
| 126 | + |
| 127 | + def result(self) -> dict: |
| 128 | + return { |
| 129 | + "limit": self.limit, |
| 130 | + "n_datums": self.n_datums, |
| 131 | + "n_groundtruths": self.n_groundtruths, |
| 132 | + "n_predictions": self.n_predictions, |
| 133 | + "n_labels": self.n_labels, |
| 134 | + "chunk_size": self.chunk_size, |
| 135 | + "ingestion": { |
| 136 | + "loading_from_file": f"{round(self.ingestion - self.preprocessing, 2)} seconds", |
| 137 | + "numpy_conversion": f"{round(self.preprocessing, 2)} seconds", |
| 138 | + "finalization": f"{round(self.precomputation, 2)} seconds", |
| 139 | + "total": f"{round(self.ingestion + self.precomputation, 2)} seconds", |
| 140 | + }, |
| 141 | + "base_evaluation": f"{round(self.evaluation, 2)} seconds", |
| 142 | + "detailed_evaluation": [ |
| 143 | + { |
| 144 | + "n_points": 10, |
| 145 | + "n_examples": curve[0], |
| 146 | + "computation": f"{round(curve[1], 2)} seconds", |
| 147 | + } |
| 148 | + for curve in self.detailed_evaluation |
| 149 | + ], |
| 150 | + } |
| 151 | + |
| 152 | + |
| 153 | +def run_benchmarking_analysis( |
| 154 | + limits_to_test: list[int], |
| 155 | + results_file: str = "clf_results.json", |
| 156 | + chunk_size: int = -1, |
| 157 | + ingestion_timeout=30, |
| 158 | + evaluation_timeout=30, |
| 159 | +): |
| 160 | + """Time various function calls and export the results.""" |
| 161 | + current_directory = Path(__file__).parent |
| 162 | + write_path = current_directory / Path(results_file) |
| 163 | + |
| 164 | + gt_filename = "gt_classification.jsonl" |
| 165 | + pd_filename = "pd_classification.jsonl" |
| 166 | + |
| 167 | + # cache data locally |
| 168 | + for filename in [gt_filename, pd_filename]: |
| 169 | + file_path = current_directory / Path(filename) |
| 170 | + url = f"https://pub-fae71003f78140bdaedf32a7c8d331d2.r2.dev/{filename}" |
| 171 | + download_data_if_not_exists( |
| 172 | + file_name=filename, file_path=file_path, url=url |
| 173 | + ) |
| 174 | + |
| 175 | + # iterate through datum limits |
| 176 | + results = list() |
| 177 | + for limit in limits_to_test: |
| 178 | + |
| 179 | + # === Base Evaluation === |
| 180 | + loader = DataLoader() |
| 181 | + |
| 182 | + # ingest + preprocess |
| 183 | + (ingest_time, preprocessing_time,) = ingest( |
| 184 | + loader=loader, |
| 185 | + gt_path=current_directory / Path(gt_filename), |
| 186 | + pd_path=current_directory / Path(pd_filename), |
| 187 | + limit=limit, |
| 188 | + chunk_size=chunk_size, |
| 189 | + ) # type: ignore - time_it wrapper |
| 190 | + |
| 191 | + finalization_time, evaluator = time_it(loader.finalize)() |
| 192 | + |
| 193 | + if ingest_time > ingestion_timeout and ingestion_timeout != -1: |
| 194 | + raise TimeoutError( |
| 195 | + f"Base precomputation timed out with limit of {limit}." |
| 196 | + ) |
| 197 | + |
| 198 | + # evaluate |
| 199 | + eval_time, _ = time_it(evaluator.evaluate)() |
| 200 | + if eval_time > evaluation_timeout and evaluation_timeout != -1: |
| 201 | + raise TimeoutError( |
| 202 | + f"Base evaluation timed out with {evaluator.n_datums} datums." |
| 203 | + ) |
| 204 | + |
| 205 | + detail_no_examples_time, _ = time_it(evaluator.evaluate)( |
| 206 | + metrics_to_return=[*MetricType.base(), MetricType.ConfusionMatrix], |
| 207 | + ) |
| 208 | + if ( |
| 209 | + detail_no_examples_time > evaluation_timeout |
| 210 | + and evaluation_timeout != -1 |
| 211 | + ): |
| 212 | + raise TimeoutError( |
| 213 | + f"Base evaluation timed out with {evaluator.n_datums} datums." |
| 214 | + ) |
| 215 | + |
| 216 | + detail_three_examples_time, _ = time_it(evaluator.evaluate)( |
| 217 | + metrics_to_return=[*MetricType.base(), MetricType.ConfusionMatrix], |
| 218 | + number_of_examples=3, |
| 219 | + ) |
| 220 | + if ( |
| 221 | + detail_three_examples_time > evaluation_timeout |
| 222 | + and evaluation_timeout != -1 |
| 223 | + ): |
| 224 | + raise TimeoutError( |
| 225 | + f"Base evaluation timed out with {evaluator.n_datums} datums." |
| 226 | + ) |
| 227 | + |
| 228 | + results.append( |
| 229 | + Benchmark( |
| 230 | + limit=limit, |
| 231 | + n_datums=evaluator.n_datums, |
| 232 | + n_groundtruths=evaluator.n_groundtruths, |
| 233 | + n_predictions=evaluator.n_predictions, |
| 234 | + n_labels=evaluator.n_labels, |
| 235 | + chunk_size=chunk_size, |
| 236 | + ingestion=ingest_time, |
| 237 | + preprocessing=preprocessing_time, |
| 238 | + precomputation=finalization_time, |
| 239 | + evaluation=eval_time, |
| 240 | + detailed_evaluation=[ |
| 241 | + (0, detail_no_examples_time), |
| 242 | + (3, detail_three_examples_time), |
| 243 | + ], |
| 244 | + ).result() |
| 245 | + ) |
| 246 | + |
| 247 | + write_results_to_file(write_path=write_path, results=results) |
| 248 | + |
| 249 | + |
| 250 | +if __name__ == "__main__": |
| 251 | + |
| 252 | + run_benchmarking_analysis( |
| 253 | + limits_to_test=[5000, 5000, 5000], |
| 254 | + ) |
0 commit comments