Repository navigation
Expand file tree
/
Copy pathsimple_sft.py
More file actions
136 lines (114 loc) · 3.84 KB
/
Copy pathsimple_sft.py
File metadata and controls
136 lines (114 loc) · 3.84 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
#!/usr/bin/env python3
import torch
from transformers import Qwen3VLForConditionalGeneration, AutoProcessor, TrainingArguments, Trainer
from peft import LoraConfig, get_peft_model
import json
from torch.utils.data import Dataset
import cv2
from PIL import Image
import os
class NexarSFTDataset(Dataset):
def __init__(self, json_path, media_path, processor, max_length=4096):
self.processor = processor
self.max_length = max_length
self.media_path = media_path
with open(json_path, 'r') as f:
self.data = json.load(f)
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
item = self.data[idx]
# Load video with OpenCV
video_path = os.path.join(self.media_path, item['videos'][0])
cap = cv2.VideoCapture(video_path)
fps = cap.get(cv2.CAP_PROP_FPS)
frame_interval = int(fps / 4)
frames = []
count = 0
while len(frames) < 40:
ret, frame = cap.read()
if not ret:
break
if count % frame_interval == 0:
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frames.append(Image.fromarray(rgb))
count += 1
cap.release()
# Build conversation
messages = [
{"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant."}]},
{"role": "user", "content": [
{"type": "video", "video": frames, "fps": 4, "max_pixels": 768*768},
{"type": "text", "text": item['conversations'][0]['value']}
]},
{"role": "assistant", "content": [{"type": "text", "text": item['conversations'][1]['value']}]}
]
# Apply chat template
inputs = self.processor.apply_chat_template(
messages,
tokenize=True,
add_generation_prompt=False,
return_dict=True,
return_tensors="pt"
)
# Remove batch dimension
for key in inputs:
if isinstance(inputs[key], torch.Tensor) and inputs[key].dim() > 1:
inputs[key] = inputs[key].squeeze(0)
# Labels are the same as input_ids for causal LM
inputs["labels"] = inputs["input_ids"].clone()
return inputs
def main():
# Load model
model_name = "nvidia/Cosmos-Reason2-2B"
model = Qwen3VLForConditionalGeneration.from_pretrained(
model_name,
device_map="auto",
torch_dtype=torch.float16,
)
processor = AutoProcessor.from_pretrained(model_name)
# LoRA config
lora_config = LoraConfig(
r=16,
lora_alpha=32,
target_modules=["q_proj", "v_proj", "k_proj", "o_proj"],
lora_dropout=0.1,
bias="none",
task_type="CAUSAL_LM"
)
# Apply LoRA
model = get_peft_model(model, lora_config)
model.train()
# Dataset
dataset = NexarSFTDataset(
"/teamspace/studios/this_studio/nexar_data/sft/train.json",
"./nexar_data/sample_videos",
processor
)
# Training arguments
training_args = TrainingArguments(
output_dir="/tmp/cosmos_reason2/sft_output",
num_train_epochs=100,
per_device_train_batch_size=1,
gradient_accumulation_steps=4,
warmup_steps=100,
logging_steps=10,
save_steps=100,
eval_steps=100,
learning_rate=1e-4,
fp16=True,
dataloader_num_workers=0,
remove_unused_columns=False,
)
# Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=dataset,
)
# Train
trainer.train()
# Save
trainer.save_model("/tmp/cosmos_reason2/sft_output/final")
if __name__ == "__main__":
main()