-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathopd_train_utral.py
More file actions
1604 lines (1372 loc) · 77.4 KB
/
opd_train_utral.py
File metadata and controls
1604 lines (1372 loc) · 77.4 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 python3
"""
Tiny-R2 OPD 训练 v5 - 优势加权表征在策蒸馏 (Teacher=9B+RAG, Student=0.8B)
合并重构版:将 GRP-Advantage 组内优势、神经验证器与多维表征对齐统一收束于多任务/多选题自适应 RAG 在策蒸馏框架下。
"""
import os
import sys
import random
import argparse
import glob
import re
import json
import time
from typing import Optional, List, Dict, Any, Tuple
from contextlib import nullcontext
import numpy as np
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.amp as amp
import torch.distributed as dist
from torch.utils.data import Dataset, DataLoader
from torch.optim.lr_scheduler import CosineAnnealingLR
from datasets import load_dataset, DatasetDict
from transformers import (
AutoTokenizer,
AutoModelForCausalLM,
AutoModelForSequenceClassification
)
# Tiny-R2 核心配置支持
try:
import config
except ImportError:
class MockConfig:
vocab_size = 151936
config = MockConfig()
# WandB 支持
try:
import wandb
WANDB_AVAILABLE = True
except ImportError:
WANDB_AVAILABLE = False
# RAG 混合检索支持
try:
from sentence_transformers import SentenceTransformer, util
from rank_bm25 import BM25Okapi
RAG_AVAILABLE = True
print("✅ 成功导入 rank_bm25 与 sentence_transformers,混合 RAG 模块已启用。")
except ImportError:
print("⚠️ 提示: 未安装 rank_bm25 或 sentence_transformers,将使用 Mock RAG 流程。")
RAG_AVAILABLE = False
try:
import model
from model import Transformer
print("✅ 成功导入 Tiny-R2 核心模块")
TINY_R2_AVAILABLE = True
except ImportError as e:
print(f"ℹ️ 未检测到 Tiny-R2 模块,将强制使用 HuggingFace 模型。")
TINY_R2_AVAILABLE = False
# ====================== 1. 数据集配置注册表 ======================
DATASET_CONFIGS = {
"pubmed_qa": {
"hf_path": "qiaojin/PubMedQA",
"hf_subset": "pqa_labeled",
"split": "train",
"language": "en",
"instruction_key": "question",
"response_key": "final_decision",
"is_mcq": False,
"student_system_prompt": (
"You are an expert clinical assistant. For the given question, "
"first analyze and reason step-by-step in plain text (keep it concise, under 3 sentences). "
"Then, provide your final conclusion at the very end using the exact format: '[Final Decision]: yes', '[Final Decision]: no', or '[Final Decision]: maybe'.\n\n"
"Now answer the user's question following the same format."
),
"student_rag_system_prompt": (
"You are an expert clinical assistant. You will be provided with a 'Retrieved Context' and a 'Question'. "
"Your task is to answer the question based on the provided Retrieved Context.\n\n"
"[Retrieved Context]\n{rag_context}\n\n"
"First, analyze and reason step-by-step in plain text (keep it concise, under 3 sentences). "
"Then, provide your final conclusion at the very end using the exact format: '[Final Decision]: yes', '[Final Decision]: no', or '[Final Decision]: maybe'.\n\n"
"Now answer the user's question using the provided context."
),
"teacher_system_prompt": (
"You are an expert clinical assistant. You will be provided with a 'Retrieved Context' and a 'Question'. "
"Your task is to answer the question based on the provided Retrieved Context.\n\n"
"[Retrieved Context]\n{rag_context}\n\n"
"First, analyze and reason step-by-step in plain text (keep it concise, under 3 sentences). "
"Then, provide your final conclusion at the very end using the exact format: '[Final Decision]: yes', '[Final Decision]: no', or '[Final Decision]: maybe'.\n\n"
"Now answer the user's question using the provided context."
)
},
"medqa": {
"hf_path": "GBaker/MedQA-USMLE-4-options",
"hf_subset": None,
"split": "train",
"language": "en",
"instruction_key": "question",
"response_key": "answer_idx",
"is_mcq": True,
"option_keys": ["A", "B", "C", "D"],
"student_system_prompt": (
"You are an expert clinical assistant. For the given question, "
"first analyze and reason step-by-step in plain text. "
"Then, provide your final conclusion at the very end using the exact format: "
"'[Final Decision]: A', '[Final Decision]: B', '[Final Decision]: C', or '[Final Decision]: D'.\n\n"
"Now answer the user's question following the same format."
),
"student_rag_system_prompt": (
"You are an expert clinical assistant. You will be provided with a 'Retrieved Context' and a 'Question'. "
"Your task is to select the correct option based on the provided Retrieved Context.\n\n"
"[Retrieved Context]\n{rag_context}\n\n"
"First, analyze and reason step-by-step in plain text. "
"Then, provide your final conclusion at the very end using the exact format: "
"'[Final Decision]: A', '[Final Decision]: B', '[Final Decision]: C', or '[Final Decision]: D'.\n\n"
"Now answer the user's question using the provided context."
),
"teacher_system_prompt": (
"You are an expert clinical assistant. You will be provided with a 'Retrieved Context' and a 'Question'. "
"Your task is to select the correct option based on the provided Retrieved Context.\n\n"
"[Retrieved Context]\n{rag_context}\n\n"
"First, analyze and reason step-by-step in plain text. "
"Then, provide your final conclusion at the very end using the exact format: "
"'[Final Decision]: A', '[Final Decision]: B', '[Final Decision]: C', or '[Final Decision]: D'.\n\n"
"Now answer the user's question using the provided context."
)
},
"medmcqa": {
"hf_path": "openlifescienceai/medmcqa",
"hf_subset": None,
"split": "train",
"language": "en",
"instruction_key": "question",
"response_key": "cop",
"is_mcq": True,
"option_keys": ["opa", "opb", "opc", "opd"],
"student_system_prompt": (
"You are an expert medical assistant. "
"Analyze the medical question carefully. "
"First provide concise reasoning in less than 3 sentences. "
"Then output the final answer strictly using the format: "
"'[Final Decision]: A', '[Final Decision]: B', "
"'[Final Decision]: C', or '[Final Decision]: D'."
),
"student_rag_system_prompt": (
"You are an expert medical assistant. "
"You are given retrieved medical references.\n\n"
"[Retrieved Context]\n{rag_context}\n\n"
"Answer the medical question using the retrieved evidence. "
"First provide concise reasoning in less than 3 sentences. "
"Then output the final answer strictly using the format: "
"'[Final Decision]: A', '[Final Decision]: B', "
"'[Final Decision]: C', or '[Final Decision]: D'."
),
"teacher_system_prompt": (
"You are an expert medical assistant. "
"You are given retrieved medical references.\n\n"
"[Retrieved Context]\n{rag_context}\n\n"
"Answer the medical question using the retrieved evidence. "
"First provide concise reasoning in less than 3 sentences. "
"Then output the final answer strictly using the format: "
"'[Final Decision]: A', '[Final Decision]: B', "
"'[Final Decision]: C', or '[Final Decision]: D'."
)
},
"custom": {
"hf_path": "custom",
"hf_subset": None,
"split": "train",
"language": "en",
"instruction_key": "question",
"response_key": "answer",
"is_mcq": False,
"student_system_prompt": (
"You are an expert assistant. For the given question, "
"first analyze and reason step-by-step in plain text (keep it concise, under 3 sentences). "
"Then, provide your final conclusion at the very end using the exact format: '[Final Decision]: yes', '[Final Decision]: no', or '[Final Decision]: maybe'.\n\n"
"Now answer the user's question following the same format."
),
"student_rag_system_prompt": (
"You are an expert assistant. You will be provided with a 'Retrieved Context' and a 'Question'. "
"Your task is to answer the question based on the provided Retrieved Context.\n\n"
"[Retrieved Context]\n{rag_context}\n\n"
"First, analyze and reason step-by-step in plain text (keep it concise, under 3 sentences). "
"Then, provide your final conclusion at the very end using the exact format: '[Final Decision]: yes', '[Final Decision]: no', or '[Final Decision]: maybe'.\n\n"
"Now answer the user's question using the provided context."
),
"teacher_system_prompt": (
"You are an expert assistant. You will be provided with a 'Retrieved Context' and a 'Question'. "
"Your task is to answer the question based on the provided Retrieved Context.\n\n"
"[Retrieved Context]\n{rag_context}\n\n"
"First, analyze and reason step-by-step in plain text (keep it concise, under 3 sentences). "
"Then, provide your final conclusion at the very end using the exact format: '[Final Decision]: yes', '[Final Decision]: no', or '[Final Decision]: maybe'.\n\n"
"Now answer the user's question using the provided context."
)
}
}
BAD_PATTERNS = [
"the user is asking", "i need to explain", "let me explain",
"the question asks", "i will answer", "as an ai",
"用户问", "我需要解释", "让我解释", "这个问题要求", "我会回答", "作为一个人工智能"
]
def get_narration_penalty(text: str) -> float:
lower = text.lower()
return sum(1.0 for p in BAD_PATTERNS if p in lower)
# ====================== MCQ 统一工具函数 ======================
def build_mcq_instruction(item: Dict[str, Any], instruction: str, config: Dict[str, Any]) -> str:
option_keys = config.get("option_keys", [])
options = []
for idx_opt, key in enumerate(option_keys):
label = chr(ord('A') + idx_opt)
if key in item:
opt_text = item[key]
else:
opt_text = item.get("options", {}).get(label, "")
options.append(f"{label}: {opt_text}")
opt_str = "\n".join(options)
return f"Question: {instruction}\nOptions:\n{opt_str}"
def convert_mcq_answer(raw_answer: Any) -> str:
if isinstance(raw_answer, int):
return chr(ord('A') + raw_answer - 1)
return str(raw_answer).strip().upper()
def normalize_answer(raw_output: str, is_mcq: bool = False) -> str:
cleaned_output = re.sub(r'<think>.*?</think>', '', raw_output, flags=re.DOTALL).strip()
if '</think>' in raw_output:
cleaned_output = raw_output.split('</think>')[-1].strip()
elif '<think>' in raw_output:
cleaned_output = raw_output.split('<think>')[-1].strip()
cleaned_output_lower = cleaned_output.lower().strip()
if is_mcq:
match_tag = re.search(
r'(?:final decision|final answer|decision|answer)\]?\s*:\s*\*?\(?\b([a-d])\b\)?\*?',
cleaned_output_lower
)
if match_tag:
return match_tag.group(1).upper()
match_alt = re.search(
r'(?:correct choice|correct option|answer is|choice is)\s*\*?\(?\b([a-d])\b\)?\*?',
cleaned_output_lower
)
if match_alt:
return match_alt.group(1).upper()
all_matches = list(re.finditer(r'\b([a-d])\b', cleaned_output_lower))
if all_matches:
return all_matches[-1].group(1).upper()
return "A"
match_tag = re.search(
r'(?:final decision|final answer|decision|answer)\]?\s*:\s*\*?\b(yes|no|maybe)\b\*?',
cleaned_output_lower
)
if match_tag:
return match_tag.group(1)
match_alt = re.search(
r'(?:correct answer is|answer is)\s*\*?\b(yes|no|maybe)\b\*?',
cleaned_output_lower
)
if match_alt:
return match_alt.group(1)
has_yes = bool(re.search(r'\byes\b', cleaned_output_lower))
has_no = bool(re.search(r'\bno\b', cleaned_output_lower))
has_maybe = bool(re.search(r'\bmaybe\b', cleaned_output_lower))
if has_yes and not has_no and not has_maybe:
return "yes"
elif has_no and not has_yes and not has_maybe:
return "no"
elif has_maybe and not has_yes and not has_no:
return "maybe"
all_matches = list(re.finditer(r'\b(yes|no|maybe)\b', cleaned_output_lower))
if all_matches:
return all_matches[-1].group(1)
return "maybe"
# ====================== 2. 深度 RAG 检索器模块 ======================
class CleanMedicalRAGManager:
def __init__(self, corpus: List[Dict[str, str]], dense_model_name="BAAI/bge-small-en-v1.5", cache_dir: Optional[str] = None, device="cuda"):
self.corpus = corpus
self.texts = [doc["text"] for doc in corpus]
self.doc_ids = [doc.get("pubid", str(i)) for i, doc in enumerate(corpus)]
self.device = device
self.cache_dir = cache_dir
if len(self.texts) > 0:
print("[-] 正在初始化过滤后的 BM25 词法索引...")
tokenized_corpus = [text.lower().split() for text in self.texts]
self.bm25 = BM25Okapi(tokenized_corpus)
print(f"[-] 正在初始化密向量检索模型 ({dense_model_name})...")
try:
self.dense_model = SentenceTransformer(dense_model_name, device=device, cache_folder=cache_dir)
self.corpus_embeddings = self.dense_model.encode(
self.texts, show_progress_bar=False, convert_to_tensor=True
)
except Exception as e:
print(f"⚠️ 向量模型加载失败 ({e}),降级为纯词法检索。")
self.dense_model = None
else:
print("⚠️ 警告: RAG 依赖未完备或检索语料库为空,将切换至 Mock 逻辑运行。")
def retrieve(self, query: str, top_k: int = 3, alpha: float = 0.4, retrieval_mode: str = "hybrid") -> Tuple[str, List[str]]:
if not RAG_AVAILABLE or len(self.texts) == 0:
retrieved_contexts = []
retrieved_ids = []
for i in range(min(top_k, len(self.texts))):
retrieved_contexts.append(f"[Document {i+1}]\n{self.texts[i]}")
retrieved_ids.append(self.doc_ids[i])
return "\n\n".join(retrieved_contexts), retrieved_ids
tokenized_query = query.lower().split()
bm25_scores = np.array(self.bm25.get_scores(tokenized_query))
if bm25_scores.max() > bm25_scores.min():
bm25_scores = (bm25_scores - bm25_scores.min()) / (bm25_scores.max() - bm25_scores.min())
else:
bm25_scores = np.zeros_like(bm25_scores)
if self.dense_model is not None:
query_embedding = self.dense_model.encode(query, convert_to_tensor=True)
dense_scores = util.cos_sim(query_embedding, self.corpus_embeddings)[0].cpu().numpy()
if dense_scores.max() > dense_scores.min():
dense_scores = (dense_scores - dense_scores.min()) / (dense_scores.max() - dense_scores.min())
else:
dense_scores = np.zeros_like(dense_scores)
else:
dense_scores = np.zeros_like(bm25_scores)
if retrieval_mode == "bm25":
hybrid_scores = bm25_scores
elif retrieval_mode == "dense":
hybrid_scores = dense_scores
else:
hybrid_scores = alpha * bm25_scores + (1 - alpha) * dense_scores
top_indices = np.argsort(hybrid_scores)[::-1][:top_k]
retrieved_contexts = []
retrieved_ids = []
for i, idx in enumerate(top_indices):
retrieved_contexts.append(f"[Document {i+1}]\n{self.texts[idx]}")
retrieved_ids.append(self.doc_ids[idx])
return "\n\n".join(retrieved_contexts), retrieved_ids
def evaluate_retrieval(self, query: str, gold_doc_id: str, top_k: int = 3, alpha: float = 0.4, retrieval_mode: str = "hybrid") -> Tuple[float, float]:
_, retrieved_ids = self.retrieve(query, top_k=top_k, alpha=alpha, retrieval_mode=retrieval_mode)
hit = 0.0
mrr = 0.0
if gold_doc_id in retrieved_ids:
hit = 1.0
rank = retrieved_ids.index(gold_doc_id) + 1
mrr = 1.0 / rank
return hit, mrr
# ====================== 3. NLI 神经验证器与奖励模型 ======================
class NeuralVerifierRewardModel:
"""
语义蕴含验证器 (Neural Entailment Verifier Model)
计算公式: Reward = P(Entailment) - P(Contradiction)
"""
def __init__(self, model_name: str = "cross-encoder/nli-deberta-v3-small", device: str = "cuda", cache_dir: Optional[str] = None):
self.device = device
try:
print(f"[-] 正在加载 NLI 神经验证器 ({model_name})...")
self.tokenizer = AutoTokenizer.from_pretrained(model_name, cache_dir=cache_dir)
self.model = AutoModelForSequenceClassification.from_pretrained(model_name, cache_dir=cache_dir).to(device).eval()
self.has_model = True
except Exception as e:
print(f"⚠️ 神经验证器加载失败 ({e}),降级为 Token 词汇重叠度计算指标。")
self.has_model = False
def compute_reward(self, context: str, response: str) -> float:
if not self.has_model or not context or not response:
ctx_words = set(re.findall(r'\b\w{3,}\b', context.lower()))
resp_words = set(re.findall(r'\b\w{3,}\b', response.lower()))
if not resp_words:
return 0.0
overlap = len(ctx_words.intersection(resp_words)) / len(resp_words)
return float(overlap)
inputs = self.tokenizer(
context,
response,
padding=True,
truncation=True,
max_length=512,
return_tensors="pt"
).to(self.device)
with torch.no_grad():
logits = self.model(**inputs).logits
probs = F.softmax(logits, dim=-1) # [0: contradiction, 1: entailment, 2: neutral]
reward = probs[0, 1].item() - probs[0, 0].item() # Entailment - Contradiction
return reward
# ====================== 4. 表征与流形对齐引擎 ======================
class RepresentationAlignmentEngine(nn.Module):
"""
表征层对齐模块 (Hidden State Projection & Attention Alignment)
支持将学生维度映射到教师维度,并计算检索条件对比损失 (Retrieval-Conditioned Contrastive Loss)
"""
def __init__(self, student_dim: int, teacher_dim: int):
super().__init__()
self.proj_hidden = nn.Linear(student_dim, teacher_dim) if student_dim != teacher_dim else nn.Identity()
def forward(self, s_hidden: torch.Tensor, t_hidden: torch.Tensor) -> torch.Tensor:
proj_s_hidden = self.proj_hidden(s_hidden.float())
loss_hidden = F.mse_loss(proj_s_hidden, t_hidden.float(), reduction="mean")
return loss_hidden
def compute_attention_alignment(self, s_attn_weights: Optional[torch.Tensor], t_attn_weights: Optional[torch.Tensor]) -> torch.Tensor:
if s_attn_weights is None or t_attn_weights is None:
return torch.tensor(0.0, device=self.proj_hidden.weight.device)
min_heads = min(s_attn_weights.size(1), t_attn_weights.size(1))
s_attn = s_attn_weights[:, :min_heads, :, :]
t_attn = t_attn_weights[:, :min_heads, :, :]
s_log = F.log_softmax(s_attn.float() + 1e-9, dim=-1)
t_prob = F.softmax(t_attn.float(), dim=-1)
return F.kl_div(s_log, t_prob, reduction="batchmean")
def compute_contrastive_loss(self, pos_hidden: torch.Tensor, neg_hidden: torch.Tensor, target_hidden: torch.Tensor, temp: float = 0.07) -> torch.Tensor:
pos_proj = self.proj_hidden(pos_hidden.float())
neg_proj = self.proj_hidden(neg_hidden.float())
pos_pooled = pos_proj.mean(dim=1)
neg_pooled = neg_proj.mean(dim=1)
target_pooled = target_hidden.mean(dim=1)
# 补齐 batch size 差异
min_b = min(pos_pooled.size(0), target_pooled.size(0), neg_pooled.size(0))
pos_pooled = pos_pooled[:min_b]
neg_pooled = neg_pooled[:min_b]
target_pooled = target_pooled[:min_b]
sim_pos = F.cosine_similarity(pos_pooled, target_pooled, dim=-1) / temp
sim_neg = F.cosine_similarity(neg_pooled, target_pooled, dim=-1) / temp
logits = torch.stack([sim_pos, sim_neg], dim=-1) # [B, 2]
labels = torch.zeros(logits.size(0), dtype=torch.long, device=logits.device)
return F.cross_entropy(logits, labels)
# ====================== 5. 扩展后的双路训练数据集 ======================
class DualPromptDataset(Dataset):
"""
自适应双路数据集。除正向 prompt 外,随机加载负向 Context 数据生成 s_neg_prompt_ids。
用于计算表征层的检索条件对比损失 (Retrieval-Conditioned Contrastive Loss)。
"""
def __init__(self, hf_dataset, tokenizer, ctx_len: int, dataset_config: Dict[str, Any], rag_manager: CleanMedicalRAGManager, args):
self.tokenizer = tokenizer
self.ctx_len = ctx_len
self.dataset = hf_dataset
self.config = dataset_config
self.rag_manager = rag_manager
self.args = args
def __len__(self):
return len(self.dataset)
def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
item = self.dataset[idx]
instruction = item[self.config["instruction_key"]]
# 兼容 PubMedQA 等多数据集提取 Gold 响应
is_pubmed_qa = (self.args.dataset == "pubmed_qa" or "pubmed_qa" in str(self.config.get("hf_path", "")).lower())
if is_pubmed_qa:
long_ans = item.get("long_answer", "")
final_dec = item.get("final_decision", "maybe")
response = f"Analysis: {long_ans}\n\n[Final Decision]: {final_dec}"
elif self.config.get("is_mcq", False):
instruction = build_mcq_instruction(item, instruction, self.config)
gold_raw = item[self.config["response_key"]]
gold_choice = convert_mcq_answer(gold_raw)
response = "Analysis: Guided by biomedical reasoning...\n\n" + f"[Final Decision]: {gold_choice}"
else:
response = item.get(self.config["response_key"], "")
if "[Final Decision]" not in response:
response = f"Analysis: Processed customized input.\n\n[Final Decision]: {response}"
response_text = response + self.tokenizer.eos_token
response_ids = self.tokenizer(response_text, return_tensors="pt")["input_ids"].squeeze(0)
max_response_len = self.ctx_len // 2
if len(response_ids) > max_response_len:
response_ids = response_ids[:max_response_len]
max_prompt_len = self.ctx_len - len(response_ids)
need_rag = (not self.args.disable_rag_teacher) or self.args.student_use_rag
if need_rag and self.args.ablation_mode != "vanilla_sft":
retrieved_context, _ = self.rag_manager.retrieve(
instruction, top_k=self.args.rag_top_k, alpha=self.args.alpha, retrieval_mode=self.args.retrieval_mode
)
else:
retrieved_context = ""
# 构建正向 Prompt (学生端)
if self.args.student_use_rag and retrieved_context:
s_system_template = self.config.get("student_rag_system_prompt", "Please answer based on reference:\n{rag_context}")
s_system = s_system_template.format(rag_context=retrieved_context)
s_prompt_input = f"Retrieved Context:\n{retrieved_context}\n\nQuestion: {instruction}"
else:
s_system = self.config.get("student_system_prompt", "You are a professional assistant.")
s_prompt_input = f"Question: {instruction}"
s_messages = [{"role": "system", "content": s_system}, {"role": "user", "content": s_prompt_input}]
try:
s_prompt_text = self.tokenizer.apply_chat_template(s_messages, tokenize=False, add_generation_prompt=True, enable_thinking=False)
except Exception:
s_prompt_text = self.tokenizer.apply_chat_template(s_messages, tokenize=False, add_generation_prompt=True)
s_prompt_ids = self.tokenizer(s_prompt_text, return_tensors="pt")["input_ids"].squeeze(0)
# 构建负向 Prompt (对比用)
random_idx = (idx + random.randint(1, len(self.dataset) - 1)) % len(self.dataset)
neg_item = self.dataset[random_idx]
neg_instruction = neg_item[self.config["instruction_key"]]
if self.config.get("is_mcq", False):
neg_instruction = build_mcq_instruction(neg_item, neg_instruction, self.config)
if need_rag and self.args.ablation_mode != "vanilla_sft":
neg_context, _ = self.rag_manager.retrieve(
neg_instruction, top_k=self.args.rag_top_k, alpha=self.args.alpha, retrieval_mode=self.args.retrieval_mode
)
else:
neg_context = ""
if self.args.student_use_rag and neg_context:
s_neg_system = s_system_template.format(rag_context=neg_context)
s_neg_prompt_input = f"Retrieved Context:\n{neg_context}\n\nQuestion: {instruction}"
else:
s_neg_system = s_system
s_neg_prompt_input = f"Question: {instruction}"
s_neg_messages = [{"role": "system", "content": s_neg_system}, {"role": "user", "content": s_neg_prompt_input}]
try:
s_neg_prompt_text = self.tokenizer.apply_chat_template(s_neg_messages, tokenize=False, add_generation_prompt=True, enable_thinking=False)
except Exception:
s_neg_prompt_text = self.tokenizer.apply_chat_template(s_neg_messages, tokenize=False, add_generation_prompt=True)
s_neg_prompt_ids = self.tokenizer(s_neg_prompt_text, return_tensors="pt")["input_ids"].squeeze(0)
# 构建教师端 Prompt
if not self.args.disable_rag_teacher and self.args.ablation_mode != "vanilla_sft" and retrieved_context:
t_system_template = self.config.get("teacher_system_prompt", "Please answer based on reference:\n{rag_context}")
t_system = t_system_template.format(rag_context=retrieved_context)
t_prompt_input = f"Retrieved Context:\n{retrieved_context}\n\nQuestion: {instruction}"
else:
t_system = self.config.get("student_system_prompt", "You are a professional assistant.")
t_prompt_input = f"Question: {instruction}"
t_messages = [{"role": "system", "content": t_system}, {"role": "user", "content": t_prompt_input}]
try:
t_prompt_text = self.tokenizer.apply_chat_template(t_messages, tokenize=False, add_generation_prompt=True, enable_thinking=False)
except Exception:
t_prompt_text = self.tokenizer.apply_chat_template(t_messages, tokenize=False, add_generation_prompt=True)
t_prompt_ids = self.tokenizer(t_prompt_text, return_tensors="pt")["input_ids"].squeeze(0)
# 截断与边界安全保障
if len(s_prompt_ids) > max_prompt_len:
s_prompt_ids = s_prompt_ids[-max_prompt_len:]
if len(s_neg_prompt_ids) > max_prompt_len:
s_neg_prompt_ids = s_neg_prompt_ids[-max_prompt_len:]
if len(t_prompt_ids) > max_prompt_len:
t_prompt_ids = t_prompt_ids[-max_prompt_len:]
s_input_ids = torch.cat([s_prompt_ids, response_ids])
s_neg_input_ids = torch.cat([s_neg_prompt_ids, response_ids])
t_input_ids = torch.cat([t_prompt_ids, response_ids])
s_labels = torch.full_like(s_input_ids, -100)
s_labels[len(s_prompt_ids):] = response_ids
s_neg_labels = torch.full_like(s_neg_input_ids, -100)
s_neg_labels[len(s_neg_prompt_ids):] = response_ids
t_labels = torch.full_like(t_input_ids, -100)
t_labels[len(t_prompt_ids):] = response_ids
return {
"s_prompt_ids": s_prompt_ids,
"t_prompt_ids": t_prompt_ids,
"s_input_ids": s_input_ids,
"s_labels": s_labels,
"s_neg_input_ids": s_neg_input_ids,
"s_neg_labels": s_neg_labels,
"t_input_ids": t_input_ids,
"t_labels": t_labels,
"context": retrieved_context if retrieved_context else "No retrieved clinical reference context available."
}
def dual_collate_fn(batch: List[Dict[str, torch.Tensor]], tokenizer):
def pad_tensors(key_ids, key_labels):
items_ids = [item[key_ids] for item in batch]
items_labels = [item[key_labels] for item in batch]
max_len = max(len(x) for x in items_ids)
padded_ids = torch.full((len(batch), max_len), tokenizer.pad_token_id, dtype=torch.long)
padded_labels = torch.full((len(batch), max_len), -100, dtype=torch.long)
for i in range(len(batch)):
padded_ids[i, :len(items_ids[i])] = items_ids[i]
padded_labels[i, :len(items_labels[i])] = items_labels[i]
return padded_ids, padded_labels
s_ids, s_labels = pad_tensors("s_input_ids", "s_labels")
s_neg_ids, s_neg_labels = pad_tensors("s_neg_input_ids", "s_neg_labels")
t_ids, t_labels = pad_tensors("t_input_ids", "t_labels")
s_prompt_ids = [item["s_prompt_ids"] for item in batch]
t_prompt_ids = [item["t_prompt_ids"] for item in batch]
contexts = [item["context"] for item in batch]
return {
"s_input_ids": s_ids,
"s_labels": s_labels,
"s_neg_input_ids": s_neg_ids,
"s_neg_labels": s_neg_labels,
"t_input_ids": t_ids,
"t_labels": t_labels,
"s_prompt_ids": s_prompt_ids,
"t_prompt_ids": t_prompt_ids,
"contexts": contexts
}
# ====================== 6. 分布式对齐 JSD 损失算子 ======================
def generalized_jsd_loss_flat(s_valid_logits, t_valid_logits, beta=0.5, temperature=1.0, chunk_size=2048):
N, V_s = s_valid_logits.shape
M, V_t = t_valid_logits.shape
if N != M:
raise RuntimeError(f"教师和学生模型 Valid Tokens 大小未对齐: {N} vs {M}.")
min_vocab = min(V_s, V_t)
if V_s != V_t:
s_valid_logits = s_valid_logits[:, :min_vocab]
t_valid_logits = t_valid_logits[:, :min_vocab]
s_valid_logits = s_valid_logits.float()
t_valid_logits = t_valid_logits.float()
total_loss = torch.tensor(0.0, device=s_valid_logits.device, dtype=torch.float32)
num_chunks = (N + chunk_size - 1) // chunk_size
for i in range(num_chunks):
start = i * chunk_size
end = min(start + chunk_size, N)
s_chunk = s_valid_logits[start:end, :] / temperature
t_chunk = t_valid_logits[start:end, :] / temperature
s_logp = F.log_softmax(s_chunk, dim=-1)
t_logp = F.log_softmax(t_chunk, dim=-1)
if beta == 0:
jsd = F.kl_div(s_logp, t_logp, reduction="none", log_target=True).sum(dim=-1)
elif beta == 1:
jsd = F.kl_div(t_logp, s_logp, reduction="none", log_target=True).sum(dim=-1)
else:
beta_tensor = torch.tensor(beta, dtype=s_logp.dtype, device=s_logp.device)
mixture_logp = torch.logsumexp(
torch.stack([s_logp + torch.log1p(-beta_tensor), t_logp + torch.log(beta_tensor)]),
dim=0
)
kl_teacher = F.kl_div(mixture_logp, t_logp, reduction="none", log_target=True).sum(dim=-1)
kl_student = F.kl_div(mixture_logp, s_logp, reduction="none", log_target=True).sum(dim=-1)
jsd = beta_tensor * kl_teacher + (1 - beta_tensor) * kl_student
total_loss += jsd.sum()
return total_loss / max(N, 1)
def extract_valid_logits(logits, labels):
shift_logits = logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
flat_logits = shift_logits.view(-1, shift_logits.size(-1))
flat_labels = shift_labels.view(-1)
valid_mask = flat_labels != -100
return flat_logits[valid_mask], flat_labels[valid_mask]
# ====================== 7. 严载与评测模块 ======================
@torch.inference_mode()
def validate(student_model, teacher_model, dataloader, args, ctx):
student_model.eval()
total_loss = 0.0
total_batches = 0
is_hf = hasattr(student_model, "config")
for batch in dataloader:
s_input_ids = batch["s_input_ids"].to(args.device)
s_labels = batch["s_labels"].to(args.device)
t_input_ids = batch["t_input_ids"].to(args.device)
t_labels = batch["t_labels"].to(args.device)
s_attn_mask = (s_input_ids != dataloader.dataset.tokenizer.pad_token_id).to(args.device) if is_hf else None
if args.ablation_mode == "vanilla_sft":
with ctx:
outputs = student_model(s_input_ids, attention_mask=s_attn_mask) if is_hf else student_model(s_input_ids)
s_logits = outputs.logits if hasattr(outputs, 'logits') else outputs[0]
loss = F.cross_entropy(s_logits.view(-1, s_logits.size(-1)), s_labels.view(-1), ignore_index=-100)
total_loss += loss.item()
total_batches += 1
else:
t_attn_mask = (t_input_ids != dataloader.dataset.tokenizer.pad_token_id).to(args.device) if is_hf else None
t_logits = teacher_model(t_input_ids, attention_mask=t_attn_mask).logits if is_hf else teacher_model(t_input_ids).logits
with ctx:
outputs = student_model(s_input_ids, attention_mask=s_attn_mask) if is_hf else student_model(s_input_ids)
s_logits = outputs.logits if hasattr(outputs, 'logits') else outputs[0]
s_valid_logits, _ = extract_valid_logits(s_logits, s_labels)
t_valid_logits, _ = extract_valid_logits(t_logits, t_labels)
if s_valid_logits.size(0) > 0:
loss = generalized_jsd_loss_flat(
s_valid_logits,
t_valid_logits,
beta=args.opd_beta,
temperature=args.temperature,
chunk_size=args.opd_chunk_size
)
total_loss += loss.item()
total_batches += 1
# === 添加:验证batch处理完后清理显存 ===
del s_input_ids, s_labels, t_input_ids, t_labels
if 's_logits' in locals(): del s_logits
if 't_logits' in locals(): del t_logits
if 'outputs' in locals(): del outputs
torch.cuda.empty_cache()
student_model.train()
return total_loss / max(total_batches, 1)
@torch.inference_mode()
def validate_comprehensive_accuracy(
student_model,
student_base_model,
teacher_model,
tokenizer,
rag_manager,
dataset_config,
val_dataset_raw,
args,
num_samples=20,
ood_dataset_raw=None
) -> Tuple[float, float, float, float, float, float]:
device = args.device
student_model.eval()
student_base_model.eval()
if teacher_model is not None:
teacher_model.eval()
num_samples = min(num_samples, len(val_dataset_raw))
eval_indices = random.sample(range(len(val_dataset_raw)), num_samples)
eval_samples = [val_dataset_raw[i] for i in eval_indices]
results_base = []
results_student = []
results_rag = []
retrieval_hits = []
retrieval_mrrs = []
print("\n" + "="*40)
print(f" 开始评估: 规模 {num_samples} 个样本 (防泄露保障评估,学生使用 RAG: {'✅' if args.student_use_rag else '❌'})")
print("="*40)
is_custom_transformer = (student_model.__class__.__name__ == "Transformer")
is_pubmed_qa = (args.dataset == "pubmed_qa" or "pubmed_qa" in str(dataset_config.get("hf_path", "")).lower())
is_mcq = dataset_config.get("is_mcq", False)
for idx, sample in enumerate(eval_samples):
question = sample[dataset_config["instruction_key"]]
if is_mcq:
question = build_mcq_instruction(sample, question, dataset_config)
if is_pubmed_qa:
gold_answer = sample.get("final_decision", "maybe")
gold_doc_id = str(sample.get("pubid", ""))
else:
gold_raw = sample.get(dataset_config["response_key"], "")
gold_answer = convert_mcq_answer(gold_raw) if is_mcq else gold_raw
gold_doc_id = str(eval_indices[idx])
# 1. 评估 RAG 指标
if (not args.disable_rag_teacher or args.student_use_rag):
hit, mrr = rag_manager.evaluate_retrieval(question, gold_doc_id, top_k=args.rag_top_k, alpha=args.alpha, retrieval_mode=args.retrieval_mode)
retrieval_hits.append(hit)
retrieval_mrrs.append(mrr)
# 2. 学生端测试
if args.student_use_rag:
retrieved_context, _ = rag_manager.retrieve(query=question, top_k=args.rag_top_k, alpha=args.alpha, retrieval_mode=args.retrieval_mode)
s_system_template = dataset_config.get("student_rag_system_prompt", "Please answer based on reference:\n{rag_context}")
s_system = s_system_template.format(rag_context=retrieved_context)
s_prompt_input = f"Retrieved Context:\n{retrieved_context}\n\nQuestion: {question}"
else:
s_system = dataset_config["student_system_prompt"]
s_prompt_input = f"Question: {question}"
messages_base = [
{"role": "system", "content": s_system},
{"role": "user", "content": s_prompt_input}
]
try:
prompt_student = tokenizer.apply_chat_template(messages_base, tokenize=False, enable_thinking=False, add_generation_prompt=True)
except Exception:
prompt_student = tokenizer.apply_chat_template(messages_base, tokenize=False, add_generation_prompt=True)
inputs_student = tokenizer([prompt_student], return_tensors="pt").to(device)
if is_custom_transformer:
outputs_student = student_model.generate(idx=inputs_student.input_ids, max_new_tokens=128, temperature=args.temperature)
outputs_base = student_base_model.generate(idx=inputs_student.input_ids, max_new_tokens=128, temperature=args.temperature)
generated_student = tokenizer.decode(outputs_student[0][inputs_student.input_ids.shape[1]:], skip_special_tokens=True)
generated_base = tokenizer.decode(outputs_base[0][inputs_student.input_ids.shape[1]:], skip_special_tokens=True)
else:
outputs_student = student_model.generate(**inputs_student, max_new_tokens=128, do_sample=False, pad_token_id=tokenizer.pad_token_id)
outputs_base = student_base_model.generate(**inputs_student, max_new_tokens=128, do_sample=False, pad_token_id=tokenizer.pad_token_id)
generated_student = tokenizer.decode(outputs_student[0][inputs_student.input_ids.shape[1]:], skip_special_tokens=True)
generated_base = tokenizer.decode(outputs_base[0][inputs_student.input_ids.shape[1]:], skip_special_tokens=True)
pred_base = normalize_answer(generated_base, is_mcq=is_mcq)
results_base.append(pred_base == gold_answer)
pred_student = normalize_answer(generated_student, is_mcq=is_mcq)
results_student.append(pred_student == gold_answer)
# 3. 教师端测试
if teacher_model is not None:
retrieved_context_t, _ = rag_manager.retrieve(query=question, top_k=args.rag_top_k, alpha=args.alpha, retrieval_mode=args.retrieval_mode)
t_system = dataset_config["teacher_system_prompt"].format(rag_context=retrieved_context_t)
messages_rag = [
{"role": "system", "content": t_system},
{"role": "user", "content": f"Retrieved Context:\n{retrieved_context_t}\n\nQuestion: {question}"}
]
try:
prompt_teacher = tokenizer.apply_chat_template(messages_rag, tokenize=False, enable_thinking=False, add_generation_prompt=True)
except Exception:
prompt_teacher = tokenizer.apply_chat_template(messages_rag, tokenize=False, add_generation_prompt=True)
inputs_teacher = tokenizer([prompt_teacher], return_tensors="pt").to(device)
outputs_rag = teacher_model.generate(**inputs_teacher, max_new_tokens=128, do_sample=False, pad_token_id=tokenizer.pad_token_id)
generated_rag = tokenizer.decode(outputs_rag[0][inputs_teacher.input_ids.shape[1]:], skip_special_tokens=True)
pred_rag = normalize_answer(generated_rag, is_mcq=is_mcq)
results_rag.append(pred_rag == gold_answer)
else:
results_rag.append(False)
if idx < 3:
print(f"\n[验证调试样例 {idx+1}]")
print(f"👉 Q: {question[:150]}...")
print(f"🎯 真实结果 (Gold): {gold_answer}")
print(f"❌ Base Student : '{pred_base}' | 对比结果: {'✓' if pred_base == gold_answer else '✗'}")
print(f"🚀 OPD Student : '{pred_student}' | 对比结果: {'✓' if pred_student == gold_answer else '✗'}")
if teacher_model is not None:
print(f"👨🏫 Teacher (RAG) : '{pred_rag}' | 对比结果: {'✓' if pred_rag == gold_answer else '✗'}")
# === 添加:评测样本处理完后清理显存 ===
del inputs_student, outputs_student, outputs_base, generated_student, generated_base
if 'inputs_teacher' in locals(): del inputs_teacher
if 'outputs_rag' in locals(): del outputs_rag
if 'generated_rag' in locals(): del generated_rag
torch.cuda.empty_cache()
# 4. Out-of-Distribution (OOD) 泛化测试
ood_acc = 0.0
if ood_dataset_raw is not None and len(ood_dataset_raw) > 0:
print("\n" + "-"*30 + " 执行 OOD (MedQA-USMLE) 泛化评测 " + "-"*30)
ood_samples_num = min(num_samples, len(ood_dataset_raw))
ood_indices = random.sample(range(len(ood_dataset_raw)), ood_samples_num)
ood_results = []
medqa_cfg = DATASET_CONFIGS["medqa"]
for oidx in ood_indices:
sample = ood_dataset_raw[oidx]
q = sample["question"]
option_keys = medqa_cfg.get("option_keys", [])
options = []
for idx_opt, key in enumerate(option_keys):
label = chr(ord('A') + idx_opt)
if key in sample:
opt_text = sample[key]
else:
opt_text = sample.get("options", {}).get(label, "")
options.append(f"{label}: {opt_text}")
opt_str = "\n".join(options)
full_q = f"Question: {q}\nOptions:\n{opt_str}"
gold_ans = sample["answer_idx"]
if args.student_use_rag:
ood_context, _ = rag_manager.retrieve(query=q, top_k=args.rag_top_k, alpha=args.alpha, retrieval_mode=args.retrieval_mode)
s_system_template = medqa_cfg.get("student_rag_system_prompt", "Please answer based on reference:\n{rag_context}")
s_system = s_system_template.format(rag_context=ood_context)
user_content_ood = f"Retrieved Context:\n{ood_context}\n\nQuestion: {full_q}"
else:
s_system = medqa_cfg["student_system_prompt"]
user_content_ood = full_q
messages_ood = [
{"role": "system", "content": s_system},
{"role": "user", "content": user_content_ood}
]
try:
prompt_ood = tokenizer.apply_chat_template(messages_ood, tokenize=False, enable_thinking=False, add_generation_prompt=True)
except Exception:
prompt_ood = tokenizer.apply_chat_template(messages_ood, tokenize=False, add_generation_prompt=True)
inputs_ood = tokenizer([prompt_ood], return_tensors="pt").to(device)
with torch.no_grad():
if is_custom_transformer:
outputs_ood = student_model.generate(idx=inputs_ood.input_ids, max_new_tokens=128, temperature=args.temperature)
else:
outputs_ood = student_model.generate(**inputs_ood, max_new_tokens=128, do_sample=False, pad_token_id=tokenizer.pad_token_id)
gen_ood = tokenizer.decode(outputs_ood[0][inputs_ood.input_ids.shape[1]:], skip_special_tokens=True)
pred_ood = normalize_answer(gen_ood, is_mcq=True)
ood_results.append(pred_ood == gold_ans)
ood_acc = np.mean(ood_results) * 100
print(f"🎯 OOD (MedQA) 学生泛化准确率: {ood_acc:.2f}%")
opd_student_acc = np.mean(results_student) * 100
base_student_acc = np.mean(results_base) * 100
teacher_acc = np.mean(results_rag) * 100 if teacher_model is not None else 0.0
m_hit = np.mean(retrieval_hits) * 100 if retrieval_hits else 0.0
m_mrr = np.mean(retrieval_mrrs) * 100 if retrieval_mrrs else 0.0
print("\n" + "="*40)
print(" 评测指标汇总统计 ")
print("="*40)
print(f"评估样本总数 (Eval Count): {num_samples}")
print(f"Base Student 准确率 : {base_student_acc:.2f}%")
print(f"OPD Student 准确率 : {opd_student_acc:.2f}%")
if teacher_model is not None:
print(f"Teacher (RAG) 准确率 : {teacher_acc:.2f}%")
print(f"RAG Hit Rate @ {args.rag_top_k} : {m_hit:.2f}%")
print(f"RAG MRR : {m_mrr:.2f}%")
print(f"OOD MedQA 泛化准确率 : {ood_acc:.2f}%")
print("="*40)
student_model.train()
return opd_student_acc, base_student_acc, teacher_acc, m_hit, m_mrr, ood_acc
# ====================== 8. 命令行参数解析 ======================
def parse_args():
parser = argparse.ArgumentParser(description="Academic Representation-enhanced Advantage-weighted OPD")
parser.add_argument('--batch_size', type=int, default=2)
parser.add_argument('--val_batch_size', type=int, default=4)
parser.add_argument('--ctx_len', type=int, default=2048)
parser.add_argument('--lr', type=float, default=2e-5)
parser.add_argument('--max_iters', type=int, default=1000)
parser.add_argument('--warmup_iters', type=int, default=100)
parser.add_argument('--grad_accum_steps', type=int, default=4)
parser.add_argument('--weight_decay', type=float, default=0.01)
parser.add_argument('--max_grad_norm', type=float, default=1.0)
parser.add_argument('--min_lr', type=float, default=1e-6)
parser.add_argument(
"--dataset",
type=str,
default="pubmed_qa",
choices=["pubmed_qa", "medqa", "medmcqa", "custom"]
)
parser.add_argument("--hf_teacher_model", type=str, default="Qwen/Qwen3.5-9B")