specbench-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,379 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import io
5
+ import re
6
+ import shlex
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ import tarfile
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+
14
+ from importlib.metadata import PackageNotFoundError, version as pkg_version
15
+
16
+ from rich.console import Console
17
+ from rich.panel import Panel
18
+
19
+ from speculation_benchmark.config import BenchmarkConfig
20
+
21
+ DEFAULT_HF_JOBS_IMAGE = "ghcr.io/ggml-org/llama.cpp:server-cuda"
22
+ DEFAULT_HF_JOBS_FLAVOR = "l40sx1"
23
+ DEFAULT_HF_JOBS_TIMEOUT = "2h"
24
+ DEFAULT_REMOTE_LLAMA_CMD = "/app/llama-server"
25
+ DEFAULT_PYPI_PACKAGE = "specbench-cli"
26
+
27
+ REPO_ROOT = Path(__file__).resolve().parents[2]
28
+ MAX_INLINE_BUNDLE_B64_BYTES = 110_000 # stay safely under Linux MAX_ARG_STRLEN (128 KiB)
29
+
30
+
31
+ @dataclass
32
+ class HFJobOptions:
33
+ """Configuration for launching a `specbench` run on Hugging Face Jobs."""
34
+
35
+ flavor: str = DEFAULT_HF_JOBS_FLAVOR
36
+ timeout: str = DEFAULT_HF_JOBS_TIMEOUT
37
+ image: str = DEFAULT_HF_JOBS_IMAGE
38
+ remote_llama_cmd: str = DEFAULT_REMOTE_LLAMA_CMD
39
+ package_source: str | None = None
40
+ detach: bool = False
41
+ namespace: str | None = None
42
+ volumes: list[str] = field(default_factory=list)
43
+ env: list[str] = field(default_factory=list)
44
+ labels: list[str] = field(default_factory=list)
45
+ plot_dir: str | None = None
46
+ allow_dry_run: bool = False
47
+
48
+
49
+ def _extract_mount_paths(volumes: list[str]) -> list[str]:
50
+ paths: list[str] = []
51
+ for spec in volumes:
52
+ # Format: hf://[TYPE/]SOURCE:/MOUNT_PATH[:ro]
53
+ parts = spec.split(":")
54
+ # "hf" + "//..." + "/mount" (+ optional "ro")
55
+ if len(parts) >= 3:
56
+ mount = parts[2].strip()
57
+ if mount:
58
+ paths.append(mount.rstrip("/"))
59
+ return paths
60
+
61
+
62
+ def _is_remote_or_mounted_suite(source: str, mount_paths: list[str]) -> bool:
63
+ s = source.strip()
64
+ if s.startswith(("preset:", "hf:")):
65
+ return True
66
+ for mp in mount_paths:
67
+ if s == mp or s.startswith(mp + "/"):
68
+ return True
69
+ return False
70
+
71
+
72
+ def validate_hf_job_config(cfg: BenchmarkConfig, job: HFJobOptions) -> None:
73
+ """Fail fast locally before launching a paid cloud GPU job."""
74
+ mount_paths = _extract_mount_paths(job.volumes)
75
+
76
+ if cfg.output.dry_run and not job.allow_dry_run and not mount_paths:
77
+ raise ValueError(
78
+ "HF Jobs containers are ephemeral: --dry-run would discard all results on exit. "
79
+ "Drop --dry-run to push to --hf-dataset, mount a bucket via --volume hf://buckets/<user>/<bucket>:/out, "
80
+ "or pass --allow-dry-run to override."
81
+ )
82
+
83
+ if not cfg.output.dry_run and not cfg.output.hf_dataset_repo:
84
+ raise ValueError(
85
+ "Provide --hf-dataset <user/repo> so results are persisted to Hugging Face Hub from the Job."
86
+ )
87
+
88
+ for s in cfg.suites:
89
+ if not _is_remote_or_mounted_suite(s.source, mount_paths):
90
+ raise ValueError(
91
+ f"Suite {s.capability!r} points to local path {s.source!r}, which will not exist inside the HF Job container. "
92
+ "Use a built-in preset (e.g. coding, multimodal, knowledge_work), an 'hf:<dataset>' source, "
93
+ "or mount the file via --volume hf://buckets/<user>/<bucket>:/data."
94
+ )
95
+
96
+ if job.plot_dir and mount_paths:
97
+ norm_plot = job.plot_dir.rstrip("/")
98
+ if not any(norm_plot == mp or norm_plot.startswith(mp + "/") for mp in mount_paths):
99
+ raise ValueError(
100
+ f"--plot-dir {job.plot_dir!r} is outside mounted volumes {mount_paths}; "
101
+ "charts written outside a mounted bucket volume will not persist after the Job ends."
102
+ )
103
+
104
+
105
+ def build_remote_specbench_args(
106
+ cfg: BenchmarkConfig,
107
+ *,
108
+ remote_llama_cmd: str = DEFAULT_REMOTE_LLAMA_CMD,
109
+ ) -> list[str]:
110
+ """Serialize a validated BenchmarkConfig into `specbench run` CLI arguments for the Job container."""
111
+ args: list[str] = [
112
+ "run",
113
+ "--model-repo",
114
+ cfg.model.model_repo,
115
+ "--llama-cmd",
116
+ remote_llama_cmd,
117
+ ]
118
+ if cfg.model.speculator_repo:
119
+ args.extend(["--speculator-repo", cfg.model.speculator_repo])
120
+ if cfg.model.speculator_file:
121
+ args.extend(["--speculator-file", cfg.model.speculator_file])
122
+ if cfg.model.spec_type:
123
+ args.extend(["--spec-type", cfg.model.spec_type])
124
+ if cfg.model.model_quant:
125
+ args.extend(["--model-quant", cfg.model.model_quant])
126
+ if cfg.model.speculator_quant:
127
+ args.extend(["--speculator-quant", cfg.model.speculator_quant])
128
+ if cfg.model.no_mmproj:
129
+ args.append("--no-mmproj")
130
+
131
+ args.extend(["--draft-tokens", ",".join(str(x) for x in cfg.draft_tokens)])
132
+
133
+ for s in cfg.suites:
134
+ args.extend(["--suite", f"{s.capability}={s.source}"])
135
+
136
+ limits = {s.limit for s in cfg.suites if s.limit is not None}
137
+ if len(limits) == 1:
138
+ args.extend(["--limit", str(next(iter(limits)))])
139
+ elif cfg.suites and cfg.suites[0].limit is not None:
140
+ args.extend(["--limit", str(cfg.suites[0].limit)])
141
+
142
+ args.extend(["--max-tokens", str(cfg.generation.max_tokens)])
143
+ args.extend(["--temperature", str(cfg.generation.temperature)])
144
+
145
+ if cfg.server.ctx_size is not None:
146
+ args.extend(["--ctx-size", str(cfg.server.ctx_size)])
147
+ if cfg.server.port:
148
+ args.extend(["--port", str(cfg.server.port)])
149
+ for raw_arg in cfg.server.extra_args:
150
+ args.extend(["--llama-arg", raw_arg])
151
+
152
+ if cfg.output.hf_dataset_repo:
153
+ args.extend(["--hf-dataset", cfg.output.hf_dataset_repo])
154
+ if cfg.output.output_dir and str(cfg.output.output_dir) != "results":
155
+ args.extend(["--output-dir", str(cfg.output.output_dir)])
156
+ if cfg.output.private:
157
+ args.append("--private")
158
+ if not cfg.output.append:
159
+ args.append("--overwrite")
160
+ if cfg.output.dry_run:
161
+ args.append("--dry-run")
162
+ if cfg.run_id:
163
+ args.extend(["--run-id", cfg.run_id])
164
+
165
+ return args
166
+
167
+
168
+ def bundle_local_package(repo_root: Path | None = None) -> str:
169
+ """Pack `pyproject.toml`, `README.md`, `src/speculation_benchmark`, and `suites` into a base64 tar.gz."""
170
+ root = repo_root or REPO_ROOT
171
+ required = [root / "pyproject.toml", root / "README.md", root / "src" / "speculation_benchmark"]
172
+ missing = [str(p) for p in required if not p.exists()]
173
+ if missing:
174
+ raise FileNotFoundError(
175
+ f"Cannot bundle local package (missing: {', '.join(missing)}). "
176
+ "Pass --package-source <git-url-or-pypi-pkg> instead."
177
+ )
178
+
179
+ def _tar_filter(info: tarfile.TarInfo) -> tarfile.TarInfo | None:
180
+ parts = Path(info.name).parts
181
+ if "__pycache__" in parts or info.name.endswith((".pyc", ".pyo")):
182
+ return None
183
+ return info
184
+
185
+ buf = io.BytesIO()
186
+ with tarfile.open(fileobj=buf, mode="w:gz", compresslevel=9) as tf:
187
+ tf.add(root / "pyproject.toml", arcname="pyproject.toml")
188
+ tf.add(root / "README.md", arcname="README.md")
189
+ tf.add(root / "src" / "speculation_benchmark", arcname="src/speculation_benchmark", filter=_tar_filter)
190
+ suites_dir = root / "suites"
191
+ if suites_dir.is_dir():
192
+ tf.add(suites_dir, arcname="suites", filter=_tar_filter)
193
+
194
+ encoded = base64.b64encode(buf.getvalue()).decode("ascii")
195
+ if len(encoded) > MAX_INLINE_BUNDLE_B64_BYTES:
196
+ raise ValueError(
197
+ f"Local package bundle is {len(encoded)} bytes (> {MAX_INLINE_BUNDLE_B64_BYTES} bytes limit for inline env). "
198
+ "Push the repo and pass --package-source git+https://github.com/merveenoyan/specbench.git."
199
+ )
200
+ return encoded
201
+
202
+
203
+ def _sanitize_label_value(raw: str) -> str:
204
+ cleaned = re.sub(r"[^A-Za-z0-9_.-]+", "-", raw.split("/")[-1]).strip("-._")
205
+ return (cleaned or "model")[:63]
206
+
207
+
208
+ def resolve_hf_cli_binary() -> str:
209
+ """Locate the `hf` CLI binary, preferring the current Python environment's bin dir."""
210
+ venv_hf = Path(sys.executable).resolve().parent / "hf"
211
+ if venv_hf.is_file():
212
+ return str(venv_hf)
213
+ found = shutil.which("hf")
214
+ if found:
215
+ return found
216
+ raise FileNotFoundError(
217
+ "Hugging Face CLI (`hf`) not found on PATH. Install it via `uv sync` or `curl -LsSf https://hf.co/cli/install.sh | bash -s`."
218
+ )
219
+
220
+
221
+ def _has_local_source_tree(repo_root: Path | None = None) -> bool:
222
+ root = repo_root or REPO_ROOT
223
+ return all(
224
+ (root / rel).exists()
225
+ for rel in ("pyproject.toml", "README.md", Path("src") / "speculation_benchmark")
226
+ )
227
+
228
+
229
+ def resolve_hf_job_package_source(
230
+ package_source: str | None,
231
+ *,
232
+ repo_root: Path | None = None,
233
+ ) -> str | None:
234
+ """Resolve the package source for HF Jobs: explicit override, local bundle (`None`), or installed PyPI version."""
235
+ if package_source:
236
+ return package_source
237
+ if _has_local_source_tree(repo_root=repo_root):
238
+ return None
239
+ try:
240
+ installed = pkg_version(DEFAULT_PYPI_PACKAGE)
241
+ return f"{DEFAULT_PYPI_PACKAGE}=={installed}"
242
+ except PackageNotFoundError:
243
+ return DEFAULT_PYPI_PACKAGE
244
+
245
+
246
+ def build_hf_jobs_command(
247
+ cfg: BenchmarkConfig,
248
+ job: HFJobOptions,
249
+ *,
250
+ hf_bin: str = "hf",
251
+ repo_root: Path | None = None,
252
+ ) -> list[str]:
253
+ """Build the complete `hf jobs run ...` command to execute `specbench` on a cloud GPU."""
254
+ validate_hf_job_config(cfg, job)
255
+
256
+ resolved_pkg_source = resolve_hf_job_package_source(job.package_source, repo_root=repo_root)
257
+ remote_args = build_remote_specbench_args(cfg, remote_llama_cmd=job.remote_llama_cmd)
258
+ remote_args_str = shlex.join(remote_args)
259
+
260
+ plot_snippet = ""
261
+ if job.plot_dir:
262
+ plot_src = cfg.output.hf_dataset_repo if not cfg.output.dry_run and cfg.output.hf_dataset_repo else str(cfg.output.output_dir)
263
+ plot_cmd_parts = ["plot", plot_src, "--output-dir", job.plot_dir]
264
+ if cfg.run_id:
265
+ plot_cmd_parts.extend(["--run-ids", cfg.run_id])
266
+ plot_args_str = shlex.join(plot_cmd_parts)
267
+ if resolved_pkg_source:
268
+ plot_snippet = f"\nuvx --python 3.12 --from {shlex.quote(resolved_pkg_source)} specbench {plot_args_str}"
269
+ else:
270
+ plot_snippet = f"\nuv run --python 3.12 specbench {plot_args_str}"
271
+
272
+ cmd: list[str] = [
273
+ hf_bin,
274
+ "jobs",
275
+ "run",
276
+ "--flavor",
277
+ job.flavor,
278
+ "--timeout",
279
+ job.timeout,
280
+ "--secrets",
281
+ "HF_TOKEN",
282
+ "--env",
283
+ "PYTHONUNBUFFERED=1",
284
+ "--label",
285
+ "app=specbench",
286
+ "--label",
287
+ f"model={_sanitize_label_value(cfg.model.model_repo)}",
288
+ ]
289
+
290
+ if job.namespace:
291
+ cmd.extend(["--namespace", job.namespace])
292
+ if job.detach:
293
+ cmd.append("--detach")
294
+ for vol in job.volumes:
295
+ cmd.extend(["--volume", vol])
296
+ for extra_env in job.env:
297
+ cmd.extend(["--env", extra_env])
298
+ for extra_label in job.labels:
299
+ cmd.extend(["--label", extra_label])
300
+
301
+ uv_bootstrap = (
302
+ "set -euo pipefail\n"
303
+ 'export LD_LIBRARY_PATH="/app:${LD_LIBRARY_PATH:-}"\n'
304
+ 'if ! command -v uv >/dev/null 2>&1; then\n'
305
+ ' curl -LsSf https://astral.sh/uv/install.sh | sh\n'
306
+ ' export PATH="$HOME/.local/bin:$PATH"\n'
307
+ "fi\n"
308
+ )
309
+
310
+ if resolved_pkg_source:
311
+ script = (
312
+ uv_bootstrap
313
+ + f"uvx --python 3.12 --from {shlex.quote(resolved_pkg_source)} specbench {remote_args_str}"
314
+ + plot_snippet
315
+ )
316
+ else:
317
+ bundle_b64 = bundle_local_package(repo_root=repo_root)
318
+ cmd.extend(["--env", f"SPECBENCH_BUNDLE_B64={bundle_b64}"])
319
+ script = (
320
+ uv_bootstrap
321
+ + "mkdir -p /tmp/specbench-src\n"
322
+ + 'printf "%s" "$SPECBENCH_BUNDLE_B64" | base64 -d | tar -xz -C /tmp/specbench-src\n'
323
+ + "cd /tmp/specbench-src\n"
324
+ + f"uv run --python 3.12 specbench {remote_args_str}"
325
+ + plot_snippet
326
+ )
327
+
328
+ cmd.extend(["--", job.image, "bash", "-lc", script])
329
+ return cmd
330
+
331
+
332
+ def format_hf_jobs_command(cmd: list[str]) -> str:
333
+ """Format an `hf jobs run` command cleanly for terminal display, redacting inline base64 bundles."""
334
+ redacted: list[str] = []
335
+ for tok in cmd:
336
+ if tok.startswith("SPECBENCH_BUNDLE_B64="):
337
+ size_kb = len(tok.split("=", 1)[1]) / 1024.0
338
+ redacted.append(f"SPECBENCH_BUNDLE_B64=<inline-package-bundle:{size_kb:.1f}KB>")
339
+ else:
340
+ redacted.append(tok)
341
+ return shlex.join(redacted)
342
+
343
+
344
+ def submit_hf_job(
345
+ cfg: BenchmarkConfig,
346
+ job: HFJobOptions,
347
+ *,
348
+ print_only: bool = False,
349
+ console: Console | None = None,
350
+ repo_root: Path | None = None,
351
+ ) -> int:
352
+ """Validate, display summary, and submit (or print) an HF Jobs benchmark run."""
353
+ console = console or Console()
354
+ hf_bin = "hf" if print_only else resolve_hf_cli_binary()
355
+ cmd = build_hf_jobs_command(cfg, job, hf_bin=hf_bin, repo_root=repo_root)
356
+
357
+ resolved_pkg_source = resolve_hf_job_package_source(job.package_source, repo_root=repo_root)
358
+ pkg_desc = resolved_pkg_source or "inline local package bundle"
359
+ suites_desc = ", ".join(f"{s.capability} ({s.limit or 'all'})" for s in cfg.suites)
360
+ summary_lines = [
361
+ f"[bold]Model:[/bold] {cfg.model.model_repo} (spec_type={cfg.model.resolved_spec_type})",
362
+ f"[bold]Flavor:[/bold] {job.flavor} [bold]Timeout:[/bold] {job.timeout} [bold]Detach:[/bold] {job.detach}",
363
+ f"[bold]Image:[/bold] {job.image}",
364
+ f"[bold]Package:[/bold] {pkg_desc}",
365
+ f"[bold]Draft N:[/bold] {cfg.draft_tokens}",
366
+ f"[bold]Suites:[/bold] {suites_desc}",
367
+ f"[bold]HF Dataset:[/bold] {cfg.output.hf_dataset_repo or '(none / dry-run)'}",
368
+ ]
369
+ if job.volumes:
370
+ summary_lines.append(f"[bold]Volumes:[/bold] {', '.join(job.volumes)}")
371
+ console.print(Panel("\n".join(summary_lines), title="Hugging Face Job Benchmark", border_style="cyan"))
372
+
373
+ if print_only:
374
+ console.print("\n[bold cyan]HF Jobs command:[/bold cyan]")
375
+ console.print(format_hf_jobs_command(cmd))
376
+ return 0
377
+
378
+ proc = subprocess.run(cmd, check=False)
379
+ return int(proc.returncode)
@@ -0,0 +1,196 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ from datasets import Dataset, Features, Value, load_dataset
7
+ from rich.console import Console
8
+
9
+ from speculation_benchmark.config import OutputConfig
10
+
11
+
12
+ SAMPLES_FEATURES = Features(
13
+ {
14
+ "run_id": Value("string"),
15
+ "timestamp_utc": Value("string"),
16
+ "backend": Value("string"),
17
+ "llama_version": Value("string"),
18
+ "hardware": Value("string"),
19
+ "model_repo": Value("string"),
20
+ "model_file": Value("string"),
21
+ "model_quant": Value("string"),
22
+ "is_quantized": Value("bool"),
23
+ "speculator_repo": Value("string"),
24
+ "speculator_file": Value("string"),
25
+ "speculator_quant": Value("string"),
26
+ "speculator_is_quantized": Value("bool"),
27
+ "speculator_mode": Value("string"),
28
+ "spec_type": Value("string"),
29
+ "draft_n_max": Value("int64"),
30
+ "effective_draft_n_max": Value("int64"),
31
+ "capability": Value("string"),
32
+ "source_dataset": Value("string"),
33
+ "sample_id": Value("string"),
34
+ "has_images": Value("bool"),
35
+ "ok": Value("bool"),
36
+ "error": Value("string"),
37
+ "finish_reason": Value("string"),
38
+ "prompt_tokens": Value("int64"),
39
+ "predicted_tokens": Value("int64"),
40
+ "draft_n": Value("int64"),
41
+ "draft_n_accepted": Value("int64"),
42
+ "acceptance_rate": Value("float64"),
43
+ "prompt_ms": Value("float64"),
44
+ "predicted_ms": Value("float64"),
45
+ "prompt_per_second": Value("float64"),
46
+ "predicted_per_second": Value("float64"),
47
+ "latency_s": Value("float64"),
48
+ "max_tokens": Value("int64"),
49
+ "temperature": Value("float64"),
50
+ }
51
+ )
52
+
53
+ SUMMARY_FEATURES = Features(
54
+ {
55
+ "run_id": Value("string"),
56
+ "timestamp_utc": Value("string"),
57
+ "backend": Value("string"),
58
+ "llama_version": Value("string"),
59
+ "hardware": Value("string"),
60
+ "model_repo": Value("string"),
61
+ "model_file": Value("string"),
62
+ "model_quant": Value("string"),
63
+ "is_quantized": Value("bool"),
64
+ "speculator_repo": Value("string"),
65
+ "speculator_file": Value("string"),
66
+ "speculator_quant": Value("string"),
67
+ "speculator_is_quantized": Value("bool"),
68
+ "speculator_mode": Value("string"),
69
+ "spec_type": Value("string"),
70
+ "draft_n_max": Value("int64"),
71
+ "effective_draft_n_max": Value("int64"),
72
+ "capability": Value("string"),
73
+ "source_datasets": Value("string"),
74
+ "samples_total": Value("int64"),
75
+ "samples_ok": Value("int64"),
76
+ "samples_failed": Value("int64"),
77
+ "total_prompt_tokens": Value("int64"),
78
+ "total_predicted_tokens": Value("int64"),
79
+ "total_draft_n": Value("int64"),
80
+ "total_draft_n_accepted": Value("int64"),
81
+ "acceptance_rate": Value("float64"),
82
+ "mean_sample_acceptance_rate": Value("float64"),
83
+ "avg_prompt_per_second": Value("float64"),
84
+ "avg_predicted_per_second": Value("float64"),
85
+ "avg_latency_s": Value("float64"),
86
+ "speedup_vs_baseline": Value("float64"),
87
+ "gpu_memory_peak_mib": Value("float64"),
88
+ "speculator_extra_gpu_memory_mib": Value("float64"),
89
+ "max_tokens": Value("int64"),
90
+ "temperature": Value("float64"),
91
+ }
92
+ )
93
+
94
+
95
+ def build_datasets(
96
+ summary_rows: list[dict[str, Any]],
97
+ sample_rows: list[dict[str, Any]],
98
+ ) -> tuple[Dataset, Dataset]:
99
+ """Construct typed Hugging Face Datasets for `summary` and `samples` configs."""
100
+ summary_ds = Dataset.from_list(summary_rows, features=SUMMARY_FEATURES)
101
+ samples_ds = Dataset.from_list(sample_rows, features=SAMPLES_FEATURES)
102
+ return summary_ds, samples_ds
103
+
104
+
105
+ def merge_rows_dedup(
106
+ existing_rows: list[dict[str, Any]],
107
+ new_rows: list[dict[str, Any]],
108
+ key_fields: tuple[str, ...],
109
+ ) -> list[dict[str, Any]]:
110
+ """Append new rows onto existing rows, replacing any matching composite key."""
111
+ merged: dict[tuple[Any, ...], dict[str, Any]] = {}
112
+ for row in existing_rows:
113
+ key = tuple(row.get(k) for k in key_fields)
114
+ merged[key] = row
115
+ for row in new_rows:
116
+ key = tuple(row.get(k) for k in key_fields)
117
+ merged[key] = row
118
+ return list(merged.values())
119
+
120
+
121
+ def _try_load_existing_rows(repo_id: str, config_name: str) -> list[dict[str, Any]]:
122
+ try:
123
+ ds = load_dataset(repo_id, name=config_name, split="train")
124
+ return [dict(row) for row in ds]
125
+ except Exception:
126
+ return []
127
+
128
+
129
+ def publish_results(
130
+ *,
131
+ summary_rows: list[dict[str, Any]],
132
+ sample_rows: list[dict[str, Any]],
133
+ output: OutputConfig,
134
+ run_dir: Path,
135
+ console: Console | None = None,
136
+ ) -> dict[str, str]:
137
+ """Export Parquet files locally and optionally push `summary` & `samples` configs to HF Hub."""
138
+ console = console or Console()
139
+ run_dir.mkdir(parents=True, exist_ok=True)
140
+
141
+ summary_ds, samples_ds = build_datasets(summary_rows, sample_rows)
142
+ summary_parquet = run_dir / "summary.parquet"
143
+ samples_parquet = run_dir / "samples.parquet"
144
+ summary_ds.to_parquet(str(summary_parquet))
145
+ samples_ds.to_parquet(str(samples_parquet))
146
+ console.print(f"Saved local Parquet artifacts to [bold]{run_dir}[/bold]")
147
+
148
+ hub_urls: dict[str, str] = {}
149
+ if output.dry_run or not output.hf_dataset_repo:
150
+ if output.dry_run:
151
+ console.print("Dry run enabled: skipping Hugging Face Hub push.")
152
+ return hub_urls
153
+
154
+ repo_id = output.hf_dataset_repo
155
+ final_summary_rows = summary_rows
156
+ final_sample_rows = sample_rows
157
+
158
+ if output.append:
159
+ existing_summary = _try_load_existing_rows(repo_id, "summary")
160
+ existing_samples = _try_load_existing_rows(repo_id, "samples")
161
+ if existing_summary:
162
+ final_summary_rows = merge_rows_dedup(
163
+ existing_summary,
164
+ summary_rows,
165
+ key_fields=("run_id", "capability", "draft_n_max"),
166
+ )
167
+ if existing_samples:
168
+ final_sample_rows = merge_rows_dedup(
169
+ existing_samples,
170
+ sample_rows,
171
+ key_fields=("run_id", "capability", "draft_n_max", "sample_id"),
172
+ )
173
+
174
+ final_summary_ds, final_samples_ds = build_datasets(final_summary_rows, final_sample_rows)
175
+
176
+ console.print(f"Pushing [bold]summary[/bold] ({len(final_summary_ds)} rows) to {repo_id}...")
177
+ summary_info = final_summary_ds.push_to_hub(
178
+ repo_id,
179
+ config_name="summary",
180
+ split="train",
181
+ private=output.private,
182
+ commit_message=f"Add summary results ({len(summary_rows)} rows)",
183
+ )
184
+ console.print(f"Pushing [bold]samples[/bold] ({len(final_samples_ds)} rows) to {repo_id}...")
185
+ samples_info = final_samples_ds.push_to_hub(
186
+ repo_id,
187
+ config_name="samples",
188
+ split="train",
189
+ private=output.private,
190
+ commit_message=f"Add sample results ({len(sample_rows)} rows)",
191
+ )
192
+
193
+ hub_urls["summary"] = str(getattr(summary_info, "commit_url", f"https://huggingface.co/datasets/{repo_id}"))
194
+ hub_urls["samples"] = str(getattr(samples_info, "commit_url", f"https://huggingface.co/datasets/{repo_id}"))
195
+ console.print(f"[green]Published dataset:[/green] https://huggingface.co/datasets/{repo_id}")
196
+ return hub_urls