-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdpo_train_mt.py
More file actions
1564 lines (1347 loc) · 67.1 KB
/
dpo_train_mt.py
File metadata and controls
1564 lines (1347 loc) · 67.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
dpo_train_reddit_finance.py — DPO on Reddit Finance (43 subreddits, 250k post↔comment pairs),
while KEEPING TAT-QA eval + MT-Bench + instruction-following eval from the original script.
Training data construction (explicit preferences):
- Group rows by post `id` from HF dataset winddude/reddit_finance_43_250k (GPL-3.0).
- For each post, rank top-level comments by `comment_normalized_score`.
- chosen = highest-scored comment; rejected = lower-scored sibling with score gap ≥ margin
(fallback to the lowest-scored sibling if needed). Optional length-similarity filter.
Prompt format (turn-level):
SUBREDDIT: r/<subreddit>
TITLE: <title>
POST: <selftext or "(no selftext)">
---
Reply like a helpful finance assistant. Be specific, polite, and practical.
References:
- HF dataset + schema preview (id/title/selftext/body/comment_normalized_score/...):
https://huggingface.co/datasets/winddude/reddit_finance_43_250k
- Kaggle mirror/description: "Reddit Finance 43 (250k)"
"""
import argparse
import hashlib
import json
import random
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Tuple
import torch
from datasets import load_dataset, Dataset
from transformers import (
AutoTokenizer,
AutoModelForCausalLM,
BitsAndBytesConfig,
TrainingArguments,
)
from peft import LoraConfig, get_peft_model
from trl import DPOTrainer as _TRL_DPOTrainer
# Keep your DPOConfig import/patch for TRL versions
from trl.trainer.dpo_config import DPOConfig
# --------------------------------------------------------------------------------------
# Patch: align DPOTrainer.log signature with Transformers Trainer calling pattern
# --------------------------------------------------------------------------------------
class DPOTrainer(_TRL_DPOTrainer):
def log(self, logs, *args, **kwargs): # compat with start_time, etc.
return super().log(logs)
# --------------------------------------------------------------------------------------
# Helpers
# --------------------------------------------------------------------------------------
def _seed_from_uid(uid: str, seed: int) -> int:
import hashlib as _hashlib
h = _hashlib.sha256((str(seed) + "|" + str(uid)).encode()).hexdigest()
return int(h[:8], 16)
def load_causal_lm(model_id: str, use_4bit: bool, dtype_compute):
if use_4bit:
bnb_cfg = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=dtype_compute)
return AutoModelForCausalLM.from_pretrained(
model_id, quantization_config=bnb_cfg, trust_remote_code=True, device_map="auto"
)
return AutoModelForCausalLM.from_pretrained(
model_id, torch_dtype=dtype_compute, trust_remote_code=True, device_map="auto"
)
# --------------------------------------------------------------------------------------
# Reddit Finance 43 → DPO pairs
# --------------------------------------------------------------------------------------
def build_reddit_prompt(subreddit: str, title: str, selftext: str, max_chars: int) -> str:
st = (selftext or "").strip()
if max_chars and len(st) > max_chars:
st = st[:max_chars].rsplit(" ", 1)[0] + " ..."
title = (title or "").strip()
sub = subreddit or ""
return (
f"SUBREDDIT: r/{sub}\n"
f"TITLE: {title if title else '(no title)'}\n"
f"POST: {st if st else '(no selftext)'}\n"
"---\n"
"Reply like a helpful finance assistant. Be specific, polite, and practical."
)
def reddit_finance_to_dpo_pairs(
ds_iter: Iterable[Dict[str, Any]],
*,
min_post_chars: int = 120,
min_comment_chars: int = 40,
max_post_chars: int = 3000,
score_margin: float = 0.10,
length_tol: float = 0.6,
max_pairs_per_post: int = 1,
seed: int = 42,
) -> Iterable[Dict[str, str]]:
"""
Construct DPO {prompt, chosen, rejected} triples from reddit_finance_43_250k.
Heuristics:
- Skip posts with too-short post text OR with <2 qualifying comments.
- chosen := highest comment_normalized_score
- rejected := a sibling whose score is lower by ≥ score_margin and whose length
is within ±length_tol * len(chosen) (to reduce length bias). If none, pick the
lowest-scored sibling.
"""
# Group by post id
groups: Dict[str, Dict[str, Any]] = {}
for ex in ds_iter:
pid = ex.get("id") or ""
if not pid:
continue
sub = ex.get("subreddit") or ""
title = ex.get("title") or ""
selftext = ex.get("selftext") or ""
# Basic post length gate (title + selftext)
post_len = len((title or "")) + len((selftext or ""))
if post_len < min_post_chars:
# Keep collecting comments anyway so we can maybe still hit the min
pass
c_body = (ex.get("body") or "").strip()
if not c_body or len(c_body) < min_comment_chars:
continue
c_score = ex.get("comment_normalized_score")
try:
c_score = float(c_score) if c_score is not None else 0.0
except Exception:
c_score = 0.0
g = groups.get(pid)
if not g:
g = {
"pid": pid,
"subreddit": sub,
"title": title,
"selftext": selftext,
"comments": [], # list of (score, text)
}
groups[pid] = g
g["comments"].append((c_score, c_body))
rnd = random.Random(seed)
for pid, g in groups.items():
comments: List[Tuple[float, str]] = sorted(g["comments"], key=lambda x: x[0], reverse=True)
if len(comments) < 2:
continue
prompt = build_reddit_prompt(g["subreddit"], g["title"], g["selftext"], max_chars=max_post_chars)
if len(prompt) < min_post_chars:
# If even the full prompt is too short, skip
continue
chosen_score, chosen_text = comments[0]
# Find a lower-scored sibling with margin + length similarity
rejected_text = None
for s, t in comments[1:]:
if (chosen_score - s) >= score_margin:
# length similarity gate
if len(chosen_text) == 0: # guard
continue
rel_gap = abs(len(t) - len(chosen_text)) / max(1, len(chosen_text))
if rel_gap <= length_tol:
rejected_text = t
break
# Fallback: the worst one
if rejected_text is None:
rejected_text = comments[-1][1]
# Final sanity
if not chosen_text or not rejected_text:
continue
if chosen_text.strip().lower() == rejected_text.strip().lower():
continue
# Optional: slight shuffle to avoid degenerate ordering bias (not needed for DPO but harmless)
if rnd.random() < 0.0:
chosen_text, rejected_text = rejected_text, chosen_text
yield {"prompt": prompt, "chosen": chosen_text, "rejected": rejected_text}
def finance_instruct_to_dpo_pairs(
model, tokenizer, num_pairs: int = 5000, max_new_tokens: int = 256, seed: int = 42
) -> List[Dict[str, str]]:
"""
Generate DPO preference pairs from Finance-Instruct-500k dataset.
Strategy:
1. Sample financial instructions from Finance-Instruct-500k
2. Use current model to generate responses
3. Use reference responses as "chosen", generated responses as "rejected"
4. This teaches the model to prefer high-quality financial instruction responses
"""
from datasets import load_dataset
import random
print(f"[finance-instruct] Loading Finance-Instruct dataset...")
finance_ds = load_dataset("Josephgflowers/Finance-Instruct-500k", split="train")
# Sample random instructions
rnd = random.Random(seed)
indices = rnd.sample(range(len(finance_ds)), min(num_pairs, len(finance_ds)))
pairs = []
model.eval()
print(f"[finance-instruct] Generating {len(indices)} DPO pairs...")
# Suppress generation warnings
try:
from transformers.utils import logging as hf_logging
_prev_level = hf_logging.get_verbosity()
hf_logging.set_verbosity_error()
except Exception:
_prev_level = None
gen_kwargs = {"max_new_tokens": max_new_tokens, "do_sample": True, "temperature": 0.8, "top_p": 0.9}
for i, idx in enumerate(indices):
try:
example = finance_ds[idx]
instruction = example.get('user', example.get('instruction', ''))
reference_response = example.get('assistant', example.get('output', ''))
if not instruction or not reference_response:
continue
# Generate response with current model
messages = [
{"role": "system", "content": "You are a helpful financial advisor."},
{"role": "user", "content": instruction},
]
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
with torch.no_grad():
out_ids = model.generate(**inputs, **gen_kwargs)
generated_response = tokenizer.decode(out_ids[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip()
# Use reference as chosen, generated as rejected (teaches model to prefer high-quality responses)
pairs.append({
"prompt": f"You are a helpful financial advisor.\n\nUser: {instruction}\n\nAssistant:",
"chosen": reference_response.strip(),
"rejected": generated_response.strip()
})
if (i + 1) % 100 == 0:
print(f"[finance-instruct] Generated {i+1}/{len(indices)} pairs")
except Exception as e:
print(f"[warn] Finance-Instruct pair generation failed for example {i+1}: {e}")
continue
# Restore logging level
try:
if _prev_level is not None:
hf_logging.set_verbosity(_prev_level)
except Exception:
pass
print(f"[finance-instruct] Generated {len(pairs)} Finance-Instruct DPO pairs")
return pairs
def load_general_dpo_pairs(dataset_name: str, num_pairs: int, seed: int = 42) -> List[Dict[str, Any]]:
"""
Load general instruction DPO pairs from a public dataset.
"""
print(f"[general] Loading general DPO dataset: {dataset_name}")
try:
if dataset_name == "Intel/orca_dpo_pairs":
# Load Intel Orca DPO dataset
dataset = load_dataset("Intel/orca_dpo_pairs", split="train")
print(f"[general] Loaded {len(dataset)} general examples")
# Sample random pairs
import random
random.seed(seed)
indices = random.sample(range(len(dataset)), min(num_pairs, len(dataset)))
pairs = []
for i in indices:
example = dataset[i]
pair = {
"prompt": example["system"] + "\n\n" + example["question"],
"chosen": example["chosen"],
"rejected": example["rejected"]
}
pairs.append(pair)
elif dataset_name == "Anthropic/hh-rlhf":
# Load Anthropic HH-RLHF dataset
dataset = load_dataset("Anthropic/hh-rlhf", "chosen", split="train")
rejected_dataset = load_dataset("Anthropic/hh-rlhf", "rejected", split="train")
# Sample and create pairs
import random
random.seed(seed)
indices = random.sample(range(min(len(dataset), len(rejected_dataset))),
min(num_pairs, len(dataset)))
pairs = []
for i in indices:
pair = {
"prompt": dataset[i]["chosen"].split("Assistant:")[0] + "Assistant:",
"chosen": dataset[i]["chosen"].split("Assistant:")[-1],
"rejected": rejected_dataset[i]["rejected"].split("Assistant:")[-1]
}
pairs.append(pair)
else:
# Generic DPO dataset loading
dataset = load_dataset(dataset_name, split="train")
import random
random.seed(seed)
indices = random.sample(range(len(dataset)), min(num_pairs, len(dataset)))
pairs = []
for i in indices:
example = dataset[i]
pair = {
"prompt": example.get("prompt", example.get("question", "")),
"chosen": example.get("chosen", example.get("response_chosen", "")),
"rejected": example.get("rejected", example.get("response_rejected", ""))
}
pairs.append(pair)
except Exception as e:
print(f"[warn] Failed to load general dataset {dataset_name}: {e}")
print("[warn] Continuing without general pairs...")
return []
print(f"[general] Created {len(pairs)} general DPO pairs")
return pairs
# --------------------------------------------------------------------------------------
# TAT-QA EVAL (unchanged from your original, with safe JSON streaming)
# --------------------------------------------------------------------------------------
def _markdown_table(table_2d: List[List[str]], max_rows: int, max_cols: int) -> str:
if not table_2d:
return ""
rows = [list(map(lambda c: (c or "").strip(), r[:max_cols])) for r in table_2d[:max_rows]]
if not rows:
return ""
if len(rows) == 1:
rows.append([""] * len(rows[0]))
header = rows[0]
sep = ["---"] * len(header)
body = rows[1:]
def pipe(r): return "| " + " | ".join(r) + " |"
return "\n".join([pipe(header), pipe(sep)] + [pipe(r) for r in body])
def _select_paragraphs(paragraphs: List[Dict[str, Any]],
rel_orders: List[Any],
only_rel: bool,
max_chars: int) -> str:
if only_rel and rel_orders:
rel = set(map(str, rel_orders))
keep = [p.get("text", "") for p in sorted(paragraphs, key=lambda x: x.get("order", 1))
if str(p.get("order", "")) in rel]
text = "\n\n".join(keep)
else:
text = "\n\n".join(p.get("text", "") for p in sorted(paragraphs, key=lambda x: x.get("order", 1)))
text = text.strip()
if len(text) > max_chars:
text = text[:max_chars].rsplit(" ", 1)[0] + " ..."
return text
def iter_tatqa_examples(split: str):
file_by_split = {
"train": "tatqa_dataset_train.json",
"validation": "tatqa_dataset_dev.json",
"test": "tatqa_dataset_test.json",
}
try:
from huggingface_hub import hf_hub_download
local_path = hf_hub_download(repo_id="next-tat/TAT-QA", filename=file_by_split[split])
with open(local_path, "r", encoding="utf-8") as f:
data = json.load(f)
for ex in data:
yield ex
return
except Exception:
pass
# Fallback to GitHub raw URLs
url_map = {
"train": "https://raw.githubusercontent.com/NExTplusplus/TAT-QA/master/dataset_raw/tatqa_dataset_train.json",
"validation": "https://raw.githubusercontent.com/NExTplusplus/TAT-QA/master/dataset_raw/tatqa_dataset_dev.json",
"test": "https://raw.githubusercontent.com/NExTplusplus/TAT-QA/master/dataset_raw/tatqa_dataset_test.json",
}
import requests
resp = requests.get(url_map[split], timeout=120)
resp.raise_for_status()
for ex in resp.json():
yield ex
# --------------------------------------------------------------------------------------
# EVAL HELPERS (kept from your script)
# --------------------------------------------------------------------------------------
import re
def _normalize_text(s: str) -> str:
s = (s or "").lower().strip()
s = re.sub(r"\s+", " ", s)
s = re.sub(r"[\t\n\r]", " ", s)
s = re.sub(r"[^\w\s\.\-]", "", s)
return s
from typing import Optional
def _extract_number(text: str) -> Optional[float]:
if not text:
return None
m = re.search(r"[-+]?\d+[\d,]*\.?\d*", text.replace(",", ""))
if not m:
return None
try:
return float(m.group(0))
except Exception:
return None
def _score(ans_type: str, gold, pred: str, scale: str) -> bool:
if ans_type in ("arithmetic", "counting"):
g = _extract_number(str(gold))
p = _extract_number(pred)
if g is None or p is None:
return False
tol = max(0.5, 0.05 * abs(g))
return abs(g - p) <= tol
# spans/others: containment
gold_texts = [str(x) for x in (gold if isinstance(gold, list) else [gold])]
pred_n = _normalize_text(pred)
return any(_normalize_text(g) in pred_n for g in gold_texts)
def _tatqa_eval_items(args, split: str, limit: int):
count = 0
for ex in iter_tatqa_examples(split):
table = (ex.get("table") or {})
table_2d = (table.get("table") or [])
paragraphs = ex.get("paragraphs") or []
questions = ex.get("questions") or []
if isinstance(questions, dict):
questions = [questions]
elif not isinstance(questions, list):
continue
for q in questions:
q_uid = q.get("uid") or f"{ex.get('uid','')}-{q.get('order','')}"
ans_type = (q.get("answer_type") or "").lower()
scale = (q.get("scale") or "None")
rel_pars = q.get("rel_paragraphs") or []
question_text = q.get("question") or ""
gold = q.get("answer")
md_table = _markdown_table(table_2d, args.tatqa_table_rows, args.tatqa_table_cols)
paras_text = _select_paragraphs(paragraphs, rel_pars, args.tatqa_only_rel_paras, args.tatqa_para_chars)
prompt = (
"You are a financial analyst. Use the TABLE and the PASSAGES to answer.\n\n"
"TABLE:\n" + (md_table if md_table else "(no table)") + "\n\n"
"PASSAGES:\n" + (paras_text if paras_text else "(no passages)") + "\n\n"
f"Question: {question_text}\n"
"Answer:"
)
yield {
"q_uid": q_uid,
"prompt": prompt,
"gold": gold,
"ans_type": ans_type,
"scale": scale,
}
count += 1
if limit and count >= limit:
return
# --------------------------------------------------------------------------------------
# Generation + evaluation runners (kept from your script)
# --------------------------------------------------------------------------------------
def run_mtbench_eval(eval_model, eval_tok, questions_file: str, limit: int, max_tokens: int, save_path: str = ""):
"""Run MT-Bench style evaluation with optional reward model scoring"""
if not Path(questions_file).exists():
print(f"[warn] MT-Bench file {questions_file} not found, skipping MT-Bench eval")
return {"n": 0, "questions_completed": 0, "avg_score": 0.0}
try:
with open(questions_file, "r", encoding="utf-8") as f:
data = json.load(f)
# Process questions
questions = []
for i, obj in enumerate(data):
qid = obj.get("id", str(i))
cat = obj.get("category", obj.get("sub_category", ""))
if "turns" in obj and isinstance(obj["turns"], list) and obj["turns"]:
prompt = "\n\n".join(map(str, obj["turns"]))
else:
prompt = obj.get("prompt") or obj.get("question") or obj.get("text") or ""
questions.append({"id": qid, "category": cat, "prompt": prompt})
if limit and limit > 0:
questions = questions[:limit]
results = []
eval_model.eval()
# Try to load Skywork reward model for scoring
reward_model = None
reward_tokenizer = None
try:
from transformers import AutoModelForSequenceClassification
print("[mtbench] Loading Skywork reward model for scoring...")
reward_tokenizer = AutoTokenizer.from_pretrained("Skywork/Skywork-Reward-V2-Qwen3-0.6B", trust_remote_code=True)
reward_model = AutoModelForSequenceClassification.from_pretrained(
"Skywork/Skywork-Reward-V2-Qwen3-0.6B",
trust_remote_code=True,
device_map="auto",
torch_dtype=torch.bfloat16
)
reward_model.eval()
print("[mtbench] Reward model loaded successfully")
except Exception as e:
print(f"[warn] Could not load reward model: {e}")
print("[mtbench] Continuing without scoring...")
# Generation settings - use greedy decoding for consistency
gen_kwargs = {"max_new_tokens": max_tokens, "do_sample": False, "num_beams": 1}
total_score = 0.0
scored_count = 0
# Suppress noisy generation warnings
try:
from transformers.utils import logging as hf_logging
_prev_level = hf_logging.get_verbosity()
hf_logging.set_verbosity_error()
except Exception:
_prev_level = None
for i, q in enumerate(questions):
prompt = q["prompt"]
# Use chat template for better responses
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt},
]
prompt = eval_tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = eval_tok(prompt, return_tensors="pt").to(eval_model.device)
with torch.no_grad():
out_ids = eval_model.generate(**inputs, **gen_kwargs)
answer = eval_tok.decode(out_ids[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip()
# Score with reward model if available
score = None
if reward_model and reward_tokenizer:
try:
score = score_with_reward_model(q["prompt"], answer, reward_model, reward_tokenizer)
total_score += score
scored_count += 1
except Exception as e:
print(f"[warn] Scoring failed for question {i+1}: {e}")
results.append({
"id": q["id"],
"category": q["category"],
"prompt": q["prompt"],
"answer": answer,
"score": score
})
if (i + 1) % 10 == 0:
print(f"[mtbench] Processed {i+1}/{len(questions)} questions")
# Restore logging level
try:
if _prev_level is not None:
from transformers.utils import logging as hf_logging
hf_logging.set_verbosity(_prev_level)
except Exception:
pass
avg_score = (total_score / scored_count) if scored_count > 0 else 0.0
if avg_score > 0:
print(f"MT-Bench eval completed — N={len(results)} questions, avg score: {avg_score:.2f}/10")
else:
print(f"MT-Bench eval completed — N={len(results)} questions (no scoring)")
if save_path:
with open(save_path, "w", encoding="utf-8") as f:
for r in results:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
print(f"Saved MT-Bench results to {save_path}")
return {"n": len(results), "questions_completed": len(results), "avg_score": avg_score, "scored_count": scored_count}
except Exception as e:
print(f"[warn] MT-Bench evaluation failed: {e}")
return {"n": 0, "questions_completed": 0, "avg_score": 0.0}
def score_with_reward_model(question, response, reward_model, reward_tokenizer):
"""Score a response using the Skywork reward model."""
# Format the conversation for the reward model
conversation = [
{"role": "user", "content": question},
{"role": "assistant", "content": response}
]
# Apply chat template
conversation_text = reward_tokenizer.apply_chat_template(
conversation,
tokenize=False,
add_generation_prompt=False
)
# Tokenize for the reward model
inputs = reward_tokenizer(
conversation_text,
return_tensors="pt",
truncation=True,
max_length=1024,
padding=True
)
inputs = {k: v.to(reward_model.device) for k, v in inputs.items()}
with torch.no_grad():
# Get reward score
outputs = reward_model(**inputs)
reward_score = outputs.logits.squeeze().float().item()
# Convert reward score to 1-10 scale
if reward_score < 0:
# Map negative scores (e.g., [-5, 5]) to [0, 1]
normalized_score = (reward_score + 5) / 10
else:
# Map positive scores to [0, 1]
normalized_score = min(1.0, reward_score / 5.0) if reward_score > 1 else reward_score
# Scale to 1-10 range
final_score = 1.0 + (normalized_score * 9.0)
final_score = max(1.0, min(10.0, final_score))
return final_score
def run_instruct_eval(eval_model, eval_tok, limit: int, max_tokens: int, save_path: str = ""):
"""Run instruction following evaluation using Finance-Instruct-500k dataset with reward model scoring"""
print("[instruct] Running Finance-Instruct instruction eval")
# Load Skywork reward model for scoring
print("[instruct] Loading Skywork reward model for scoring...")
try:
from transformers import AutoModelForSequenceClassification, AutoTokenizer
reward_model_name = "Skywork/Skywork-Reward-V2-Qwen3-0.6B"
reward_model = AutoModelForSequenceClassification.from_pretrained(
reward_model_name,
torch_dtype=torch.bfloat16,
device_map="auto",
trust_remote_code=True
)
reward_tokenizer = AutoTokenizer.from_pretrained(reward_model_name, trust_remote_code=True)
print("[instruct] Reward model loaded successfully")
except Exception as e:
print(f"[warn] Failed to load reward model: {e}")
return {"n": 0, "avg_score": 0.0, "tasks_completed": 0}
# Load Finance-Instruct-500k dataset
try:
from datasets import load_dataset
dataset = load_dataset("Josephgflowers/Finance-Instruct-500k", split="train")
print(f"[instruct] Loaded {len(dataset)} Finance-Instruct examples")
except Exception as e:
print(f"[warn] Failed to load Finance-Instruct dataset: {e}")
return {"n": 0, "avg_score": 0.0, "tasks_completed": 0}
# Sample evaluation examples
import random
random.seed(42) # Consistent sampling
eval_indices = random.sample(range(len(dataset)), min(limit, len(dataset)))
results = []
total_score = 0.0
successful_evals = 0
eval_model.eval()
# Suppress generation warnings
try:
from transformers.utils import logging as hf_logging
_prev_level = hf_logging.get_verbosity()
hf_logging.set_verbosity_error()
except Exception:
_prev_level = None
for i, idx in enumerate(eval_indices):
try:
example = dataset[idx]
# Extract instruction from the dataset
# Finance-Instruct-500k uses 'user' field for instruction
if 'user' in example:
instruction = example['user']
elif 'instruction' in example:
instruction = example['instruction']
else:
print(f"[warn] No instruction field found in example {i+1}")
continue
# Generate response using chat template
messages = [
{"role": "system", "content": "You are a helpful financial assistant that follows instructions carefully."},
{"role": "user", "content": instruction}
]
prompt = eval_tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = eval_tok(prompt, return_tensors="pt", truncation=True, max_length=2048).to(eval_model.device)
with torch.no_grad():
gen_kwargs = {
"max_new_tokens": max_tokens,
"do_sample": True,
"temperature": 0.7,
"top_p": 0.9,
"pad_token_id": eval_tok.eos_token_id
}
out_ids = eval_model.generate(**inputs, **gen_kwargs)
# Decode response
generated_text = eval_tok.decode(
out_ids[0][inputs["input_ids"].shape[1]:],
skip_special_tokens=True
).strip()
# Score with reward model (same as MT-Bench)
reward_score = score_with_reward_model(instruction, generated_text, reward_model, reward_tokenizer)
results.append({
"idx": idx,
"instruction": instruction[:200] + "..." if len(instruction) > 200 else instruction,
"response": generated_text,
"reward_score": reward_score,
"reference_answer": example.get('assistant', example.get('output', ''))[:100] + "..." if example.get('assistant', example.get('output', '')) else None
})
total_score += reward_score
successful_evals += 1
if (i + 1) % 5 == 0:
print(f"[instruct] Evaluated {i+1}/{len(eval_indices)} instructions")
except Exception as e:
print(f"[warn] Instruction evaluation failed for example {i+1}: {e}")
continue
# Restore logging level
try:
if _prev_level is not None:
from transformers.utils import logging as hf_logging
hf_logging.set_verbosity(_prev_level)
except Exception:
pass
avg_score = total_score / successful_evals if successful_evals > 0 else 0.0
success_rate = (sum(1 for r in results if r["reward_score"] >= 7.0) / successful_evals * 100) if successful_evals > 0 else 0.0
print(f"Finance-Instruct eval completed — N={successful_evals} instructions, avg score: {avg_score:.2f}/10, success rate: {success_rate:.1f}%")
if save_path:
with open(save_path, "w", encoding="utf-8") as f:
for r in results:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
print(f"Saved Finance-Instruct results to {save_path}")
return {"n": successful_evals, "tasks_completed": successful_evals, "avg_score": avg_score, "success_rate": success_rate}
def run_reddit_reward_eval(eval_model, eval_tok, limit: int = 100, max_tokens: int = 256, save_path: str = ""):
"""Evaluate Reddit Finance test set using reward model scoring."""
print("[reddit] Running Reddit Finance reward evaluation")
# Load Skywork reward model for scoring
print("[reddit] Loading Skywork reward model for scoring...")
try:
from transformers import AutoModelForSequenceClassification, AutoTokenizer
reward_model_name = "Skywork/Skywork-Reward-V2-Qwen3-0.6B"
reward_model = AutoModelForSequenceClassification.from_pretrained(
reward_model_name,
torch_dtype=torch.bfloat16,
device_map="auto",
trust_remote_code=True
)
reward_tokenizer = AutoTokenizer.from_pretrained(reward_model_name, trust_remote_code=True)
print("[reddit] Reward model loaded successfully")
except Exception as e:
print(f"[warn] Failed to load reward model: {e}")
return {"n": 0, "avg_reward": 0.0, "examples_evaluated": 0}
# Load Reddit Finance test data
try:
from datasets import load_dataset
dataset = load_dataset("winddude/reddit_finance_43_250k", split="train")
print(f"[reddit] Loaded {len(dataset)} Reddit Finance examples")
except Exception as e:
print(f"[warn] Failed to load Reddit dataset: {e}")
return {"n": 0, "avg_reward": 0.0, "examples_evaluated": 0}
# Sample test examples (different from training data)
import random
random.seed(12345) # Different seed from training
test_indices = random.sample(range(len(dataset)), min(limit, len(dataset)))
results = []
total_reward = 0.0
successful_evals = 0
eval_model.eval()
# Suppress generation warnings
try:
from transformers.utils import logging as hf_logging
_prev_level = hf_logging.get_verbosity()
hf_logging.set_verbosity_error()
except Exception:
_prev_level = None
for i, idx in enumerate(test_indices):
try:
example = dataset[idx]
# Build prompt in same format as training
subreddit = example.get("subreddit", "")
title = example.get("title", "")
selftext = example.get("selftext", "")
prompt = build_reddit_prompt(subreddit, title, selftext, max_chars=3000)
# Generate response
messages = [{"role": "user", "content": prompt}]
formatted_prompt = eval_tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = eval_tok(formatted_prompt, return_tensors="pt", truncation=True, max_length=2048).to(eval_model.device)
with torch.no_grad():
gen_kwargs = {
"max_new_tokens": max_tokens,
"do_sample": True,
"temperature": 0.7,
"top_p": 0.9,
"pad_token_id": eval_tok.eos_token_id
}
out_ids = eval_model.generate(**inputs, **gen_kwargs)
# Decode response
generated_text = eval_tok.decode(
out_ids[0][inputs["input_ids"].shape[1]:],
skip_special_tokens=True
).strip()
# Score with reward model
reward_score = score_with_reward_model(prompt, generated_text, reward_model, reward_tokenizer)
results.append({
"idx": idx,
"subreddit": subreddit,
"title": title[:100] + "..." if len(title) > 100 else title,
"prompt": prompt[:200] + "..." if len(prompt) > 200 else prompt,
"response": generated_text,
"reward_score": reward_score
})
total_reward += reward_score
successful_evals += 1
if (i + 1) % 25 == 0:
print(f"[reddit] Evaluated {i+1}/{len(test_indices)} examples")
except Exception as e:
print(f"[warn] Reddit evaluation failed for example {i+1}: {e}")
continue
# Restore logging level
try:
if _prev_level is not None:
from transformers.utils import logging as hf_logging
hf_logging.set_verbosity(_prev_level)
except Exception:
pass
avg_reward = total_reward / successful_evals if successful_evals > 0 else 0.0
print(f"Reddit Finance reward eval completed — N={successful_evals} examples, avg reward: {avg_reward:.2f}/10")
if save_path:
with open(save_path, "w", encoding="utf-8") as f:
for r in results:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
print(f"Saved Reddit Finance results to {save_path}")
return {"n": successful_evals, "avg_reward": avg_reward, "examples_evaluated": successful_evals}
def score_instruction_response(response: str, criteria: list) -> float:
"""Score an instruction following response based on criteria compliance."""
response_lower = response.lower()
score = 0.0
max_score = len(criteria)
for criterion in criteria:
criterion_score = 0.0
# Formatting criteria
if "numbered_list" in criterion:
if any(f"{i}." in response for i in range(1, 11)) or any(f"{i})" in response for i in range(1, 11)):
criterion_score = 1.0
elif "exactly_3_items" in criterion:
item_count = sum(1 for i in range(1, 11) if f"{i}." in response or f"{i})" in response)
if item_count == 3:
criterion_score = 1.0
elif abs(item_count - 3) <= 1:
criterion_score = 0.5
elif "exactly_2_sentences" in criterion:
sentence_count = response.count('.') + response.count('!') + response.count('?')
if sentence_count == 2:
criterion_score = 1.0
elif sentence_count == 1 or sentence_count == 3:
criterion_score = 0.5
elif "has_advantages_section" in criterion:
if "advantage" in response_lower or "benefit" in response_lower or "pro" in response_lower:
criterion_score = 1.0
elif "has_disadvantages_section" in criterion:
if "disadvantage" in response_lower or "drawback" in response_lower or "con" in response_lower:
criterion_score = 1.0
elif "table_format" in criterion:
if "|" in response or ("cat" in response_lower and "dog" in response_lower and ("size" in response_lower or "care" in response_lower)):
criterion_score = 1.0
elif "proper_quotation_marks" in criterion:
if '"' in response or "'" in response:
criterion_score = 1.0
# Content criteria
elif "contains_canvas" in criterion:
if "canvas" in response_lower:
criterion_score = 1.0
elif "contains_dream" in criterion:
if "dream" in response_lower:
criterion_score = 1.0
elif "python_function" in criterion:
if "def " in response:
criterion_score = 1.0
elif "named_add_numbers" in criterion:
if "add_numbers" in response:
criterion_score = 1.0
elif "has_docstring" in criterion:
if '"""' in response or "'''" in response:
criterion_score = 1.0
elif "shows_calculation_steps" in criterion:
if any(word in response_lower for word in ["step", "first", "then", "calculate", "multiply"]):
criterion_score = 1.0
elif "word_count_mentioned" in criterion:
if "word" in response_lower and any(str(i) in response for i in range(45, 56)):
criterion_score = 1.0
elif "approximately_50_words" in criterion:
word_count = len(response.split())
if 45 <= word_count <= 55:
criterion_score = 1.0
elif 40 <= word_count <= 60:
criterion_score = 0.5
# Add more criteria scoring logic as needed...
else:
# Default heuristic scoring for unhandled criteria
criterion_words = criterion.replace("_", " ").split()
if any(word in response_lower for word in criterion_words):
criterion_score = 0.5
score += criterion_score
# Convert to 0-10 scale
final_score = (score / max_score) * 10 if max_score > 0 else 0.0
return min(10.0, max(0.0, final_score))
def run_eval(args, eval_model, eval_tok, split: str, limit: int, save_path: str = ""):
eval_model.eval()
results = []
correct = 0
total = 0
by_type: Dict[str, Dict[str, int]] = {}
do_sample = (args.eval_temperature and args.eval_temperature > 0.0) or (args.eval_top_p and args.eval_top_p < 1.0)
gen_kwargs = {"max_new_tokens": args.eval_max_new_tokens}