Upload vlm-streaming-sft-unsloth-qwen.py with huggingface_hub
Browse files- vlm-streaming-sft-unsloth-qwen.py +177 -54
vlm-streaming-sft-unsloth-qwen.py
CHANGED
|
@@ -10,27 +10,36 @@
|
|
| 10 |
# ]
|
| 11 |
# ///
|
| 12 |
"""
|
| 13 |
-
Fine-tune Vision Language Models using
|
| 14 |
|
| 15 |
-
Streams data directly from the Hub - no disk space needed for massive VLM datasets.
|
| 16 |
Uses Unsloth for ~60% less VRAM and 2x faster training.
|
|
|
|
| 17 |
|
| 18 |
-
Run locally
|
| 19 |
-
uv run vlm-streaming-sft-unsloth.py \
|
| 20 |
-
--max-steps
|
|
|
|
|
|
|
| 21 |
--output-repo your-username/vlm-test
|
| 22 |
|
| 23 |
Run on HF Jobs:
|
| 24 |
-
hf jobs uv run
|
| 25 |
-
|
| 26 |
-
--
|
| 27 |
-
-- \
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
--max-steps 500 \
|
| 29 |
--output-repo your-username/vlm-finetuned
|
| 30 |
|
| 31 |
With Trackio dashboard:
|
| 32 |
-
uv run vlm-streaming-sft-unsloth.py \
|
| 33 |
-
--max-steps
|
|
|
|
| 34 |
--output-repo your-username/vlm-finetuned \
|
| 35 |
--trackio-space your-username/trackio
|
| 36 |
"""
|
|
@@ -163,6 +172,32 @@ Examples:
|
|
| 163 |
help="Local directory to save model (default: vlm-streaming-output)",
|
| 164 |
)
|
| 165 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
return parser.parse_args()
|
| 167 |
|
| 168 |
|
|
@@ -170,11 +205,19 @@ def main():
|
|
| 170 |
args = parse_args()
|
| 171 |
|
| 172 |
print("=" * 70)
|
| 173 |
-
print("VLM
|
| 174 |
print("=" * 70)
|
| 175 |
print("\nConfiguration:")
|
| 176 |
print(f" Base model: {args.base_model}")
|
| 177 |
print(f" Dataset: {args.dataset}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
print(f" Max steps: {args.max_steps}")
|
| 179 |
print(
|
| 180 |
f" Batch size: {args.batch_size} x {args.gradient_accumulation} = {args.batch_size * args.gradient_accumulation}"
|
|
@@ -194,7 +237,9 @@ def main():
|
|
| 194 |
# Set Trackio space if provided
|
| 195 |
if args.trackio_space:
|
| 196 |
os.environ["TRACKIO_SPACE_ID"] = args.trackio_space
|
| 197 |
-
logger.info(
|
|
|
|
|
|
|
| 198 |
|
| 199 |
# Import heavy dependencies (note: import from unsloth.trainer for VLM)
|
| 200 |
from unsloth import FastVisionModel
|
|
@@ -237,31 +282,74 @@ def main():
|
|
| 237 |
)
|
| 238 |
print(f"Model loaded in {time.time() - start:.1f}s")
|
| 239 |
|
| 240 |
-
# 2. Load streaming
|
| 241 |
-
print(
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
dataset = load_dataset(
|
| 245 |
-
args.dataset,
|
| 246 |
-
split="train",
|
| 247 |
-
streaming=True,
|
| 248 |
)
|
|
|
|
| 249 |
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
|
| 266 |
# 3. Configure trainer
|
| 267 |
print("\n[3/5] Configuring trainer...")
|
|
@@ -280,7 +368,7 @@ def main():
|
|
| 280 |
optim="adamw_8bit", # Per notebook
|
| 281 |
weight_decay=0.001,
|
| 282 |
lr_scheduler_type="linear", # Per notebook (not cosine)
|
| 283 |
-
seed=
|
| 284 |
# VLM-specific settings (required for Unsloth)
|
| 285 |
remove_unused_columns=False,
|
| 286 |
dataset_text_field="",
|
|
@@ -288,13 +376,14 @@ def main():
|
|
| 288 |
max_length=args.max_seq_length,
|
| 289 |
# Logging
|
| 290 |
report_to="trackio",
|
| 291 |
-
run_name=f"vlm-
|
| 292 |
)
|
| 293 |
|
| 294 |
-
#
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
|
|
|
| 298 |
|
| 299 |
# Use older 'tokenizer=' parameter (not processing_class) - required for Unsloth VLM
|
| 300 |
trainer = SFTTrainer(
|
|
@@ -302,6 +391,7 @@ def main():
|
|
| 302 |
tokenizer=tokenizer, # Full processor, not processor.tokenizer
|
| 303 |
data_collator=UnslothVisionDataCollator(model, tokenizer),
|
| 304 |
train_dataset=train_data,
|
|
|
|
| 305 |
args=training_config,
|
| 306 |
)
|
| 307 |
|
|
@@ -309,12 +399,36 @@ def main():
|
|
| 309 |
print(f"\n[4/5] Training for {args.max_steps} steps...")
|
| 310 |
start = time.time()
|
| 311 |
|
| 312 |
-
trainer.train()
|
| 313 |
|
| 314 |
train_time = time.time() - start
|
| 315 |
print(f"\nTraining completed in {train_time / 60:.1f} minutes")
|
| 316 |
print(f" Speed: {args.max_steps / train_time:.2f} steps/s")
|
| 317 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
# 5. Save and push
|
| 319 |
print("\n[5/5] Saving model...")
|
| 320 |
|
|
@@ -337,27 +451,36 @@ if __name__ == "__main__":
|
|
| 337 |
# Show example usage if no arguments
|
| 338 |
if len(sys.argv) == 1:
|
| 339 |
print("=" * 70)
|
| 340 |
-
print("VLM
|
| 341 |
print("=" * 70)
|
| 342 |
-
print("\nFine-tune Vision-Language Models
|
| 343 |
-
print("Data streams directly from the Hub - no disk space needed.")
|
| 344 |
print("\nFeatures:")
|
| 345 |
print(" - ~60% less VRAM with Unsloth optimizations")
|
| 346 |
print(" - 2x faster training vs standard methods")
|
|
|
|
| 347 |
print(" - Trackio integration for monitoring")
|
| 348 |
print(" - Works with any VLM dataset in conversation format")
|
| 349 |
-
print("\nExample usage:")
|
| 350 |
-
print("\n uv run vlm-streaming-sft-unsloth.py \\")
|
| 351 |
-
print(" --max-steps
|
|
|
|
|
|
|
| 352 |
print(" --output-repo your-username/vlm-finetuned")
|
| 353 |
print("\nHF Jobs example:")
|
| 354 |
-
print("\n hf jobs uv run
|
| 355 |
-
print(
|
| 356 |
-
|
| 357 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
print(" --max-steps 500 \\")
|
| 359 |
print(" --output-repo your-username/vlm-finetuned")
|
| 360 |
-
print("\nFor full help: uv run vlm-streaming-sft-unsloth.py --help")
|
| 361 |
print("=" * 70)
|
| 362 |
sys.exit(0)
|
| 363 |
|
|
|
|
| 10 |
# ]
|
| 11 |
# ///
|
| 12 |
"""
|
| 13 |
+
Fine-tune Vision Language Models using Unsloth optimizations.
|
| 14 |
|
|
|
|
| 15 |
Uses Unsloth for ~60% less VRAM and 2x faster training.
|
| 16 |
+
Supports optional train/eval split to verify generalization (not just memorization).
|
| 17 |
|
| 18 |
+
Run locally with evaluation (recommended):
|
| 19 |
+
uv run vlm-streaming-sft-unsloth-qwen.py \
|
| 20 |
+
--max-steps 200 \
|
| 21 |
+
--num-samples 500 \
|
| 22 |
+
--eval-split 0.2 \
|
| 23 |
--output-repo your-username/vlm-test
|
| 24 |
|
| 25 |
Run on HF Jobs:
|
| 26 |
+
hf jobs uv run --flavor a100-large --secrets HF_TOKEN -- \
|
| 27 |
+
https://huggingface.co/datasets/uv-scripts/training/raw/main/vlm-streaming-sft-unsloth-qwen.py \
|
| 28 |
+
--max-steps 200 \
|
| 29 |
+
--num-samples 500 \
|
| 30 |
+
--eval-split 0.2 \
|
| 31 |
+
--output-repo your-username/vlm-finetuned
|
| 32 |
+
|
| 33 |
+
For very large datasets, use streaming mode:
|
| 34 |
+
uv run vlm-streaming-sft-unsloth-qwen.py \
|
| 35 |
+
--streaming \
|
| 36 |
--max-steps 500 \
|
| 37 |
--output-repo your-username/vlm-finetuned
|
| 38 |
|
| 39 |
With Trackio dashboard:
|
| 40 |
+
uv run vlm-streaming-sft-unsloth-qwen.py \
|
| 41 |
+
--max-steps 200 \
|
| 42 |
+
--eval-split 0.2 \
|
| 43 |
--output-repo your-username/vlm-finetuned \
|
| 44 |
--trackio-space your-username/trackio
|
| 45 |
"""
|
|
|
|
| 172 |
help="Local directory to save model (default: vlm-streaming-output)",
|
| 173 |
)
|
| 174 |
|
| 175 |
+
# Evaluation and data control
|
| 176 |
+
parser.add_argument(
|
| 177 |
+
"--eval-split",
|
| 178 |
+
type=float,
|
| 179 |
+
default=0.0,
|
| 180 |
+
help="Fraction of data for evaluation (0.0-0.5). Default: 0.0 (no eval)",
|
| 181 |
+
)
|
| 182 |
+
parser.add_argument(
|
| 183 |
+
"--num-samples",
|
| 184 |
+
type=int,
|
| 185 |
+
default=None,
|
| 186 |
+
help="Limit samples (default: None = use all for non-streaming, 500 for streaming)",
|
| 187 |
+
)
|
| 188 |
+
parser.add_argument(
|
| 189 |
+
"--seed",
|
| 190 |
+
type=int,
|
| 191 |
+
default=3407,
|
| 192 |
+
help="Random seed for reproducibility (default: 3407)",
|
| 193 |
+
)
|
| 194 |
+
parser.add_argument(
|
| 195 |
+
"--streaming",
|
| 196 |
+
action="store_true",
|
| 197 |
+
default=False,
|
| 198 |
+
help="Use streaming mode (default: False). Use for very large datasets.",
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
return parser.parse_args()
|
| 202 |
|
| 203 |
|
|
|
|
| 205 |
args = parse_args()
|
| 206 |
|
| 207 |
print("=" * 70)
|
| 208 |
+
print("VLM Fine-tuning with Unsloth")
|
| 209 |
print("=" * 70)
|
| 210 |
print("\nConfiguration:")
|
| 211 |
print(f" Base model: {args.base_model}")
|
| 212 |
print(f" Dataset: {args.dataset}")
|
| 213 |
+
print(f" Streaming: {args.streaming}")
|
| 214 |
+
print(
|
| 215 |
+
f" Num samples: {args.num_samples or ('500' if args.streaming else 'all')}"
|
| 216 |
+
)
|
| 217 |
+
print(
|
| 218 |
+
f" Eval split: {args.eval_split if args.eval_split > 0 else '(disabled)'}"
|
| 219 |
+
)
|
| 220 |
+
print(f" Seed: {args.seed}")
|
| 221 |
print(f" Max steps: {args.max_steps}")
|
| 222 |
print(
|
| 223 |
f" Batch size: {args.batch_size} x {args.gradient_accumulation} = {args.batch_size * args.gradient_accumulation}"
|
|
|
|
| 237 |
# Set Trackio space if provided
|
| 238 |
if args.trackio_space:
|
| 239 |
os.environ["TRACKIO_SPACE_ID"] = args.trackio_space
|
| 240 |
+
logger.info(
|
| 241 |
+
f"Trackio dashboard: https://huggingface.co/spaces/{args.trackio_space}"
|
| 242 |
+
)
|
| 243 |
|
| 244 |
# Import heavy dependencies (note: import from unsloth.trainer for VLM)
|
| 245 |
from unsloth import FastVisionModel
|
|
|
|
| 282 |
)
|
| 283 |
print(f"Model loaded in {time.time() - start:.1f}s")
|
| 284 |
|
| 285 |
+
# 2. Load dataset (streaming or non-streaming)
|
| 286 |
+
print(
|
| 287 |
+
f"\n[2/5] Loading dataset ({'streaming' if args.streaming else 'non-streaming'})..."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
)
|
| 289 |
+
start = time.time()
|
| 290 |
|
| 291 |
+
if args.streaming:
|
| 292 |
+
# Streaming mode: take limited samples
|
| 293 |
+
dataset = load_dataset(args.dataset, split="train", streaming=True)
|
| 294 |
+
num_samples = args.num_samples or 500
|
| 295 |
+
|
| 296 |
+
# Peek at first sample to show info
|
| 297 |
+
sample = next(iter(dataset))
|
| 298 |
+
if "messages" in sample:
|
| 299 |
+
print(f" Sample has {len(sample['messages'])} messages")
|
| 300 |
+
if "images" in sample:
|
| 301 |
+
img_count = (
|
| 302 |
+
len(sample["images"]) if isinstance(sample["images"], list) else 1
|
| 303 |
+
)
|
| 304 |
+
print(f" Sample has {img_count} image(s)")
|
| 305 |
+
|
| 306 |
+
# Reload and take samples
|
| 307 |
+
dataset = load_dataset(args.dataset, split="train", streaming=True)
|
| 308 |
+
all_data = list(dataset.take(num_samples))
|
| 309 |
+
print(f" Loaded {len(all_data)} samples in {time.time() - start:.1f}s")
|
| 310 |
+
|
| 311 |
+
if args.eval_split > 0:
|
| 312 |
+
# Manual shuffle for streaming (no built-in split)
|
| 313 |
+
import random
|
| 314 |
+
|
| 315 |
+
random.seed(args.seed)
|
| 316 |
+
random.shuffle(all_data)
|
| 317 |
+
split_idx = int(len(all_data) * (1 - args.eval_split))
|
| 318 |
+
train_data = all_data[:split_idx]
|
| 319 |
+
eval_data = all_data[split_idx:]
|
| 320 |
+
print(f" Train: {len(train_data)} samples, Eval: {len(eval_data)} samples")
|
| 321 |
+
else:
|
| 322 |
+
train_data = all_data
|
| 323 |
+
eval_data = None
|
| 324 |
+
else:
|
| 325 |
+
# Non-streaming: use proper train_test_split
|
| 326 |
+
dataset = load_dataset(args.dataset, split="train")
|
| 327 |
+
print(f" Dataset has {len(dataset)} total samples")
|
| 328 |
+
|
| 329 |
+
# Peek at first sample
|
| 330 |
+
sample = dataset[0]
|
| 331 |
+
if "messages" in sample:
|
| 332 |
+
print(f" Sample has {len(sample['messages'])} messages")
|
| 333 |
+
if "images" in sample:
|
| 334 |
+
img_count = (
|
| 335 |
+
len(sample["images"]) if isinstance(sample["images"], list) else 1
|
| 336 |
+
)
|
| 337 |
+
print(f" Sample has {img_count} image(s)")
|
| 338 |
+
|
| 339 |
+
if args.num_samples:
|
| 340 |
+
dataset = dataset.select(range(min(args.num_samples, len(dataset))))
|
| 341 |
+
print(f" Limited to {len(dataset)} samples")
|
| 342 |
+
|
| 343 |
+
if args.eval_split > 0:
|
| 344 |
+
split = dataset.train_test_split(test_size=args.eval_split, seed=args.seed)
|
| 345 |
+
train_data = list(split["train"])
|
| 346 |
+
eval_data = list(split["test"])
|
| 347 |
+
print(f" Train: {len(train_data)} samples, Eval: {len(eval_data)} samples")
|
| 348 |
+
else:
|
| 349 |
+
train_data = list(dataset)
|
| 350 |
+
eval_data = None
|
| 351 |
+
|
| 352 |
+
print(f" Dataset ready in {time.time() - start:.1f}s")
|
| 353 |
|
| 354 |
# 3. Configure trainer
|
| 355 |
print("\n[3/5] Configuring trainer...")
|
|
|
|
| 368 |
optim="adamw_8bit", # Per notebook
|
| 369 |
weight_decay=0.001,
|
| 370 |
lr_scheduler_type="linear", # Per notebook (not cosine)
|
| 371 |
+
seed=args.seed,
|
| 372 |
# VLM-specific settings (required for Unsloth)
|
| 373 |
remove_unused_columns=False,
|
| 374 |
dataset_text_field="",
|
|
|
|
| 376 |
max_length=args.max_seq_length,
|
| 377 |
# Logging
|
| 378 |
report_to="trackio",
|
| 379 |
+
run_name=f"vlm-sft-{args.max_steps}steps",
|
| 380 |
)
|
| 381 |
|
| 382 |
+
# Add evaluation config if eval is enabled
|
| 383 |
+
if eval_data:
|
| 384 |
+
training_config.eval_strategy = "steps"
|
| 385 |
+
training_config.eval_steps = max(1, args.max_steps // 5)
|
| 386 |
+
print(f" Evaluation enabled: every {training_config.eval_steps} steps")
|
| 387 |
|
| 388 |
# Use older 'tokenizer=' parameter (not processing_class) - required for Unsloth VLM
|
| 389 |
trainer = SFTTrainer(
|
|
|
|
| 391 |
tokenizer=tokenizer, # Full processor, not processor.tokenizer
|
| 392 |
data_collator=UnslothVisionDataCollator(model, tokenizer),
|
| 393 |
train_dataset=train_data,
|
| 394 |
+
eval_dataset=eval_data, # None if no eval
|
| 395 |
args=training_config,
|
| 396 |
)
|
| 397 |
|
|
|
|
| 399 |
print(f"\n[4/5] Training for {args.max_steps} steps...")
|
| 400 |
start = time.time()
|
| 401 |
|
| 402 |
+
train_result = trainer.train()
|
| 403 |
|
| 404 |
train_time = time.time() - start
|
| 405 |
print(f"\nTraining completed in {train_time / 60:.1f} minutes")
|
| 406 |
print(f" Speed: {args.max_steps / train_time:.2f} steps/s")
|
| 407 |
|
| 408 |
+
# Print training metrics
|
| 409 |
+
if train_result.metrics:
|
| 410 |
+
train_loss = train_result.metrics.get("train_loss")
|
| 411 |
+
if train_loss:
|
| 412 |
+
print(f" Final train loss: {train_loss:.4f}")
|
| 413 |
+
|
| 414 |
+
# Print eval results if eval was enabled
|
| 415 |
+
if eval_data:
|
| 416 |
+
print("\nRunning final evaluation...")
|
| 417 |
+
eval_results = trainer.evaluate()
|
| 418 |
+
eval_loss = eval_results.get("eval_loss")
|
| 419 |
+
if eval_loss:
|
| 420 |
+
print(f" Final eval loss: {eval_loss:.4f}")
|
| 421 |
+
if train_loss:
|
| 422 |
+
ratio = eval_loss / train_loss
|
| 423 |
+
if ratio > 1.5:
|
| 424 |
+
print(
|
| 425 |
+
f" ⚠️ Eval loss is {ratio:.1f}x train loss - possible overfitting"
|
| 426 |
+
)
|
| 427 |
+
else:
|
| 428 |
+
print(
|
| 429 |
+
f" ✓ Eval/train ratio: {ratio:.2f} - model generalizes well"
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
# 5. Save and push
|
| 433 |
print("\n[5/5] Saving model...")
|
| 434 |
|
|
|
|
| 451 |
# Show example usage if no arguments
|
| 452 |
if len(sys.argv) == 1:
|
| 453 |
print("=" * 70)
|
| 454 |
+
print("VLM Fine-tuning with Unsloth")
|
| 455 |
print("=" * 70)
|
| 456 |
+
print("\nFine-tune Vision-Language Models with optional train/eval split.")
|
|
|
|
| 457 |
print("\nFeatures:")
|
| 458 |
print(" - ~60% less VRAM with Unsloth optimizations")
|
| 459 |
print(" - 2x faster training vs standard methods")
|
| 460 |
+
print(" - Optional evaluation to detect overfitting")
|
| 461 |
print(" - Trackio integration for monitoring")
|
| 462 |
print(" - Works with any VLM dataset in conversation format")
|
| 463 |
+
print("\nExample usage (with evaluation):")
|
| 464 |
+
print("\n uv run vlm-streaming-sft-unsloth-qwen.py \\")
|
| 465 |
+
print(" --max-steps 200 \\")
|
| 466 |
+
print(" --num-samples 500 \\")
|
| 467 |
+
print(" --eval-split 0.2 \\")
|
| 468 |
print(" --output-repo your-username/vlm-finetuned")
|
| 469 |
print("\nHF Jobs example:")
|
| 470 |
+
print("\n hf jobs uv run --flavor a100-large --secrets HF_TOKEN -- \\")
|
| 471 |
+
print(
|
| 472 |
+
" https://huggingface.co/datasets/uv-scripts/training/raw/main/vlm-streaming-sft-unsloth-qwen.py \\"
|
| 473 |
+
)
|
| 474 |
+
print(" --max-steps 200 \\")
|
| 475 |
+
print(" --num-samples 500 \\")
|
| 476 |
+
print(" --eval-split 0.2 \\")
|
| 477 |
+
print(" --output-repo your-username/vlm-finetuned")
|
| 478 |
+
print("\nFor large datasets, use --streaming to avoid loading all data:")
|
| 479 |
+
print("\n uv run vlm-streaming-sft-unsloth-qwen.py \\")
|
| 480 |
+
print(" --streaming \\")
|
| 481 |
print(" --max-steps 500 \\")
|
| 482 |
print(" --output-repo your-username/vlm-finetuned")
|
| 483 |
+
print("\nFor full help: uv run vlm-streaming-sft-unsloth-qwen.py --help")
|
| 484 |
print("=" * 70)
|
| 485 |
sys.exit(0)
|
| 486 |
|