Download src/shiftedx_bench/cli.py from Shiftedx/shiftedx-bench: direct link, hf CLI and curl.
- Browser
- Download file 22.6 kB
-
https://huggingface.co/datasets/Shiftedx/shiftedx-bench/resolve/main/src/shiftedx_bench/cli.py
- Command line
-
hf download hf://datasets/Shiftedx/shiftedx-bench/src/shiftedx_bench/cli.py
-
curl -L -o cli.py https://huggingface.co/datasets/Shiftedx/shiftedx-bench/resolve/main/src/shiftedx_bench/cli.py
22.6 kB
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import uuid | |
| from dataclasses import replace | |
| from pathlib import Path | |
| from typing import Any | |
| from .agentic import run_agentic_cases, scenario_set, scenarios | |
| from .agentic_report import summarize_agentic_trials | |
| from .api import OpenAIClient | |
| from .boundary import probe_context_boundary | |
| from .context import build_context_case, expand_context_config | |
| from .holdout import derive_holdout_config | |
| from .model_card import render_benchmark_block, update_model_card, validate_post_publish_run | |
| from .provenance import make_run_manifest, write_manifest | |
| from .quality import generate_quality_cases | |
| from .release import sanitize_manifest, sanitize_result_row, scan_public_tree | |
| from .runner import api_key_from_env, run_cases | |
| from .summary import summarize_results | |
| from .tokenizer import TransformersTokenizer | |
| from .tools import generate_tool_cases | |
| from .util import read_json, read_jsonl, write_json, write_jsonl | |
| from .vision import generate_vision_cases | |
| def _variants(path: Path | None, label: str | None = None) -> list[dict[str, Any]]: | |
| if path is not None and label is not None: | |
| raise ValueError("--label and --variants are mutually exclusive") | |
| if path is None: | |
| return [{"label": label or "default", "request_overrides": {}}] | |
| value = read_json(path) | |
| if not isinstance(value, list) or not value: | |
| raise ValueError("Variant file must contain a non-empty JSON array") | |
| return value | |
| def _client(args: argparse.Namespace) -> OpenAIClient: | |
| return OpenAIClient( | |
| base_url=args.base_url, | |
| api_key=api_key_from_env(args.api_key_env), | |
| timeout_s=args.timeout, | |
| ) | |
| def plan_context(args: argparse.Namespace) -> None: | |
| config = read_json(args.config) | |
| specs = expand_context_config(config) | |
| value = { | |
| "schema_version": "1.0", | |
| "suite_id": config["suite_id"], | |
| "cases": len(specs), | |
| "total_requested_prompt_tokens": sum(item.target_tokens for item in specs), | |
| "by_matrix": {}, | |
| "specs": [item.__dict__ | {"case_id": item.case_id} for item in specs], | |
| } | |
| for spec in specs: | |
| value["by_matrix"][spec.matrix] = value["by_matrix"].get(spec.matrix, 0) + 1 | |
| write_json(args.output, value) | |
| def _tokenizer(args: argparse.Namespace) -> TransformersTokenizer: | |
| return TransformersTokenizer( | |
| args.tokenizer, | |
| enable_thinking=args.thinking == "on", | |
| reasoning_effort=args.reasoning_effort, | |
| preserve_thinking=True, | |
| ) | |
| def _reasoning_request_overrides(args: argparse.Namespace) -> dict[str, Any]: | |
| value: dict[str, Any] = {"thinking": {"enabled": args.thinking == "on"}} | |
| if args.reasoning_effort: | |
| value["reasoning_effort"] = args.reasoning_effort | |
| return value | |
| def _record_evaluated_artifact(manifest: dict[str, Any], args: argparse.Namespace) -> None: | |
| repo_id = getattr(args, "hf_repo", None) | |
| revision = getattr(args, "hf_revision", None) | |
| benchmark_revision = getattr(args, "benchmark_revision", None) | |
| if bool(repo_id) != bool(revision): | |
| raise ValueError("--hf-repo and --hf-revision must be supplied together") | |
| if repo_id and not benchmark_revision: | |
| raise ValueError("--benchmark-revision is required for a post-publication run") | |
| if repo_id: | |
| manifest["evaluated_artifact"] = {"repo_id": repo_id, "revision": revision} | |
| manifest["benchmark_source"] = { | |
| "repo_id": "Shiftedx/shiftedx-bench", | |
| "revision": benchmark_revision, | |
| } | |
| def _validate_context_variant_profile(args: argparse.Namespace, variants: list[dict[str, Any]]) -> None: | |
| declared = { | |
| bool((variant.get("request_overrides", {}).get("thinking") or {}).get("enabled")) | |
| for variant in variants | |
| if "thinking" in (variant.get("request_overrides") or {}) | |
| } | |
| if len(declared) > 1: | |
| raise ValueError("All variants in one exact-token context run must use the same thinking mode") | |
| if declared and declared != {args.thinking == "on"}: | |
| raise ValueError("--thinking must match the variant file so local and server templates are identical") | |
| def inspect_context(args: argparse.Namespace) -> None: | |
| config = read_json(args.config) | |
| specs = expand_context_config(config) | |
| selected = next((item for item in specs if item.case_id == args.case_id), None) | |
| if selected is None: | |
| raise ValueError(f"Unknown case identifier: {args.case_id}") | |
| tokenizer = _tokenizer(args) | |
| case = build_context_case(selected, tokenizer) | |
| value = case.to_dict(include_expected=True) | |
| if not args.include_prompt: | |
| value["messages"] = [{"role": item["role"], "content": "<omitted>"} for item in case.messages] | |
| write_json(args.output, value) | |
| def run_context(args: argparse.Namespace) -> None: | |
| config = read_json(args.config) | |
| specs = expand_context_config(config) | |
| if args.matrix: | |
| specs = [item for item in specs if item.matrix == args.matrix] | |
| if args.limit is not None: | |
| specs = specs[: args.limit] | |
| tokenizer = _tokenizer(args) | |
| variants = _variants(args.variants, args.label) | |
| _validate_context_variant_profile(args, variants) | |
| run_id = str(uuid.uuid4()) | |
| manifest = make_run_manifest( | |
| run_id=run_id, | |
| suite_id=config["suite_id"], | |
| model=args.model, | |
| config_path=args.config, | |
| tokenizer_fingerprint=tokenizer.fingerprint, | |
| variants=variants, | |
| ) | |
| manifest["planned_cases"] = len(specs) | |
| manifest["requested_prompt_tokens"] = sum(item.target_tokens for item in specs) | |
| _record_evaluated_artifact(manifest, args) | |
| write_manifest(args.output.with_suffix(".manifest.json"), manifest) | |
| reasoning_overrides = _reasoning_request_overrides(args) | |
| cases = ( | |
| replace(build_context_case(spec, tokenizer), request_overrides=reasoning_overrides) | |
| for spec in specs | |
| ) | |
| run_cases( | |
| cases, | |
| client=_client(args), | |
| model=args.model, | |
| output_path=args.output, | |
| variants=variants, | |
| run_id=run_id, | |
| stream=args.stream, | |
| ) | |
| def run_suite(args: argparse.Namespace) -> None: | |
| config = read_json(args.config) | |
| variants = _variants(args.variants, args.label) | |
| if args.suite == "quality": | |
| cases = generate_quality_cases(config["quality"]["seeds"], config["quality"].get("families")) | |
| suite_id = "shiftedx-quality-v1" | |
| elif args.suite == "tools": | |
| cases = generate_tool_cases(config["tools"]["seeds"]) | |
| suite_id = "shiftedx-tools-v1" | |
| elif args.suite == "vision": | |
| cases = generate_vision_cases(args.output.parent / "vision-fixtures", config["vision"]["seeds"]) | |
| suite_id = "shiftedx-vision-v1" | |
| elif args.suite == "agentic": | |
| if len(variants) != 1: | |
| raise ValueError("Agentic runner currently accepts one request variant per invocation") | |
| request_overrides = dict(variants[0].get("request_overrides") or {}) | |
| thinking = getattr(args, "thinking", None) | |
| reasoning_effort = getattr(args, "reasoning_effort", None) | |
| if thinking is not None: | |
| request_overrides["thinking"] = {"enabled": thinking == "on"} | |
| if reasoning_effort is not None: | |
| request_overrides["reasoning_effort"] = reasoning_effort | |
| variants = [{**variants[0], "request_overrides": request_overrides}] | |
| agentic_set = getattr(args, "agentic_set", "core") | |
| selected = scenario_set(agentic_set) | |
| case_id = getattr(args, "case_id", None) | |
| if case_id is not None: | |
| selected = [item for item in selected if item.case_id == case_id] | |
| if not selected: | |
| raise ValueError(f"Unknown case identifier for {agentic_set}: {case_id}") | |
| if args.limit is not None: | |
| selected = selected[: args.limit] | |
| run_id = str(uuid.uuid4()) | |
| manifest = make_run_manifest( | |
| run_id=run_id, suite_id="shiftedx-agentic-v1", model=args.model, | |
| config_path=args.config, tokenizer_fingerprint=None, variants=variants, | |
| ) | |
| manifest["planned_cases"] = len(selected) | |
| manifest["agentic_control_profile"] = getattr(args, "agentic_control_profile", "baseline") | |
| manifest["agentic_set"] = agentic_set | |
| _record_evaluated_artifact(manifest, args) | |
| write_manifest(args.output.with_suffix(".manifest.json"), manifest) | |
| run_agentic_cases( | |
| client=_client(args), model=args.model, output_path=args.output, | |
| request_overrides=variants[0].get("request_overrides") or {}, | |
| variant_label=str(variants[0]["label"]), | |
| limit=args.limit, | |
| run_id=run_id, | |
| control_profile=getattr(args, "agentic_control_profile", "baseline"), | |
| agentic_set=agentic_set, | |
| case_id=case_id, | |
| ) | |
| return | |
| else: | |
| raise ValueError(args.suite) | |
| if args.limit is not None: | |
| cases = cases[: args.limit] | |
| run_id = str(uuid.uuid4()) | |
| manifest = make_run_manifest( | |
| run_id=run_id, suite_id=suite_id, model=args.model, config_path=args.config, | |
| tokenizer_fingerprint=None, variants=variants, | |
| ) | |
| _record_evaluated_artifact(manifest, args) | |
| write_manifest(args.output.with_suffix(".manifest.json"), manifest) | |
| run_cases( | |
| cases, | |
| client=_client(args), model=args.model, output_path=args.output, | |
| variants=variants, run_id=run_id, stream=args.stream, | |
| ) | |
| def summarize(args: argparse.Namespace) -> None: | |
| rows = [] | |
| for path in args.inputs: | |
| rows.extend(read_jsonl(path)) | |
| write_json( | |
| args.output, | |
| summarize_results(rows, args.effective_threshold, baseline_variant=args.baseline), | |
| ) | |
| def summarize_agentic(args: argparse.Namespace) -> None: | |
| rows = [] | |
| for path in args.inputs: | |
| rows.extend(read_jsonl(path)) | |
| write_json(args.output, summarize_agentic_trials(rows)) | |
| def export_public_results(args: argparse.Namespace) -> None: | |
| rows = [] | |
| for path in args.inputs: | |
| rows.extend(read_jsonl(path)) | |
| write_jsonl(args.output, (sanitize_result_row(row) for row in rows)) | |
| if args.manifest is not None: | |
| if args.manifest_output is None: | |
| raise ValueError("--manifest-output is required with --manifest") | |
| write_json(args.manifest_output, sanitize_manifest(read_json(args.manifest))) | |
| elif args.manifest_output is not None: | |
| raise ValueError("--manifest is required with --manifest-output") | |
| def _bundled_config(name: str) -> Path: | |
| path = Path(__file__).resolve().parents[2] / "configs" / name | |
| if not path.exists(): | |
| raise FileNotFoundError( | |
| f"Bundled config not found at {path}; pass an explicit config path from the source repository" | |
| ) | |
| return path | |
| def run_quant_gate(args: argparse.Namespace) -> None: | |
| args.output_dir.mkdir(parents=True, exist_ok=True) | |
| context_config = args.context_config or _bundled_config("context-quant-gate-v1.json") | |
| suite_config = args.suite_config or _bundled_config("suites-quant-gate-v1.json") | |
| common = { | |
| "base_url": args.base_url, | |
| "model": args.model, | |
| "hf_repo": args.hf_repo, | |
| "hf_revision": args.hf_revision, | |
| "benchmark_revision": args.benchmark_revision, | |
| "api_key_env": args.api_key_env, | |
| "timeout": args.timeout, | |
| "variants": None, | |
| "label": args.label, | |
| "stream": True, | |
| } | |
| run_context( | |
| argparse.Namespace( | |
| **common, | |
| output=args.output_dir / "context.jsonl", | |
| config=context_config, | |
| tokenizer=args.tokenizer, | |
| thinking=args.thinking, | |
| reasoning_effort=args.reasoning_effort, | |
| matrix=None, | |
| limit=None, | |
| ) | |
| ) | |
| suite_settings = read_json(suite_config) | |
| outputs = [args.output_dir / "context.jsonl"] | |
| suites = ["quality", "tools", "agentic"] | |
| if args.profile == "vision": | |
| suites.append("vision") | |
| for suite in suites: | |
| output = args.output_dir / f"{suite}.jsonl" | |
| run_suite( | |
| argparse.Namespace( | |
| **common, | |
| output=output, | |
| config=suite_config, | |
| suite=suite, | |
| limit=suite_settings.get("agentic_limit") if suite == "agentic" else None, | |
| ) | |
| ) | |
| outputs.append(output) | |
| rows = [] | |
| for path in outputs: | |
| rows.extend(read_jsonl(path)) | |
| write_json( | |
| args.output_dir / "summary.json", | |
| summarize_results(rows, baseline_variant=args.label), | |
| ) | |
| def render_model_card(args: argparse.Namespace) -> None: | |
| rows, benchmark_version = validate_post_publish_run( | |
| args.run_dir, | |
| variant=args.variant, | |
| profile=args.profile, | |
| model_repo=args.model_repo, | |
| model_revision=args.model_revision, | |
| benchmark_revision=args.benchmark_revision, | |
| ) | |
| block = render_benchmark_block( | |
| rows, | |
| variant=args.variant, | |
| model_repo=args.model_repo, | |
| model_revision=args.model_revision, | |
| benchmark_revision=args.benchmark_revision, | |
| benchmark_version=benchmark_version, | |
| host=args.host, | |
| runtime=args.runtime, | |
| kv_cache=args.kv_cache, | |
| mtp_depth=args.mtp_depth, | |
| max_window_status=args.max_window_status, | |
| ) | |
| args.output.parent.mkdir(parents=True, exist_ok=True) | |
| args.output.write_text(update_model_card(args.readme.read_text(encoding="utf-8"), block), encoding="utf-8") | |
| def validate_release(args: argparse.Namespace) -> None: | |
| result = scan_public_tree(args.root) | |
| if args.output: | |
| write_json(args.output, result) | |
| else: | |
| print(json.dumps(result, indent=2, sort_keys=True)) | |
| if not result["ok"]: | |
| raise SystemExit(1) | |
| def make_holdout(args: argparse.Namespace) -> None: | |
| master_key = api_key_from_env(args.master_key_env) | |
| if master_key is None: | |
| raise RuntimeError("Holdout master key is required") | |
| config = derive_holdout_config(read_json(args.template), master_key, args.release_id) | |
| write_json(args.output, config) | |
| def probe_boundary(args: argparse.Namespace) -> None: | |
| tokenizer = _tokenizer(args) | |
| result = probe_context_boundary( | |
| client=_client(args), tokenizer=tokenizer, model=args.model, | |
| context_window=args.context_window, reserved_output_tokens=args.reserved_output_tokens, | |
| include_positive=args.include_positive, | |
| ) | |
| write_json(args.output, result) | |
| if not result["passed"]: | |
| raise SystemExit(1) | |
| def add_runtime_arguments(parser: argparse.ArgumentParser) -> None: | |
| parser.add_argument("--base-url", required=True, help="OpenAI-compatible base URL ending in /v1") | |
| parser.add_argument("--model", required=True) | |
| parser.add_argument("--output", required=True, type=Path) | |
| parser.add_argument("--api-key-env", help="Environment-variable name containing the API key") | |
| parser.add_argument("--timeout", type=float, default=900) | |
| parser.add_argument("--variants", type=Path) | |
| parser.add_argument("--label", help="Stable candidate label stored in every result row") | |
| parser.add_argument("--limit", type=int) | |
| parser.add_argument("--stream", action="store_true") | |
| parser.add_argument("--hf-repo", help="Published Hugging Face repo evaluated by this run") | |
| parser.add_argument("--hf-revision", help="Full immutable Hugging Face revision evaluated by this run") | |
| parser.add_argument( | |
| "--benchmark-revision", help="Full immutable Shiftedx Bench revision used by this run" | |
| ) | |
| def add_tokenizer_profile_arguments(parser: argparse.ArgumentParser) -> None: | |
| parser.add_argument("--tokenizer", required=True, type=Path) | |
| parser.add_argument("--thinking", choices=["on", "off"], default="on") | |
| parser.add_argument("--reasoning-effort", default="medium") | |
| def make_parser() -> argparse.ArgumentParser: | |
| parser = argparse.ArgumentParser(prog="shiftedx-bench") | |
| subparsers = parser.add_subparsers(dest="command", required=True) | |
| command = subparsers.add_parser("plan-context") | |
| command.add_argument("--config", required=True, type=Path) | |
| command.add_argument("--output", required=True, type=Path) | |
| command.set_defaults(func=plan_context) | |
| command = subparsers.add_parser("inspect-context") | |
| command.add_argument("--config", required=True, type=Path) | |
| add_tokenizer_profile_arguments(command) | |
| command.add_argument("--case-id", required=True) | |
| command.add_argument("--output", required=True, type=Path) | |
| command.add_argument("--include-prompt", action="store_true") | |
| command.set_defaults(func=inspect_context) | |
| command = subparsers.add_parser("run-context") | |
| add_runtime_arguments(command) | |
| command.add_argument("--config", required=True, type=Path) | |
| add_tokenizer_profile_arguments(command) | |
| command.add_argument("--matrix") | |
| command.set_defaults(func=run_context) | |
| command = subparsers.add_parser("run-suite") | |
| add_runtime_arguments(command) | |
| command.add_argument("--config", required=True, type=Path) | |
| command.add_argument("--suite", required=True, choices=["quality", "tools", "agentic", "vision"]) | |
| command.add_argument( | |
| "--agentic-control-profile", | |
| choices=["baseline", "shiftedx-harness-v1"], | |
| default="baseline", | |
| help="Optional Shiftedx Agent Harness profile for the agentic suite only", | |
| ) | |
| command.add_argument( | |
| "--thinking", choices=["on", "off"], | |
| help="Explicit reasoning mode for agentic requests; omit to use the endpoint default", | |
| ) | |
| command.add_argument( | |
| "--reasoning-effort", | |
| help="Explicit reasoning effort for agentic requests; omit to use the endpoint default", | |
| ) | |
| command.add_argument( | |
| "--agentic-set", choices=["core", "expanded", "repo"], default="core", | |
| help="Agentic scenario set; core remains the lightweight quant-gate default", | |
| ) | |
| command.add_argument("--case-id", help="Run one named agentic case from the selected set") | |
| command.set_defaults(func=run_suite) | |
| command = subparsers.add_parser("summarize") | |
| command.add_argument("inputs", nargs="+", type=Path) | |
| command.add_argument("--output", required=True, type=Path) | |
| command.add_argument("--effective-threshold", type=float, default=0.90) | |
| command.add_argument("--baseline", help="Explicit baseline variant for paired comparison") | |
| command.set_defaults(func=summarize) | |
| command = subparsers.add_parser("summarize-agentic") | |
| command.add_argument("inputs", nargs="+", type=Path) | |
| command.add_argument("--output", required=True, type=Path) | |
| command.set_defaults(func=summarize_agentic) | |
| command = subparsers.add_parser("export-public-results") | |
| command.add_argument("inputs", nargs="+", type=Path) | |
| command.add_argument("--output", required=True, type=Path) | |
| command.add_argument("--manifest", type=Path) | |
| command.add_argument("--manifest-output", type=Path) | |
| command.set_defaults(func=export_public_results) | |
| command = subparsers.add_parser("run-quant-gate") | |
| command.add_argument("--base-url", required=True, help="OpenAI-compatible base URL ending in /v1") | |
| command.add_argument("--model", required=True) | |
| command.add_argument("--tokenizer", required=True, type=Path) | |
| command.add_argument("--label", required=True) | |
| command.add_argument("--output-dir", required=True, type=Path) | |
| command.add_argument("--context-config", type=Path) | |
| command.add_argument("--suite-config", type=Path) | |
| command.add_argument("--api-key-env") | |
| command.add_argument("--timeout", type=float, default=1800) | |
| command.add_argument("--thinking", choices=["on", "off"], default="on") | |
| command.add_argument("--reasoning-effort", default="medium") | |
| command.add_argument("--profile", choices=["vision", "text"], default="vision") | |
| command.add_argument("--hf-repo", help="Published Hugging Face repo evaluated by this run") | |
| command.add_argument("--hf-revision", help="Full immutable Hugging Face revision evaluated by this run") | |
| command.add_argument("--benchmark-revision", help="Full immutable Shiftedx Bench revision used by this run") | |
| command.set_defaults(func=run_quant_gate) | |
| command = subparsers.add_parser("render-model-card") | |
| command.add_argument("--run-dir", required=True, type=Path) | |
| command.add_argument("--readme", required=True, type=Path) | |
| command.add_argument("--output", required=True, type=Path) | |
| command.add_argument("--variant", required=True) | |
| command.add_argument("--profile", choices=["vision", "text"], default="vision") | |
| command.add_argument("--model-repo", required=True) | |
| command.add_argument("--model-revision", required=True) | |
| command.add_argument("--benchmark-revision", required=True) | |
| command.add_argument("--host", required=True) | |
| command.add_argument("--runtime", required=True) | |
| command.add_argument("--kv-cache", choices=["off", "q8", "q4"], required=True) | |
| command.add_argument("--mtp-depth", default="not-applicable") | |
| command.add_argument( | |
| "--max-window-status", choices=["not-run", "host-limited", "passed"], default="not-run" | |
| ) | |
| command.set_defaults(func=render_model_card) | |
| command = subparsers.add_parser("validate-release") | |
| command.add_argument("--root", required=True, type=Path) | |
| command.add_argument("--output", type=Path) | |
| command.set_defaults(func=validate_release) | |
| command = subparsers.add_parser("make-holdout") | |
| command.add_argument("--template", required=True, type=Path) | |
| command.add_argument("--release-id", required=True) | |
| command.add_argument("--master-key-env", required=True) | |
| command.add_argument("--output", required=True, type=Path) | |
| command.set_defaults(func=make_holdout) | |
| command = subparsers.add_parser("probe-boundary") | |
| command.add_argument("--base-url", required=True) | |
| command.add_argument("--model", required=True) | |
| add_tokenizer_profile_arguments(command) | |
| command.add_argument("--context-window", type=int, default=262144) | |
| command.add_argument("--reserved-output-tokens", type=int, default=2048) | |
| command.add_argument("--include-positive", action="store_true") | |
| command.add_argument("--api-key-env") | |
| command.add_argument("--timeout", type=float, default=900) | |
| command.add_argument("--output", required=True, type=Path) | |
| command.set_defaults(func=probe_boundary) | |
| return parser | |
| def main() -> None: | |
| args = make_parser().parse_args() | |
| args.func(args) | |
| if __name__ == "__main__": | |
| main() | |