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+
Uses HuggingFace Transformers Trainer with Qwen2.5-VL processor.
|
| 5 |
+
Freezes the vision encoder to save memory and prevent catastrophic forgetting.
|
| 6 |
+
"""
|
| 7 |
+
import os
|
| 8 |
+
import json
|
| 9 |
+
import torch
|
| 10 |
+
from PIL import Image
|
| 11 |
+
from torch.utils.data import Dataset
|
| 12 |
+
from transformers import (
|
| 13 |
+
Qwen2_5_VLForConditionalGeneration,
|
| 14 |
+
AutoProcessor,
|
| 15 |
+
TrainingArguments,
|
| 16 |
+
Trainer,
|
| 17 |
+
)
|
| 18 |
+
from peft import LoraConfig, get_peft_model, TaskType
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# ===== Configuration =====
|
| 22 |
+
MODEL_NAME = "/workspace/rl4phyx/models/Qwen2.5-VL-3B-Instruct"
|
| 23 |
+
DATA_PATH = "/workspace/rl4phyx/RL4Phyx/SFT/sft_train/sft_train_formatted.jsonl"
|
| 24 |
+
OUTPUT_DIR = "/workspace/rl4phyx/RL4Phyx/SFT/checkpoints/sft_qwen25vl_3b"
|
| 25 |
+
|
| 26 |
+
# Training hyperparameters
|
| 27 |
+
NUM_EPOCHS = 3
|
| 28 |
+
LEARNING_RATE = 1e-4 # LoRA uses higher LR
|
| 29 |
+
PER_DEVICE_BATCH_SIZE = 1 # Small batch for 40GB A100 with VLM
|
| 30 |
+
GRAD_ACCUM_STEPS = 8 # Effective batch = 1 * 4 GPUs * 16 = 64
|
| 31 |
+
MAX_LENGTH = 4096 # Max total sequence length
|
| 32 |
+
USE_LORA = True # LoRA saves memory, merge afterwards for RLVR
|
| 33 |
+
FREEZE_VISION = True # Always freeze vision encoder
|
| 34 |
+
|
| 35 |
+
# LoRA config
|
| 36 |
+
LORA_R = 64
|
| 37 |
+
LORA_ALPHA = 128
|
| 38 |
+
LORA_DROPOUT = 0.05
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class PhysicsCoTDataset(Dataset):
|
| 42 |
+
"""Dataset for Qwen2.5-VL SFT with physics CoT."""
|
| 43 |
+
|
| 44 |
+
def __init__(self, data_path, processor, max_length=2048):
|
| 45 |
+
self.processor = processor
|
| 46 |
+
self.max_length = max_length
|
| 47 |
+
|
| 48 |
+
with open(data_path, 'r', encoding='utf-8') as f:
|
| 49 |
+
self.records = [json.loads(line) for line in f]
|
| 50 |
+
|
| 51 |
+
print(f"Loaded {len(self.records)} records from {data_path}")
|
| 52 |
+
|
| 53 |
+
def __len__(self):
|
| 54 |
+
return len(self.records)
|
| 55 |
+
|
| 56 |
+
def __getitem__(self, idx):
|
| 57 |
+
record = self.records[idx]
|
| 58 |
+
messages = record['messages']
|
| 59 |
+
|
| 60 |
+
# Extract image path from user message
|
| 61 |
+
user_msg = messages[0]
|
| 62 |
+
image_path = None
|
| 63 |
+
text_content = ""
|
| 64 |
+
|
| 65 |
+
for content in user_msg['content']:
|
| 66 |
+
if content['type'] == 'image':
|
| 67 |
+
image_path = content['image'].replace('file://', '')
|
| 68 |
+
elif content['type'] == 'text':
|
| 69 |
+
text_content = content['text']
|
| 70 |
+
|
| 71 |
+
# Extract assistant response
|
| 72 |
+
assistant_msg = messages[1]
|
| 73 |
+
assistant_text = assistant_msg['content'][0]['text']
|
| 74 |
+
|
| 75 |
+
# Load image
|
| 76 |
+
image = Image.open(image_path).convert('RGB')
|
| 77 |
+
|
| 78 |
+
# Build conversation for apply_chat_template
|
| 79 |
+
conversation = [
|
| 80 |
+
{
|
| 81 |
+
"role": "user",
|
| 82 |
+
"content": [
|
| 83 |
+
{"type": "image", "image": image},
|
| 84 |
+
{"type": "text", "text": text_content},
|
| 85 |
+
],
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"role": "assistant",
|
| 89 |
+
"content": [
|
| 90 |
+
{"type": "text", "text": assistant_text},
|
| 91 |
+
],
|
| 92 |
+
},
|
| 93 |
+
]
|
| 94 |
+
|
| 95 |
+
# Use processor to create inputs
|
| 96 |
+
text = self.processor.apply_chat_template(
|
| 97 |
+
conversation,
|
| 98 |
+
tokenize=False,
|
| 99 |
+
add_generation_prompt=False,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
inputs = self.processor(
|
| 103 |
+
text=[text],
|
| 104 |
+
images=[image],
|
| 105 |
+
padding=False,
|
| 106 |
+
truncation=True,
|
| 107 |
+
max_length=self.max_length,
|
| 108 |
+
return_tensors="pt",
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
# Squeeze batch dimension
|
| 112 |
+
input_ids = inputs['input_ids'].squeeze(0)
|
| 113 |
+
attention_mask = inputs['attention_mask'].squeeze(0)
|
| 114 |
+
|
| 115 |
+
# Create labels: mask user tokens (only train on assistant response)
|
| 116 |
+
labels = input_ids.clone()
|
| 117 |
+
|
| 118 |
+
# Find the assistant turn start token and mask everything before it
|
| 119 |
+
# The chat template adds <|im_start|>assistant\n before the response
|
| 120 |
+
assistant_token_str = "<|im_start|>assistant\n"
|
| 121 |
+
assistant_token_ids = self.processor.tokenizer.encode(
|
| 122 |
+
assistant_token_str, add_special_tokens=False
|
| 123 |
+
)
|
| 124 |
+
# Find the position of assistant turn
|
| 125 |
+
input_ids_list = input_ids.tolist()
|
| 126 |
+
assistant_start = -1
|
| 127 |
+
for i in range(len(input_ids_list) - len(assistant_token_ids) + 1):
|
| 128 |
+
if input_ids_list[i:i + len(assistant_token_ids)] == assistant_token_ids:
|
| 129 |
+
assistant_start = i + len(assistant_token_ids)
|
| 130 |
+
break
|
| 131 |
+
|
| 132 |
+
if assistant_start > 0:
|
| 133 |
+
labels[:assistant_start] = -100 # Mask user prompt
|
| 134 |
+
else:
|
| 135 |
+
# Fallback: mask first 30% as approximate user tokens
|
| 136 |
+
mask_len = int(len(labels) * 0.3)
|
| 137 |
+
labels[:mask_len] = -100
|
| 138 |
+
|
| 139 |
+
# Also mask padding
|
| 140 |
+
labels[attention_mask == 0] = -100
|
| 141 |
+
|
| 142 |
+
return {
|
| 143 |
+
'input_ids': input_ids,
|
| 144 |
+
'attention_mask': attention_mask,
|
| 145 |
+
'labels': labels,
|
| 146 |
+
'pixel_values': inputs.get('pixel_values', torch.tensor([])).squeeze(0) if 'pixel_values' in inputs else None,
|
| 147 |
+
'image_grid_thw': inputs.get('image_grid_thw', torch.tensor([])).squeeze(0) if 'image_grid_thw' in inputs else None,
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class VLMDataCollator:
|
| 152 |
+
"""Custom data collator for variable-length VLM inputs."""
|
| 153 |
+
|
| 154 |
+
def __init__(self, processor):
|
| 155 |
+
self.processor = processor
|
| 156 |
+
self.pad_token_id = processor.tokenizer.pad_token_id or processor.tokenizer.eos_token_id
|
| 157 |
+
|
| 158 |
+
def __call__(self, features):
|
| 159 |
+
# Pad input_ids, attention_mask, labels
|
| 160 |
+
max_len = max(f['input_ids'].size(0) for f in features)
|
| 161 |
+
|
| 162 |
+
input_ids = []
|
| 163 |
+
attention_mask = []
|
| 164 |
+
labels = []
|
| 165 |
+
pixel_values = []
|
| 166 |
+
image_grid_thw = []
|
| 167 |
+
|
| 168 |
+
for f in features:
|
| 169 |
+
seq_len = f['input_ids'].size(0)
|
| 170 |
+
pad_len = max_len - seq_len
|
| 171 |
+
|
| 172 |
+
# Right-pad
|
| 173 |
+
input_ids.append(torch.cat([
|
| 174 |
+
f['input_ids'],
|
| 175 |
+
torch.full((pad_len,), self.pad_token_id, dtype=f['input_ids'].dtype)
|
| 176 |
+
]))
|
| 177 |
+
attention_mask.append(torch.cat([
|
| 178 |
+
f['attention_mask'],
|
| 179 |
+
torch.zeros(pad_len, dtype=f['attention_mask'].dtype)
|
| 180 |
+
]))
|
| 181 |
+
labels.append(torch.cat([
|
| 182 |
+
f['labels'],
|
| 183 |
+
torch.full((pad_len,), -100, dtype=f['labels'].dtype)
|
| 184 |
+
]))
|
| 185 |
+
|
| 186 |
+
if f.get('pixel_values') is not None:
|
| 187 |
+
pixel_values.append(f['pixel_values'])
|
| 188 |
+
if f.get('image_grid_thw') is not None:
|
| 189 |
+
image_grid_thw.append(f['image_grid_thw'])
|
| 190 |
+
|
| 191 |
+
batch = {
|
| 192 |
+
'input_ids': torch.stack(input_ids),
|
| 193 |
+
'attention_mask': torch.stack(attention_mask),
|
| 194 |
+
'labels': torch.stack(labels),
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
if pixel_values:
|
| 198 |
+
batch['pixel_values'] = torch.cat(pixel_values, dim=0)
|
| 199 |
+
if image_grid_thw:
|
| 200 |
+
batch['image_grid_thw'] = torch.stack(image_grid_thw)
|
| 201 |
+
|
| 202 |
+
return batch
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def main():
|
| 206 |
+
print(f"Loading model: {MODEL_NAME}")
|
| 207 |
+
print(f"Data: {DATA_PATH}")
|
| 208 |
+
print(f"Output: {OUTPUT_DIR}")
|
| 209 |
+
print(f"LoRA: {USE_LORA}, Freeze Vision: {FREEZE_VISION}")
|
| 210 |
+
print(f"Epochs: {NUM_EPOCHS}, LR: {LEARNING_RATE}, Batch: {PER_DEVICE_BATCH_SIZE} x {GRAD_ACCUM_STEPS}")
|
| 211 |
+
|
| 212 |
+
# Load processor
|
| 213 |
+
processor = AutoProcessor.from_pretrained(
|
| 214 |
+
MODEL_NAME,
|
| 215 |
+
min_pixels=3136, # 56x56
|
| 216 |
+
max_pixels=200704, # ~256 image tokens
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
# Load model
|
| 220 |
+
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 221 |
+
MODEL_NAME,
|
| 222 |
+
torch_dtype=torch.bfloat16,
|
| 223 |
+
attn_implementation="sdpa",
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
# Freeze vision encoder
|
| 227 |
+
if FREEZE_VISION:
|
| 228 |
+
for name, param in model.named_parameters():
|
| 229 |
+
if 'visual' in name:
|
| 230 |
+
param.requires_grad = False
|
| 231 |
+
print("Froze vision encoder parameters")
|
| 232 |
+
|
| 233 |
+
# Apply LoRA
|
| 234 |
+
if USE_LORA:
|
| 235 |
+
# Target only language model layers
|
| 236 |
+
lora_config = LoraConfig(
|
| 237 |
+
r=LORA_R,
|
| 238 |
+
lora_alpha=LORA_ALPHA,
|
| 239 |
+
lora_dropout=LORA_DROPOUT,
|
| 240 |
+
target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
|
| 241 |
+
task_type=TaskType.CAUSAL_LM,
|
| 242 |
+
)
|
| 243 |
+
model = get_peft_model(model, lora_config)
|
| 244 |
+
model.enable_input_require_grads() # Required for gradient_checkpointing + LoRA
|
| 245 |
+
model.print_trainable_parameters()
|
| 246 |
+
|
| 247 |
+
# Create dataset
|
| 248 |
+
dataset = PhysicsCoTDataset(data_path=DATA_PATH, processor=processor, max_length=MAX_LENGTH)
|
| 249 |
+
|
| 250 |
+
# Training arguments
|
| 251 |
+
training_args = TrainingArguments(
|
| 252 |
+
output_dir=OUTPUT_DIR,
|
| 253 |
+
overwrite_output_dir=True,
|
| 254 |
+
num_train_epochs=NUM_EPOCHS,
|
| 255 |
+
per_device_train_batch_size=PER_DEVICE_BATCH_SIZE,
|
| 256 |
+
gradient_accumulation_steps=GRAD_ACCUM_STEPS,
|
| 257 |
+
learning_rate=LEARNING_RATE,
|
| 258 |
+
lr_scheduler_type="cosine",
|
| 259 |
+
warmup_ratio=0.1,
|
| 260 |
+
weight_decay=0.01,
|
| 261 |
+
bf16=True,
|
| 262 |
+
logging_steps=5,
|
| 263 |
+
save_strategy="epoch",
|
| 264 |
+
save_total_limit=3,
|
| 265 |
+
dataloader_num_workers=4,
|
| 266 |
+
gradient_checkpointing=True,
|
| 267 |
+
gradient_checkpointing_kwargs={'use_reentrant': False},
|
| 268 |
+
remove_unused_columns=False,
|
| 269 |
+
report_to="none",
|
| 270 |
+
ddp_find_unused_parameters=True, # Must be True: frozen vision params not in backward graph
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
# Collator
|
| 274 |
+
collator = VLMDataCollator(processor)
|
| 275 |
+
|
| 276 |
+
# Trainer
|
| 277 |
+
trainer = Trainer(
|
| 278 |
+
model=model,
|
| 279 |
+
args=training_args,
|
| 280 |
+
train_dataset=dataset,
|
| 281 |
+
data_collator=collator,
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
# Train
|
| 285 |
+
print("\n===== Starting SFT Training =====")
|
| 286 |
+
trainer.train()
|
| 287 |
+
|
| 288 |
+
# Save final model
|
| 289 |
+
print("\n===== Saving final model =====")
|
| 290 |
+
trainer.save_model(os.path.join(OUTPUT_DIR, "final"))
|
| 291 |
+
|
| 292 |
+
if USE_LORA:
|
| 293 |
+
# Also merge LoRA and save full model for RLVR
|
| 294 |
+
print("Merging LoRA weights...")
|
| 295 |
+
merged_model = model.merge_and_unload()
|
| 296 |
+
merged_output = os.path.join(OUTPUT_DIR, "merged")
|
| 297 |
+
merged_model.save_pretrained(merged_output)
|
| 298 |
+
processor.save_pretrained(merged_output)
|
| 299 |
+
# Copy visual processor config files from original model
|
| 300 |
+
import shutil
|
| 301 |
+
model_dir = MODEL_NAME
|
| 302 |
+
for fname in ['preprocessor_config.json', 'chat_template.json']:
|
| 303 |
+
src = os.path.join(model_dir, fname)
|
| 304 |
+
if os.path.exists(src):
|
| 305 |
+
shutil.copy2(src, os.path.join(merged_output, fname))
|
| 306 |
+
print(f'Copied {fname} to merged output')
|
| 307 |
+
print(f"Merged model saved to: {merged_output}")
|
| 308 |
+
|
| 309 |
+
print("\n===== SFT Training Complete =====")
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
if __name__ == "__main__":
|
| 313 |
+
main()
|