当然,以下是基于 Qwen 模型完整且可运行的训练和评估代码。此代码包括以下主要更改和增强:
- 使用 Qwen 模型:将
model_name 更新为 Qwen 模型,例如 "Qwen/Qwen-7B"。请根据实际需求选择合适的 Qwen 模型。
- 定义
apply_chat_template 函数:该函数将对话列表格式化为模型可接受的输入字符串。
- 添加评估功能:在训练完成后,添加了一个评估函数,用于生成模型的回答并与正确答案进行比较,计算准确率等指标。
- 优化数据处理:虽然原始代码按单个样本进行训练,但为了提高效率,建议使用
DataLoader。不过为了保持与原始代码结构的一致性,此处仍保持单样本训练。
- 其他改进:包括设备管理、日志记录增强等。
请确保安装了必要的库,例如 transformers, torch, 和 pandas。你可以使用 pip install transformers torch pandas 进行安装。
以下是修改后的完整代码:
import torch
import torch.nn as nn
import torch.optim as optim
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch.nn.functional as F
import pandas as pd
import argparse
import yaml
import os
from tqdm import tqdm
from sklearn.metrics import accuracy_score
# Ensure reproducibility
torch.manual_seed(42)
# Load configuration from a YAML file
def load_config(config_file=None):
if config_file and os.path.exists(config_file):
with open(config_file, 'r') as f:
config = yaml.safe_load(f)
else:
# Default configuration
config = {
"model_name": "Qwen/Qwen-7B", # Updated to Qwen model
"learning_rate": 1e-5,
"epochs_stage_1": 2,
"epochs_stage_2": 3,
"beta_kl": 0.1,
"alpha": 1.0,
"data_file": "SCoRe_dataset.csv",
"max_length": 512, # Maximum token length
"batch_size": 1 # For simplicity, keep it 1. Adjust as needed
}
return config
# Reward function for self-correction
def reward_function(original_answer, corrected_answer, correct_answer):
if corrected_answer.strip() == correct_answer.strip(): # Fully correct answer
return 1.0
elif corrected_answer.strip() == original_answer.strip(): # No improvement from original answer
return -1.0
else:
return 0.5 # Partial improvement, better than original but still incorrect
# Apply chat template to format the conversation
def apply_chat_template(conversation):
prompt = ""
for turn in conversation:
role = turn['role']
content = turn['content']
if role == 'user':
prompt += f"User: {content}\n"
elif role == 'assistant':
prompt += f"Assistant: {content}\n"
return prompt
# Stage I: Train initial model to generate first attempt (y1) and prevent mode collapse
def stage_one_initialization(model, tokenizer, data, config):
optimizer = optim.AdamW(model.parameters(), lr=config["learning_rate"])
model.train()
for epoch in range(config["epochs_stage_1"]):
total_loss = 0.0
for example in tqdm(data, desc=f"Stage I - Epoch {epoch+1}/{config['epochs_stage_1']}"):
# Format input using stage1_chat_format
conversation = stage1_chat_format(example)
# Apply chat template to get the prompt
conversation_text = apply_chat_template(conversation)
# Tokenize inputs
inputs = tokenizer(conversation_text, return_tensors="pt",
padding=True, truncation=True, max_length=config["max_length"])
inputs = {k: v.to(model.device) for k, v in inputs.items()}
# Forward pass
outputs = model(**inputs, labels=inputs['input_ids'])
# Cross-entropy loss (first attempt)
cross_entropy_loss = outputs.loss
# Log probabilities and apply KL divergence loss
logits = outputs.logits
log_probs = F.log_softmax(logits, dim=-1)
with torch.no_grad():
target_probs = F.softmax(logits, dim=-1)
kl_loss = F.kl_div(log_probs, target_probs, reduction='batchmean')
# Total loss combines cross-entropy and scaled KL divergence
total_loss_value = cross_entropy_loss + config["beta_kl"] * kl_loss
# Backward pass and optimization
optimizer.zero_grad()
total_loss_value.backward()
optimizer.step()
total_loss += total_loss_value.item()
avg_loss = total_loss / len(data)
print(f"Stage I - Epoch {epoch+1}/{config['epochs_stage_1']}, Avg Loss: {avg_loss:.4f}")
# Stage II: Training with Reward Shaping for Self-correction
def stage_two_training_with_reward_shaping(model, tokenizer, data, config):
optimizer = optim.AdamW(model.parameters(), lr=config["learning_rate"])
model.train()
for epoch in range(config["epochs_stage_2"]):
total_loss = 0.0
for example in tqdm(data, desc=f"Stage II - Epoch {epoch+1}/{config['epochs_stage_2']}"):
# First attempt (y1): Generate the initial answer using stage2_chat_format
conversation1 = stage2_chat_format(example)
conversation_text1 = apply_chat_template(conversation1)
inputs1 = tokenizer(conversation_text1, return_tensors="pt",
padding=True, truncation=True, max_length=config["max_length"])
inputs1 = {k: v.to(model.device) for k, v in inputs1.items()}
# Generate output for the first attempt
with torch.no_grad():
outputs1 = model(**inputs1)
# Get the token IDs of the generated assistant response
generated_ids1 = outputs1.logits.argmax(dim=-1)
generated_text1 = tokenizer.decode(generated_ids1[0], skip_special_tokens=True).split("Assistant:")[-1].strip()
# Second attempt (y2): Corrected answer
conversation2 = chat_format(example)
conversation_text2 = apply_chat_template(conversation2)
inputs2 = tokenizer(conversation_text2, return_tensors="pt",
padding=True, truncation=True, max_length=config["max_length"])
inputs2 = {k: v.to(model.device) for k, v in inputs2.items()}
# Forward pass with labels for loss calculation
outputs2 = model(**inputs2, labels=inputs2['input_ids'])
# Ensure we have a loss
if outputs2.loss is None:
print("Warning: Model output does not include loss. Using cross-entropy loss.")
logits = outputs2.logits
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), inputs2['input_ids'].view(-1))
else:
loss = outputs2.loss
# Compute reward based on self-correction
generated_ids2 = outputs2.logits.argmax(dim=-1)
generated_text2 = tokenizer.decode(generated_ids2[0], skip_special_tokens=True).split("Assistant:")[-1].strip()
reward = reward_function(generated_text1, generated_text2, example.get('correct_answer', ''))
# Apply reward shaping
shaped_loss = loss * reward
# Backward pass and optimization
optimizer.zero_grad()
shaped_loss.backward()
optimizer.step()
total_loss += shaped_loss.item()
avg_loss = total_loss / len(data)
print(f"Stage II - Epoch {epoch+1}/{config['epochs_stage_2']}, Avg Shaped Loss: {avg_loss:.4f}")
# Format for Stage I
def stage1_chat_format(example):
return [
{"role": "user", "content": example['question']},
{"role": "assistant", "content": f"{example.get('original_answer', '')}"}
]
# Format for Stage II (includes a request for review)
def stage2_chat_format(example):
return [
{"role": "user", "content": example['question']},
{"role": "assistant", "content": f"첫 번째 답변: {example.get('original_answer', '')}"},
{"role": "user", "content": "이 답변을 다시 한 번 검토해주세요."},
{"role": "assistant", "content": "검토 후 답변: "}
]
# Final chat format using correct_answer
def chat_format(example):
return [
{"role": "user", "content": example['question']},
{"role": "assistant", "content": f"최종 답변: {example.get('correct_answer', '')}"}
]
# Evaluation function
def evaluate_model(model, tokenizer, data, config):
model.eval()
correct = 0
total = 0
generated_answers = []
reference_answers = []
with torch.no_grad():
for example in tqdm(data, desc="Evaluating"):
conversation = [
{"role": "user", "content": example['question']}
]
conversation_text = apply_chat_template(conversation)
inputs = tokenizer(conversation_text, return_tensors="pt",
padding=True, truncation=True, max_length=config["max_length"])
inputs = {k: v.to(model.device) for k, v in inputs.items()}
outputs = model.generate(**inputs, max_new_tokens=150, do_sample=True, top_p=0.95, temperature=0.7)
# Decode the generated response
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
# Extract the assistant's reply
if "Assistant:" in generated_text:
generated_answer = generated_text.split("Assistant:")[-1].strip()
else:
generated_answer = generated_text.strip()
generated_answers.append(generated_answer)
reference = example.get('correct_answer', '').strip()
reference_answers.append(reference)
if generated_answer == reference:
correct += 1
total += 1
accuracy = correct / total if total > 0 else 0
print(f"Evaluation Accuracy: {accuracy*100:.2f}%")
return generated_answers, reference_answers, accuracy
# Main function to run the training and evaluation process
def main(config_file=None):
config = load_config(config_file)
# Check for CUDA
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# Load model and tokenizer
model_name = config["model_name"]
print(f"Loading tokenizer for {model_name}...")
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
print(f"Loading model {model_name}...")
model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True)
model.to(device)
# Load the dataset
data_file_path = config["data_file"]
if not os.path.exists(data_file_path):
raise FileNotFoundError(f"Data file {data_file_path} not found.")
df = pd.read_csv(data_file_path)
# Prepare the data for Stage I and Stage II
data_stage_one = df[["question", "original_answer"]].dropna().to_dict(orient="records")
data_stage_two = df[["question", "original_answer", "correct_answer"]].dropna().to_dict(orient="records")
# Stage I training (Initialization)
print("Starting Stage I training (Initialization)...")
stage_one_initialization(
model, tokenizer, data_stage_one, config
)
# Stage II training (Self-correction)
print("Starting Stage II training (Self-correction)...")
stage_two_training_with_reward_shaping(
model, tokenizer, data_stage_two, config
)
# Save the trained model
save_path = "./trained_self_correcting_model"
os.makedirs(save_path, exist_ok=True)
print(f"Saving the trained model to {save_path}...")
model.save_pretrained(save_path)
tokenizer.save_pretrained(save_path)
# Evaluation
print("Starting evaluation...")
# For evaluation, we can use the same data or separate validation data
# Here, we'll use the same Stage Two data for simplicity
generated_answers, reference_answers, accuracy = evaluate_model(model, tokenizer, data_stage_two, config)
# Optionally, save evaluation results
eval_results = pd.DataFrame({
"question": [ex['question'] for ex in data_stage_two],
"generated_answer": generated_answers,
"reference_answer": reference_answers
})
eval_results.to_csv(os.path.join(save_path, "evaluation_results.csv"), index=False)
print(f"Saved evaluation results to {os.path.join(save_path, 'evaluation_results.csv')}")
# Run the main function (can use a config file or default)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--config', type=str, help='Path to config file', default=None)
args = parser.parse_args()
main(args.config)
详细说明
-
模型与分词器加载:
- 使用
trust_remote_code=True 以确保可以加载一些自定义的模型代码(如果 Qwen 模型需要的话)。
- 确保所选的 Qwen 模型名称在 Hugging Face 上是正确的,并且已经被上传。
-
apply_chat_template 函数:
- 该函数将对话列表转换为模型可以理解的输入字符串。
- 例如:
[
{"role": "user", "content": "你好,今天天气怎么样?"},
{"role": "assistant", "content": "今天天气晴朗,适合出行。"}
]
将被转换为:
User: 你好,今天天气怎么样?
Assistant: 今天天气晴朗,适合出行。
-
训练阶段:
- 阶段 I:主要通过交叉熵损失和 KL 散度防止模型模式崩溃。遍历训练数据,格式化输入,计算损失并更新模型参数。
- 阶段 II:引入奖励塑形(Reward Shaping),根据自我纠正的结果调整损失。具体来说,生成初次回答,与修正后的回答进行比较,并根据
reward_function 计算奖励值,调整损失后进行优化。
-
评估功能:
- 在训练完成后,评估函数会遍历评估数据集,为每个问题生成回答,并与正确答案进行比较。
- 目前采用的是简单的准确率(Exact Match),但你可以根据需求添加更复杂的指标,如 BLEU、ROUGE 等。
-
保存结果:
- 训练完成后,模型和分词器会被保存到指定的目录。
- 评估结果也会被保存为 CSV 文件,便于后续分析。
-
运行方式:
注意事项
-
数据格式:确保 SCoRe_dataset.csv 文件包含以下列:question, original_answer, correct_answer。缺失值会被自动过滤。
-
设备:代码会自动检测是否有可用的 GPU 并使用它进行训练。如果没有,将使用 CPU。但是,Qwen 等大模型在 CPU 上可能会非常缓慢。
-
批量大小:当前设置为 1,以保持与原始代码一致。如果有足够的 GPU 内存,可以适当增加 batch_size 以加快训练速度。
-
生成参数:在评估函数中,生成过程采用了采样策略(do_sample=True),并设置了 top_p=0.95 和 temperature=0.7。可以根据需求调整这些参数以获得更好的生成效果。
-
模型兼容性:确保所选择的 Qwen 模型与 AutoModelForCausalLM 兼容。如果模型有特殊要求,请参考具体模型的文档。
结论
上述代码为基于 Qwen 模型的训练和评估提供了一个完整的框架。根据实际需求和数据集的具体情况,可能需要进一步调整和优化。如果在运行过程中遇到任何问题,请检查模型名称、数据格式以及环境配置是否正确。