详解下面代码背后的逻辑, 隐式的cot是如何实现的; 蕴含了什么数学原理:import torch import torch.nn as nn import…
- User
详解下面代码背后的逻辑, 隐式的cot是如何实现的; 蕴含了什么数学原理: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
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_stage1": 1e-5, "learning_rate_stage2": 1e-5, "epochs_stage_1": 2, "epochs_stage_2": 3, "beta_kl_stage1": 0.1, "beta_kl_stage2": 0.05, "alpha_reward_bonus": 2.0, "data_file": "SCoRe_dataset.csv", "max_length": 512, # Maximum token length "batch_size": 1, # For simplicity, keep it 1. Adjust as needed "device": "cuda" if torch.cuda.is_available() else "cpu" } 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: Training the Model to Generate Correct Answers Directly
def stage_one_initialization(train_model, reference_model, tokenizer, data, config): optimizer = optim.AdamW(train_model.parameters(), lr=config["learning_rate_stage1"]) train_model.train() reference_model.eval() # Ensure reference model is in eval mode
code - Assistant