arach commited on
Commit
5fea69b
·
verified ·
1 Parent(s): 304d210

Add news summarization eval harness

Browse files
eval/news_summarization/COLAB_QUICKSTART.md ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Colab Quickstart
2
+
3
+ Use this when we want one strong open-weight model on the news-summarization benchmark without depending on hosted API limits.
4
+
5
+ Recommended first model:
6
+
7
+ - `Qwen/Qwen3.5-8B-Instruct-2507`
8
+
9
+ Good heavier option if the Colab runtime can handle it:
10
+
11
+ - `Qwen/Qwen3.5-14B-Instruct-2507`
12
+
13
+ ## Colab Setup
14
+
15
+ Runtime:
16
+
17
+ - `GPU`
18
+ - ideally `A100` or `L4`
19
+
20
+ Install deps:
21
+
22
+ ```bash
23
+ !pip install -q transformers accelerate sentencepiece bert-score rouge-score
24
+ ```
25
+
26
+ Clone the repo and enter it:
27
+
28
+ ```bash
29
+ !git clone https://github.com/arach/lab.git
30
+ %cd /content/lab
31
+ ```
32
+
33
+ Run a first 50-case pass:
34
+
35
+ ```bash
36
+ !python eval/news_summarization/run_hf_transformers.py \
37
+ --model Qwen/Qwen3.5-8B-Instruct-2507 \
38
+ --limit 50 \
39
+ --prompt-style simple \
40
+ --trust-remote-code \
41
+ --dtype bfloat16 \
42
+ --verbose
43
+ ```
44
+
45
+ Resume if the Colab runtime disconnects:
46
+
47
+ ```bash
48
+ !python eval/news_summarization/run_hf_transformers.py \
49
+ --model Qwen/Qwen3.5-8B-Instruct-2507 \
50
+ --limit 50 \
51
+ --prompt-style simple \
52
+ --trust-remote-code \
53
+ --dtype bfloat16 \
54
+ --resume
55
+ ```
56
+
57
+ ## What This Gives Us
58
+
59
+ - one strong open model
60
+ - visible progress every 5 cases
61
+ - resumable output in:
62
+ - `/content/lab/eval/news_summarization/results/`
63
+
64
+ ## Suggested Comparison
65
+
66
+ Match this against the hosted frontier baseline we already ran:
67
+
68
+ - `anthropic/claude-sonnet-4.5`
69
+
70
+ That gives us:
71
+
72
+ - best hosted high-end model so far
73
+ - one serious open-weight Colab model
74
+
75
+ ## Notes
76
+
77
+ - This runner uses the same dataset and scoring path as the local news pilot.
78
+ - `simple` prompt is the default because it behaved well in our earlier tests.
79
+ - For first passes, prefer `50` cases over `500`.
eval/news_summarization/README.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # News Summarization Pilot
2
+
3
+ Small, paper-aligned pilot based on:
4
+
5
+ - [Evaluating Small Language Models for News Summarization: Implications and Factors Influencing Performance](https://aclanthology.org/2025.naacl-long.253/)
6
+ - benchmark repo: [Xtra-Computing/SLM_Summary_Benchmark](https://github.com/Xtra-Computing/SLM_Summary_Benchmark)
7
+
8
+ Why this exists:
9
+
10
+ - It is a cleaner first external probe for `rewrite clearly` and `what matters most` than QMSum.
11
+ - The paper found that strong SLMs can approach much larger models on summarization quality.
12
+ - The paper also found that simple prompts often work better than more detailed prompts for SLMs.
13
+
14
+ Current scope:
15
+
16
+ - dataset: `bbc2024_qwen_reference`
17
+ - reference: `qwen_reference_summary` from the released benchmark sample
18
+ - prompts:
19
+ - `simple`: closest to the paper default
20
+ - `helpful`: light assistant framing
21
+ - `detailed`: tests the paper's "more prompt detail is not always better" claim
22
+
23
+ Metrics:
24
+
25
+ - `token_f1`
26
+ - `ROUGE-1 / ROUGE-2 / ROUGE-L`
27
+ - `BERTScore`
28
+ - `word_count`
29
+ - `latency_ms`
30
+
31
+ Quick run:
32
+
33
+ ```bash
34
+ GH_TOKEN="$(gh auth token)" eval/qmsum/.venv/bin/python eval/news_summarization/run_news_summary_pilot.py \
35
+ --provider github_models \
36
+ --model openai/gpt-4.1-mini \
37
+ --limit 5 \
38
+ --prompt-style simple \
39
+ --verbose
40
+ ```
41
+
42
+ Compare prompt styles on the same sample:
43
+
44
+ ```bash
45
+ GH_TOKEN="$(gh auth token)" eval/qmsum/.venv/bin/python eval/news_summarization/run_news_summary_pilot.py \
46
+ --provider github_models \
47
+ --model openai/gpt-4.1-mini \
48
+ --limit 10 \
49
+ --seed 7 \
50
+ --prompt-style simple
51
+
52
+ GH_TOKEN="$(gh auth token)" eval/qmsum/.venv/bin/python eval/news_summarization/run_news_summary_pilot.py \
53
+ --provider github_models \
54
+ --model openai/gpt-4.1-mini \
55
+ --limit 10 \
56
+ --seed 7 \
57
+ --prompt-style detailed
58
+ ```
59
+
60
+ Interpretation:
61
+
62
+ - Use this as an external calibration point for memo rewrite quality, not as the whole memo eval.
63
+ - Strong scores here suggest a model may be viable for `rewrite clearly` and `what matters most`.
64
+ - Weak scores here do not say much about reminder/calendar/action extraction.
65
+
66
+ ## Colab
67
+
68
+ For a strong open-weight comparison path, use:
69
+
70
+ - [`COLAB_QUICKSTART.md`](/Users/arach/dev/lab/eval/news_summarization/COLAB_QUICKSTART.md)
71
+ - [`run_hf_transformers.py`](/Users/arach/dev/lab/eval/news_summarization/run_hf_transformers.py)
eval/news_summarization/data/bbc2024_qwen_reference.json ADDED
The diff for this file is too large to render. See raw diff
 
eval/news_summarization/requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ bert-score
2
+ rouge-score
3
+ torch
4
+ transformers
5
+ accelerate
6
+ sentencepiece
eval/news_summarization/run_hf_transformers.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ from pathlib import Path
7
+ import re
8
+ import sys
9
+ import time
10
+
11
+ REPO_ROOT = Path(__file__).resolve().parents[2]
12
+ if str(REPO_ROOT) not in sys.path:
13
+ sys.path.insert(0, str(REPO_ROOT))
14
+
15
+ from eval.news_summarization.run_news_summary_pilot import ( # noqa: E402
16
+ RESULTS_DIR,
17
+ build_messages,
18
+ clean_summary,
19
+ compute_bertscore,
20
+ compute_rouge_scores,
21
+ default_output_path,
22
+ ensure_dataset,
23
+ load_cases,
24
+ score_text,
25
+ summarize,
26
+ write_progress,
27
+ )
28
+
29
+
30
+ def parse_args() -> argparse.Namespace:
31
+ parser = argparse.ArgumentParser(description="Run the news summarization pilot on Hugging Face/Colab with transformers.")
32
+ parser.add_argument("--model", required=True, help="Hub model id, e.g. Qwen/Qwen3.5-8B-Instruct-2507")
33
+ parser.add_argument("--dataset", default="bbc2024_qwen_reference")
34
+ parser.add_argument("--prompt-style", default="simple", choices=["simple", "helpful", "detailed"])
35
+ parser.add_argument("--limit", type=int, default=50)
36
+ parser.add_argument("--seed", type=int, default=7)
37
+ parser.add_argument("--max-article-chars", type=int, default=8000)
38
+ parser.add_argument("--max-new-tokens", type=int, default=220)
39
+ parser.add_argument("--device-map", default="auto")
40
+ parser.add_argument("--dtype", default="auto")
41
+ parser.add_argument("--attn-implementation")
42
+ parser.add_argument("--trust-remote-code", action="store_true")
43
+ parser.add_argument("--disable-rouge", action="store_true")
44
+ parser.add_argument("--disable-bertscore", action="store_true")
45
+ parser.add_argument("--bertscore-model", default="roberta-large")
46
+ parser.add_argument("--output")
47
+ parser.add_argument("--resume", action="store_true")
48
+ parser.add_argument("--save-every", type=int, default=5)
49
+ parser.add_argument("--verbose", action="store_true")
50
+ return parser.parse_args()
51
+
52
+
53
+ def build_generator(args: argparse.Namespace):
54
+ import torch
55
+ from transformers import pipeline
56
+
57
+ torch_dtype = None
58
+ if args.dtype != "auto":
59
+ torch_dtype = getattr(torch, args.dtype)
60
+
61
+ kwargs: dict[str, object] = {
62
+ "model": args.model,
63
+ "device_map": args.device_map,
64
+ "trust_remote_code": args.trust_remote_code,
65
+ }
66
+ if torch_dtype is not None:
67
+ kwargs["torch_dtype"] = torch_dtype
68
+ if args.attn_implementation:
69
+ kwargs["model_kwargs"] = {"attn_implementation": args.attn_implementation}
70
+
71
+ generator = pipeline("text-generation", **kwargs)
72
+ generation_config = getattr(generator.model, "generation_config", None)
73
+ if generation_config is not None and getattr(generation_config, "max_length", None) == 20:
74
+ generation_config.max_length = None
75
+ return generator
76
+
77
+
78
+ def render_prompt(generator, messages: list[dict[str, str]]) -> str:
79
+ tokenizer = getattr(generator, "tokenizer", None)
80
+ if tokenizer is not None and hasattr(tokenizer, "apply_chat_template") and getattr(tokenizer, "chat_template", None):
81
+ try:
82
+ return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
83
+ except Exception:
84
+ pass
85
+ return "\n\n".join(f"{message['role'].upper()}:\n{message['content']}" for message in messages)
86
+
87
+
88
+ def main() -> int:
89
+ args = parse_args()
90
+ dataset_path = ensure_dataset(args.dataset)
91
+ cases = load_cases(dataset_path, limit=args.limit, seed=args.seed, max_article_chars=args.max_article_chars)
92
+ if not cases:
93
+ raise SystemExit("No news summarization cases selected.")
94
+
95
+ generator = build_generator(args)
96
+ output_path = Path(args.output) if args.output else default_output_path(
97
+ argparse.Namespace(
98
+ provider="hf-transformers",
99
+ model=args.model,
100
+ dataset=args.dataset,
101
+ prompt_style=args.prompt_style,
102
+ seed=args.seed,
103
+ limit=args.limit,
104
+ )
105
+ )
106
+
107
+ rows: list[dict] = []
108
+ completed_case_ids: set[str] = set()
109
+ if args.resume and output_path.exists():
110
+ existing = json.loads(output_path.read_text())
111
+ rows = existing.get("rows", [])
112
+ completed_case_ids = {row["case_id"] for row in rows}
113
+ print(f"Resuming from {output_path} with {len(rows)} completed cases.")
114
+
115
+ pending_cases = [case for case in cases if case.case_id not in completed_case_ids]
116
+ for index, case in enumerate(pending_cases, start=len(rows) + 1):
117
+ messages = build_messages(case, args.prompt_style)
118
+ prompt = render_prompt(generator, messages)
119
+ start = time.perf_counter()
120
+ output = generator(
121
+ prompt,
122
+ max_new_tokens=args.max_new_tokens,
123
+ do_sample=False,
124
+ return_full_text=False,
125
+ )
126
+ latency_ms = (time.perf_counter() - start) * 1000
127
+ prediction = clean_summary(output[0]["generated_text"])
128
+ scores = score_text(prediction, case.reference_summary)
129
+ scores.update(compute_rouge_scores(prediction, case.reference_summary, args.disable_rouge))
130
+ scores["word_count"] = len(prediction.split())
131
+ row = {
132
+ "case_id": case.case_id,
133
+ "article_chars": len(case.article),
134
+ "reference_summary": case.reference_summary,
135
+ "prediction": prediction,
136
+ "source_url": case.source_url,
137
+ "latency_ms": round(latency_ms, 2),
138
+ "scores": scores,
139
+ "provider_metadata": {"model": args.model},
140
+ }
141
+ rows.append(row)
142
+ if args.save_every > 0 and len(rows) % args.save_every == 0:
143
+ write_progress(output_path, rows, argparse.Namespace(
144
+ provider="hf-transformers",
145
+ model=args.model,
146
+ dataset=args.dataset,
147
+ prompt_style=args.prompt_style,
148
+ ), final=False)
149
+ print(f"Saved progress at {len(rows)}/{len(cases)} cases -> {output_path}")
150
+ if args.verbose:
151
+ print(
152
+ f"[{index:03d}] {case.case_id} "
153
+ f"token_f1={row['scores']['token_f1']:.4f} "
154
+ f"rougeL={row['scores'].get('rougeL_f1') or 0:.4f} "
155
+ f"words={row['scores']['word_count']} "
156
+ f"latency_ms={row['latency_ms']:.2f}"
157
+ )
158
+
159
+ compute_bertscore(rows, args.disable_bertscore, args.bertscore_model)
160
+ final_args = argparse.Namespace(
161
+ provider="hf-transformers",
162
+ model=args.model,
163
+ dataset=args.dataset,
164
+ prompt_style=args.prompt_style,
165
+ )
166
+ print(json.dumps(summarize(rows, final_args), indent=2))
167
+ write_progress(output_path, rows, final_args, final=True)
168
+ print(f"Wrote results to {output_path}")
169
+ return 0
170
+
171
+
172
+ if __name__ == "__main__":
173
+ raise SystemExit(main())
eval/news_summarization/run_news_summary_pilot.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ from dataclasses import dataclass
6
+ from datetime import datetime, timezone
7
+ from urllib.error import HTTPError
8
+ import json
9
+ from pathlib import Path
10
+ import random
11
+ import re
12
+ import sys
13
+ import time
14
+ from typing import Any
15
+ from urllib.request import urlopen
16
+
17
+ REPO_ROOT = Path(__file__).resolve().parents[2]
18
+ if str(REPO_ROOT) not in sys.path:
19
+ sys.path.insert(0, str(REPO_ROOT))
20
+
21
+ from eval.local_intelligence.providers import create_provider # noqa: E402
22
+
23
+ NEWS_SUMMARY_DIR = REPO_ROOT / "eval" / "news_summarization"
24
+ DATA_DIR = NEWS_SUMMARY_DIR / "data"
25
+ RESULTS_DIR = NEWS_SUMMARY_DIR / "results"
26
+ DEFAULT_DATASETS = {
27
+ "bbc2024_qwen_reference": "https://raw.githubusercontent.com/Xtra-Computing/SLM_Summary_Benchmark/main/dataset/sample_500_qwen1.5_72b_summary/bbc2024_sample_500_0k5_1k5_qwen1.5_72b_summary_no_len_limit.jsonl",
28
+ }
29
+ PROMPT_TEMPLATES = {
30
+ "simple": (
31
+ "News: {article}\n"
32
+ "Summarize the news in two sentences. Summary:"
33
+ ),
34
+ "helpful": (
35
+ "You are a helpful summary assistant. You can help users summarize news in two sentences.\n"
36
+ "News: {article}\n"
37
+ "Summarize the news in two sentences. Summary:"
38
+ ),
39
+ "detailed": (
40
+ "News: {article}\n"
41
+ "Summarize the news in two sentences. "
42
+ "Your summary should: 1. Capture the main points of the article. "
43
+ "2. Be concise and informative. 3. Use clear and simple language. "
44
+ "4. Avoid unnecessary details or opinions. Summary:"
45
+ ),
46
+ }
47
+
48
+ try:
49
+ from rouge_score import rouge_scorer # type: ignore
50
+ except ImportError:
51
+ rouge_scorer = None
52
+
53
+ try:
54
+ from bert_score import score as bert_score_fn # type: ignore
55
+ except ImportError:
56
+ bert_score_fn = None
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class NewsSummaryCase:
61
+ case_id: str
62
+ article: str
63
+ reference_summary: str
64
+ source_url: str | None
65
+
66
+
67
+ def utc_timestamp() -> str:
68
+ return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
69
+
70
+
71
+ def safe_slug(value: str | None) -> str:
72
+ text = value or "unknown"
73
+ return re.sub(r"[^a-z0-9._-]+", "-", text.lower()).strip("-") or "unknown"
74
+
75
+
76
+ def parse_args() -> argparse.Namespace:
77
+ parser = argparse.ArgumentParser(description="Run a lightweight news summarization pilot based on the NAACL 2025 SLM benchmark.")
78
+ parser.add_argument("--provider", choices=["replay", "apple", "mlx", "mlx_vlm", "ollama", "hf", "github_models", "openrouter", "nous", "groq"], required=True)
79
+ parser.add_argument("--model")
80
+ parser.add_argument("--adapter")
81
+ parser.add_argument("--apple-command")
82
+ parser.add_argument("--ollama-url", default="http://127.0.0.1:11434")
83
+ parser.add_argument("--hf-token")
84
+ parser.add_argument("--timeout", type=int, default=90)
85
+ parser.add_argument("--max-tokens", type=int, default=220)
86
+ parser.add_argument("--dataset", choices=sorted(DEFAULT_DATASETS), default="bbc2024_qwen_reference")
87
+ parser.add_argument("--prompt-style", choices=sorted(PROMPT_TEMPLATES), default="simple")
88
+ parser.add_argument("--limit", type=int, default=5)
89
+ parser.add_argument("--seed", type=int, default=7)
90
+ parser.add_argument("--max-article-chars", type=int, default=8000)
91
+ parser.add_argument("--disable-rouge", action="store_true")
92
+ parser.add_argument("--disable-bertscore", action="store_true")
93
+ parser.add_argument("--bertscore-model", default="roberta-large")
94
+ parser.add_argument("--output")
95
+ parser.add_argument("--resume", action="store_true")
96
+ parser.add_argument("--save-every", type=int, default=10)
97
+ parser.add_argument("--verbose", action="store_true")
98
+ return parser.parse_args()
99
+
100
+
101
+ def ensure_dataset(dataset_name: str) -> Path:
102
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
103
+ path = DATA_DIR / f"{dataset_name}.json"
104
+ if path.exists():
105
+ return path
106
+ url = DEFAULT_DATASETS[dataset_name]
107
+ with urlopen(url) as response:
108
+ path.write_bytes(response.read())
109
+ return path
110
+
111
+
112
+ def clip_article(text: str, max_chars: int) -> str:
113
+ article = re.sub(r"\s+", " ", text).strip()
114
+ if len(article) <= max_chars:
115
+ return article
116
+ clipped = article[:max_chars].rsplit(" ", 1)[0].strip()
117
+ return clipped or article[:max_chars].strip()
118
+
119
+
120
+ def load_cases(path: Path, limit: int, seed: int, max_article_chars: int) -> list[NewsSummaryCase]:
121
+ rows = json.loads(path.read_text())
122
+ rng = random.Random(seed)
123
+ sample = list(rows)
124
+ rng.shuffle(sample)
125
+ cases = []
126
+ for index, row in enumerate(sample[:limit], start=1):
127
+ article = clip_article(row["article"], max_article_chars)
128
+ reference_summary = row["qwen_reference_summary"].strip()
129
+ cases.append(
130
+ NewsSummaryCase(
131
+ case_id=f"news-{index:03d}",
132
+ article=article,
133
+ reference_summary=reference_summary,
134
+ source_url=row.get("url"),
135
+ )
136
+ )
137
+ return cases
138
+
139
+
140
+ def normalize_token(token: str) -> str:
141
+ return re.sub(r"[^a-z0-9]+", "", token.lower()).strip()
142
+
143
+
144
+ def tokenize(text: str) -> list[str]:
145
+ tokens = [normalize_token(part) for part in re.split(r"\s+", text)]
146
+ return [token for token in tokens if token]
147
+
148
+
149
+ def lcs_length(a: list[str], b: list[str]) -> int:
150
+ if not a or not b:
151
+ return 0
152
+ prev = [0] * (len(b) + 1)
153
+ for left in a:
154
+ curr = [0]
155
+ for j, right in enumerate(b, start=1):
156
+ if left == right:
157
+ curr.append(prev[j - 1] + 1)
158
+ else:
159
+ curr.append(max(prev[j], curr[-1]))
160
+ prev = curr
161
+ return prev[-1]
162
+
163
+
164
+ def score_text(prediction: str, reference: str) -> dict[str, float]:
165
+ pred_tokens = tokenize(prediction)
166
+ ref_tokens = tokenize(reference)
167
+ if not pred_tokens or not ref_tokens:
168
+ return {"token_f1": 0.0, "rouge_l_f1_approx": 0.0}
169
+
170
+ pred_counts: dict[str, int] = {}
171
+ for token in pred_tokens:
172
+ pred_counts[token] = pred_counts.get(token, 0) + 1
173
+
174
+ overlap = 0
175
+ for token in ref_tokens:
176
+ count = pred_counts.get(token, 0)
177
+ if count > 0:
178
+ overlap += 1
179
+ pred_counts[token] = count - 1
180
+
181
+ precision = overlap / len(pred_tokens)
182
+ recall = overlap / len(ref_tokens)
183
+ token_f1 = 0.0 if precision + recall == 0 else 2 * precision * recall / (precision + recall)
184
+
185
+ lcs = lcs_length(pred_tokens, ref_tokens)
186
+ rouge_precision = lcs / len(pred_tokens)
187
+ rouge_recall = lcs / len(ref_tokens)
188
+ rouge_l_f1 = 0.0 if rouge_precision + rouge_recall == 0 else 2 * rouge_precision * rouge_recall / (rouge_precision + rouge_recall)
189
+
190
+ return {
191
+ "token_f1": round(token_f1, 4),
192
+ "rouge_l_f1_approx": round(rouge_l_f1, 4),
193
+ }
194
+
195
+
196
+ def compute_rouge_scores(prediction: str, reference: str, disabled: bool) -> dict[str, float | None]:
197
+ if disabled or rouge_scorer is None:
198
+ return {"rouge1_f1": None, "rouge2_f1": None, "rougeL_f1": None}
199
+ scorer = rouge_scorer.RougeScorer(["rouge1", "rouge2", "rougeL"], use_stemmer=True)
200
+ scores = scorer.score(reference, prediction)
201
+ return {
202
+ "rouge1_f1": round(scores["rouge1"].fmeasure, 4),
203
+ "rouge2_f1": round(scores["rouge2"].fmeasure, 4),
204
+ "rougeL_f1": round(scores["rougeL"].fmeasure, 4),
205
+ }
206
+
207
+
208
+ def compute_bertscore(rows: list[dict[str, Any]], disabled: bool, model_type: str) -> None:
209
+ if disabled or bert_score_fn is None or not rows:
210
+ for row in rows:
211
+ row["scores"]["bertscore_f1"] = None
212
+ return
213
+
214
+ try:
215
+ predictions = [row["prediction"] for row in rows]
216
+ references = [row["reference_summary"] for row in rows]
217
+ _, _, f1 = bert_score_fn(
218
+ predictions,
219
+ references,
220
+ lang="en",
221
+ model_type=model_type,
222
+ verbose=False,
223
+ )
224
+ for row, value in zip(rows, f1.tolist(), strict=True):
225
+ row["scores"]["bertscore_f1"] = round(float(value), 4)
226
+ except Exception as exc:
227
+ for row in rows:
228
+ row["scores"]["bertscore_f1"] = None
229
+ row["scores"]["bertscore_error"] = str(exc)
230
+
231
+
232
+ def clean_summary(text: str) -> str:
233
+ cleaned = text.strip()
234
+ cleaned = cleaned.removeprefix("Summary:").strip()
235
+ cleaned = cleaned.removeprefix("The news summary is:").strip().strip('"')
236
+ cleaned = re.sub(r"\s+", " ", cleaned)
237
+ return cleaned
238
+
239
+
240
+ def build_messages(case: NewsSummaryCase, prompt_style: str, article_override: str | None = None) -> list[dict[str, str]]:
241
+ system = (
242
+ "You summarize news articles. "
243
+ "Return only the summary in plain text. "
244
+ "Do not add bullets, labels, or commentary."
245
+ )
246
+ user = PROMPT_TEMPLATES[prompt_style].format(article=article_override or case.article)
247
+ return [
248
+ {"role": "system", "content": system},
249
+ {"role": "user", "content": user},
250
+ ]
251
+
252
+
253
+ def build_prompt_text(messages: list[dict[str, str]]) -> str:
254
+ return "\n\n".join(f"{message['role'].upper()}:\n{message['content']}" for message in messages)
255
+
256
+
257
+ def evaluate_case(provider, args: argparse.Namespace, case: NewsSummaryCase) -> dict[str, Any]:
258
+ reduction_steps = [args.max_article_chars, 6000, 4000, 2500, 1500, 1000, 700]
259
+ response = None
260
+ prediction = ""
261
+ last_error: Exception | None = None
262
+ used_article = case.article
263
+ for char_limit in reduction_steps:
264
+ used_article = clip_article(case.article, min(len(case.article), char_limit))
265
+ messages = build_messages(case, args.prompt_style, article_override=used_article)
266
+ prompt_text = build_prompt_text(messages)
267
+ started = time.perf_counter()
268
+ try:
269
+ response = provider.generate(
270
+ {
271
+ "id": case.case_id,
272
+ "title": f"{args.dataset}:{case.case_id}",
273
+ "evaluationMode": "news_summarization",
274
+ },
275
+ messages,
276
+ prompt_text,
277
+ )
278
+ break
279
+ except HTTPError as exc:
280
+ last_error = exc
281
+ if exc.code != 400 or char_limit == reduction_steps[-1]:
282
+ raise
283
+ except Exception as exc: # noqa: BLE001
284
+ last_error = exc
285
+ raise
286
+
287
+ if response is None:
288
+ raise RuntimeError(f"Provider failed for {case.case_id}: {last_error}")
289
+
290
+ latency_ms = round(response.latency_ms or ((time.perf_counter() - started) * 1000), 2)
291
+ prediction = clean_summary(response.raw_text)
292
+ scores = score_text(prediction, case.reference_summary)
293
+ scores.update(compute_rouge_scores(prediction, case.reference_summary, args.disable_rouge))
294
+ scores["word_count"] = len(prediction.split())
295
+ return {
296
+ "case_id": case.case_id,
297
+ "article_chars": len(used_article),
298
+ "reference_summary": case.reference_summary,
299
+ "prediction": prediction,
300
+ "source_url": case.source_url,
301
+ "latency_ms": latency_ms,
302
+ "scores": scores,
303
+ "provider_metadata": response.metadata,
304
+ }
305
+
306
+
307
+ def summarize(rows: list[dict[str, Any]], args: argparse.Namespace) -> dict[str, Any]:
308
+ summary = {
309
+ "provider": args.provider,
310
+ "model": args.model,
311
+ "dataset": args.dataset,
312
+ "prompt_style": args.prompt_style,
313
+ "cases": len(rows),
314
+ "average_token_f1": round(sum(row["scores"]["token_f1"] for row in rows) / len(rows), 4),
315
+ "average_rouge_l_f1_approx": round(sum(row["scores"]["rouge_l_f1_approx"] for row in rows) / len(rows), 4),
316
+ "average_word_count": round(sum(row["scores"]["word_count"] for row in rows) / len(rows), 2),
317
+ "median_latency_ms": round(sorted(row["latency_ms"] for row in rows)[len(rows) // 2], 2),
318
+ }
319
+ for metric in ["rouge1_f1", "rouge2_f1", "rougeL_f1", "bertscore_f1"]:
320
+ present = [row["scores"][metric] for row in rows if row["scores"].get(metric) is not None]
321
+ summary[f"average_{metric}"] = round(sum(present) / len(present), 4) if present else None
322
+ return summary
323
+
324
+
325
+ def default_output_path(args: argparse.Namespace) -> Path:
326
+ return RESULTS_DIR / f"{args.provider}-{safe_slug(args.model)}-{args.dataset}-{args.prompt_style}-seed{args.seed}-limit{args.limit}.json"
327
+
328
+
329
+ def write_progress(output_path: Path, rows: list[dict[str, Any]], args: argparse.Namespace, *, final: bool) -> None:
330
+ output_path.parent.mkdir(parents=True, exist_ok=True)
331
+ if final:
332
+ payload = {"summary": summarize(rows, args), "rows": rows}
333
+ else:
334
+ payload = {
335
+ "summary": {
336
+ "provider": args.provider,
337
+ "model": args.model,
338
+ "dataset": args.dataset,
339
+ "prompt_style": args.prompt_style,
340
+ "cases_completed": len(rows),
341
+ "finalized": False,
342
+ },
343
+ "rows": rows,
344
+ }
345
+ output_path.write_text(json.dumps(payload, indent=2))
346
+
347
+
348
+ def main() -> int:
349
+ args = parse_args()
350
+ dataset_path = ensure_dataset(args.dataset)
351
+ cases = load_cases(dataset_path, limit=args.limit, seed=args.seed, max_article_chars=args.max_article_chars)
352
+ if not cases:
353
+ raise SystemExit("No news summarization cases selected.")
354
+
355
+ RESULTS_DIR.mkdir(parents=True, exist_ok=True)
356
+ output_path = Path(args.output) if args.output else default_output_path(args)
357
+ provider = create_provider(args)
358
+ rows: list[dict[str, Any]] = []
359
+ completed_case_ids: set[str] = set()
360
+ if args.resume and output_path.exists():
361
+ existing = json.loads(output_path.read_text())
362
+ rows = existing.get("rows", [])
363
+ completed_case_ids = {row["case_id"] for row in rows}
364
+ print(f"Resuming from {output_path} with {len(rows)} completed cases.")
365
+
366
+ pending_cases = [case for case in cases if case.case_id not in completed_case_ids]
367
+ for index, case in enumerate(pending_cases, start=len(rows) + 1):
368
+ row = evaluate_case(provider, args, case)
369
+ rows.append(row)
370
+ if args.save_every > 0 and len(rows) % args.save_every == 0:
371
+ write_progress(output_path, rows, args, final=False)
372
+ print(f"Saved progress at {len(rows)}/{len(cases)} cases -> {output_path}")
373
+ if args.verbose:
374
+ print(
375
+ f"[{index:02d}] {case.case_id} "
376
+ f"token_f1={row['scores']['token_f1']:.4f} "
377
+ f"rouge_l_approx={row['scores']['rouge_l_f1_approx']:.4f} "
378
+ f"words={row['scores']['word_count']}"
379
+ )
380
+ print(f"PRED: {row['prediction']}")
381
+ print(f"REF: {case.reference_summary}")
382
+ print()
383
+
384
+ compute_bertscore(rows, args.disable_bertscore, args.bertscore_model)
385
+ summary = summarize(rows, args)
386
+ print(json.dumps(summary, indent=2))
387
+ write_progress(output_path, rows, args, final=True)
388
+ print(f"Wrote results to {output_path}")
389
+ return 0
390
+
391
+
392
+ if __name__ == "__main__":
393
+ raise SystemExit(main())