yutong.song commited on
Commit
07965b5
·
1 Parent(s): 4ffd5f7

auto-save-before-sync-2025-12-08-113135

Browse files
compute_rouge_lamp4.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ compute_rouge_lamp4.py
6
+
7
+ Compute ROUGE-1 and ROUGE-L (F1) on a JSON predictions file of the form:
8
+
9
+ [
10
+ {
11
+ "gold": "reference headline",
12
+ "prediction": "model headline",
13
+ ...
14
+ },
15
+ ...
16
+ ]
17
+
18
+ Usage:
19
+
20
+ python compute_rouge_lamp4.py \
21
+ --input /opt/tiger/PLLM2.0/results_lamp4_cluster12_lora_vllm.json
22
+ """
23
+
24
+ import json
25
+ import argparse
26
+ from typing import List, Dict, Any
27
+
28
+ from rouge_score import rouge_scorer
29
+ from tqdm import tqdm
30
+
31
+
32
+ def load_predictions(path: str) -> List[Dict[str, Any]]:
33
+ with open(path, "r", encoding="utf-8") as f:
34
+ data = json.load(f)
35
+ if not isinstance(data, list):
36
+ raise ValueError(f"Input JSON must be a list, got {type(data)}")
37
+ return data
38
+
39
+
40
+ def compute_rouge(
41
+ records: List[Dict[str, Any]],
42
+ ref_key: str = "gold",
43
+ pred_key: str = "prediction",
44
+ ) -> Dict[str, float]:
45
+ scorer = rouge_scorer.RougeScorer(["rouge1", "rougeL"], use_stemmer=True)
46
+
47
+ total_r1_f = 0.0
48
+ total_rl_f = 0.0
49
+ count = 0
50
+
51
+ for rec in tqdm(records, desc="Computing ROUGE"):
52
+ ref = str(rec.get(ref_key, "") or "").strip()
53
+ pred = str(rec.get(pred_key, "") or "").strip()
54
+
55
+ if ref == "" and pred == "":
56
+ continue # skip completely empty pairs
57
+
58
+ scores = scorer.score(ref, pred)
59
+ total_r1_f += scores["rouge1"].fmeasure
60
+ total_rl_f += scores["rougeL"].fmeasure
61
+ count += 1
62
+
63
+ if count == 0:
64
+ return {"rouge1_f": 0.0, "rougeL_f": 0.0, "count": 0}
65
+
66
+ return {
67
+ "rouge1_f": total_r1_f / count,
68
+ "rougeL_f": total_rl_f / count,
69
+ "count": count,
70
+ }
71
+
72
+
73
+ def main():
74
+ parser = argparse.ArgumentParser(description="Compute ROUGE-1 and ROUGE-L on LaMP-4 style predictions JSON.")
75
+ parser.add_argument("--input", type=str, required=True, help="Path to predictions JSON file.")
76
+ parser.add_argument("--ref_key", type=str, default="gold", help="Key for reference text in each record.")
77
+ parser.add_argument("--pred_key", type=str, default="prediction", help="Key for prediction text in each record.")
78
+
79
+ args = parser.parse_args()
80
+
81
+ records = load_predictions(args.input)
82
+ metrics = compute_rouge(records, ref_key=args.ref_key, pred_key=args.pred_key)
83
+
84
+ print("\n=== ROUGE results ===")
85
+ print(f"Count : {metrics['count']}")
86
+ print(f"ROUGE-1 F1 : {metrics['rouge1_f']:.4f}")
87
+ print(f"ROUGE-L F1 : {metrics['rougeL_f']:.4f}")
88
+
89
+
90
+ if __name__ == "__main__":
91
+ main()
inference_lamp4_cluster_lora_vllm.py CHANGED
@@ -15,7 +15,7 @@ python inference_lamp4_cluster_lora_vllm.py \
15
  --cluster_info_path /opt/tiger/PLLM2.0/clustering_lamp4/cluster_info_k60_kmeans.json\
16
  --cluster_id 12 \
17
  --output_file /opt/tiger/PLLM2.0/results_lamp4_cluster12_lora_vllm.json \
18
- --max_new_tokens 64 \
19
  --tensor_parallel_size 4
20
 
21
  """
@@ -148,7 +148,7 @@ def convert_lamp4_data_for_eval(
148
  text = article_obj.get("text", "")
149
  if title and text:
150
  if len(text) > 1000:
151
- text = text[:1000]
152
  profile_data.append({"title": title, "text": text})
153
 
154
  samples.append(
@@ -188,6 +188,21 @@ def load_lamp4_eval_data(questions_path: str, outputs_path: str) -> List[Dict[st
188
 
189
 
190
  # ---------- Cluster info ----------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
 
192
  def load_cluster_info(cluster_info_path: str) -> Dict[str, Any]:
193
  print(f"Loading cluster info from: {cluster_info_path}")
@@ -329,10 +344,11 @@ def run_inference_for_cluster_vllm(
329
  for sample, out in zip(cluster_samples, outputs):
330
  # vLLM: each out.outputs is a list of candidates; we take the first one
331
  if not out.outputs:
332
- pred_text = ""
333
  else:
334
- pred_text = out.outputs[0].text.strip()
335
 
 
336
  results.append(
337
  {
338
  "user_id": sample["user_id"],
 
15
  --cluster_info_path /opt/tiger/PLLM2.0/clustering_lamp4/cluster_info_k60_kmeans.json\
16
  --cluster_id 12 \
17
  --output_file /opt/tiger/PLLM2.0/results_lamp4_cluster12_lora_vllm.json \
18
+ --max_new_tokens 128 \
19
  --tensor_parallel_size 4
20
 
21
  """
 
148
  text = article_obj.get("text", "")
149
  if title and text:
150
  if len(text) > 1000:
151
+ text = text
152
  profile_data.append({"title": title, "text": text})
153
 
154
  samples.append(
 
188
 
189
 
190
  # ---------- Cluster info ----------
191
+ def clean_prediction(text: str) -> str:
192
+ """
193
+ Clean model prediction:
194
+ - strip leading/trailing whitespace
195
+ - if wrapped in a single pair of quotes ("...") or ('...'), remove them
196
+ """
197
+ if not text:
198
+ return text
199
+ t = text.strip()
200
+
201
+ # remove surrounding normal quotes
202
+ if len(t) >= 2 and ((t[0] == '"' and t[-1] == '"') or (t[0] == "'" and t[-1] == "'")):
203
+ t = t[1:-1].strip()
204
+
205
+ return t
206
 
207
  def load_cluster_info(cluster_info_path: str) -> Dict[str, Any]:
208
  print(f"Loading cluster info from: {cluster_info_path}")
 
344
  for sample, out in zip(cluster_samples, outputs):
345
  # vLLM: each out.outputs is a list of candidates; we take the first one
346
  if not out.outputs:
347
+ raw_pred = ""
348
  else:
349
+ raw_pred = out.outputs[0].text.strip()
350
 
351
+ pred_text = clean_prediction(raw_pred)
352
  results.append(
353
  {
354
  "user_id": sample["user_id"],
results_lamp4_cluster12_lora_vllm.json CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:6efa919f7bab53f2c2f4f56b6734c6652c027bd3d35ef3015b05d68aac6ed4b8
3
- size 223549
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7124e711b49472c796ca79f1eacacec5b9f7b5797b27aa747da4df810ad6d03
3
+ size 223526