File size: 17,996 Bytes
15582ee | 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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 | # /// script
# requires-python = ">=3.10"
# dependencies = [
# "unsloth",
# "datasets",
# "trl==0.22.2",
# "huggingface_hub[hf_transfer]",
# "transformers==4.57.1",
# ]
# ///
"""
Fine-tune Vision Language Models using Unsloth optimizations.
Uses Unsloth for ~60% less VRAM and 2x faster training.
Supports epoch-based or step-based training with optional eval split.
Epoch-based training (recommended for full datasets):
uv run vlm-streaming-sft-unsloth-qwen.py \
--num-epochs 1 \
--eval-split 0.2 \
--output-repo your-username/vlm-finetuned
Run on HF Jobs (1 epoch with eval):
hf jobs uv run --flavor a100-large --secrets HF_TOKEN --timeout 4h -- \
https://huggingface.co/datasets/uv-scripts/training/raw/main/vlm-streaming-sft-unsloth-qwen.py \
--num-epochs 1 \
--eval-split 0.2 \
--trackio-space your-username/trackio \
--output-repo your-username/vlm-finetuned
Step-based training (for streaming or quick tests):
uv run vlm-streaming-sft-unsloth-qwen.py \
--streaming \
--max-steps 500 \
--output-repo your-username/vlm-finetuned
Quick test with limited samples:
uv run vlm-streaming-sft-unsloth-qwen.py \
--num-samples 500 \
--num-epochs 2 \
--eval-split 0.2 \
--output-repo your-username/vlm-test
"""
import argparse
import logging
import os
import sys
import time
# Force unbuffered output for HF Jobs logs
sys.stdout.reconfigure(line_buffering=True)
sys.stderr.reconfigure(line_buffering=True)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
def check_cuda():
"""Check CUDA availability and exit if not available."""
import torch
if not torch.cuda.is_available():
logger.error("CUDA is not available. This script requires a GPU.")
logger.error("Run on a machine with a CUDA-capable GPU or use HF Jobs:")
logger.error(
" hf jobs uv run vlm-streaming-sft-unsloth.py --flavor a100-large ..."
)
sys.exit(1)
logger.info(f"CUDA available: {torch.cuda.get_device_name(0)}")
def parse_args():
parser = argparse.ArgumentParser(
description="Fine-tune VLMs with streaming datasets using Unsloth",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Quick test run
uv run vlm-streaming-sft-unsloth.py \\
--max-steps 50 \\
--output-repo username/vlm-test
# Full training with Trackio monitoring
uv run vlm-streaming-sft-unsloth.py \\
--max-steps 500 \\
--output-repo username/vlm-finetuned \\
--trackio-space username/trackio
# Custom dataset and model
uv run vlm-streaming-sft-unsloth.py \\
--base-model unsloth/Qwen3-VL-8B-Instruct-unsloth-bnb-4bit \\
--dataset your-username/your-vlm-dataset \\
--max-steps 1000 \\
--output-repo username/custom-vlm
""",
)
# Model and data
parser.add_argument(
"--base-model",
default="unsloth/Qwen3-VL-8B-Instruct-unsloth-bnb-4bit",
help="Base VLM model (default: unsloth/Qwen3-VL-8B-Instruct-unsloth-bnb-4bit)",
)
parser.add_argument(
"--dataset",
default="davanstrien/iconclass-vlm-sft",
help="Dataset with 'images' and 'messages' columns (default: davanstrien/iconclass-vlm-sft)",
)
parser.add_argument(
"--output-repo",
required=True,
help="HF Hub repo to push model to (e.g., 'username/vlm-finetuned')",
)
# Training config
parser.add_argument(
"--num-epochs",
type=float,
default=None,
help="Number of epochs (default: None). Use instead of --max-steps for non-streaming mode.",
)
parser.add_argument(
"--max-steps",
type=int,
default=None,
help="Training steps (default: None). Required for streaming mode, optional otherwise.",
)
parser.add_argument(
"--batch-size",
type=int,
default=2,
help="Per-device batch size (default: 2)",
)
parser.add_argument(
"--gradient-accumulation",
type=int,
default=4,
help="Gradient accumulation steps (default: 4). Effective batch = batch-size * this",
)
parser.add_argument(
"--learning-rate",
type=float,
default=2e-4,
help="Learning rate (default: 2e-4)",
)
parser.add_argument(
"--max-seq-length",
type=int,
default=2048,
help="Maximum sequence length (default: 2048)",
)
# LoRA config
parser.add_argument(
"--lora-r",
type=int,
default=16,
help="LoRA rank (default: 16). Higher = more capacity but more VRAM",
)
parser.add_argument(
"--lora-alpha",
type=int,
default=16,
help="LoRA alpha (default: 16). Same as r per Unsloth notebook",
)
# Output
parser.add_argument(
"--save-local",
default="vlm-streaming-output",
help="Local directory to save model (default: vlm-streaming-output)",
)
# Evaluation and data control
parser.add_argument(
"--eval-split",
type=float,
default=0.0,
help="Fraction of data for evaluation (0.0-0.5). Default: 0.0 (no eval)",
)
parser.add_argument(
"--num-samples",
type=int,
default=None,
help="Limit samples (default: None = use all for non-streaming, 500 for streaming)",
)
parser.add_argument(
"--seed",
type=int,
default=3407,
help="Random seed for reproducibility (default: 3407)",
)
parser.add_argument(
"--streaming",
action="store_true",
default=False,
help="Use streaming mode (default: False). Use for very large datasets.",
)
return parser.parse_args()
def main():
args = parse_args()
# Validate epochs/steps configuration
if args.streaming and args.num_epochs:
logger.error(
"Cannot use --num-epochs with --streaming. Use --max-steps instead."
)
sys.exit(1)
if args.streaming and not args.max_steps:
args.max_steps = 500 # Default for streaming
logger.info("Using default --max-steps=500 for streaming mode")
if not args.streaming and not args.num_epochs and not args.max_steps:
args.num_epochs = 1 # Default to 1 epoch for non-streaming
logger.info("Using default --num-epochs=1 for non-streaming mode")
# Determine training duration display
if args.num_epochs:
duration_str = f"{args.num_epochs} epoch(s)"
else:
duration_str = f"{args.max_steps} steps"
print("=" * 70)
print("VLM Fine-tuning with Unsloth")
print("=" * 70)
print("\nConfiguration:")
print(f" Base model: {args.base_model}")
print(f" Dataset: {args.dataset}")
print(f" Streaming: {args.streaming}")
print(
f" Num samples: {args.num_samples or ('500' if args.streaming else 'all')}"
)
print(
f" Eval split: {args.eval_split if args.eval_split > 0 else '(disabled)'}"
)
print(f" Seed: {args.seed}")
print(f" Training: {duration_str}")
print(
f" Batch size: {args.batch_size} x {args.gradient_accumulation} = {args.batch_size * args.gradient_accumulation}"
)
print(f" Learning rate: {args.learning_rate}")
print(f" LoRA rank: {args.lora_r}")
print(f" Output repo: {args.output_repo}")
print()
# Check CUDA before heavy imports
check_cuda()
# Enable fast transfers
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
# Import heavy dependencies (note: import from unsloth.trainer for VLM)
from unsloth import FastVisionModel
from unsloth.trainer import UnslothVisionDataCollator
from datasets import load_dataset
from trl import SFTTrainer, SFTConfig
from huggingface_hub import login
# Login to Hub
token = os.environ.get("HF_TOKEN")
if token:
login(token=token)
logger.info("Logged in to Hugging Face Hub")
else:
logger.warning("HF_TOKEN not set - model upload may fail")
# 1. Load model (Qwen returns tokenizer, not processor)
print("\n[1/5] Loading model...")
start = time.time()
model, tokenizer = FastVisionModel.from_pretrained(
args.base_model,
load_in_4bit=True,
use_gradient_checkpointing="unsloth",
)
model = FastVisionModel.get_peft_model(
model,
finetune_vision_layers=True,
finetune_language_layers=True,
finetune_attention_modules=True,
finetune_mlp_modules=True,
r=args.lora_r,
lora_alpha=args.lora_alpha,
lora_dropout=0,
bias="none",
random_state=3407,
use_rslora=False,
loftq_config=None,
)
print(f"Model loaded in {time.time() - start:.1f}s")
# 2. Load dataset (streaming or non-streaming)
print(
f"\n[2/5] Loading dataset ({'streaming' if args.streaming else 'non-streaming'})..."
)
start = time.time()
if args.streaming:
# Streaming mode: take limited samples
dataset = load_dataset(args.dataset, split="train", streaming=True)
num_samples = args.num_samples or 500
# Peek at first sample to show info
sample = next(iter(dataset))
if "messages" in sample:
print(f" Sample has {len(sample['messages'])} messages")
if "images" in sample:
img_count = (
len(sample["images"]) if isinstance(sample["images"], list) else 1
)
print(f" Sample has {img_count} image(s)")
# Reload and take samples
dataset = load_dataset(args.dataset, split="train", streaming=True)
all_data = list(dataset.take(num_samples))
print(f" Loaded {len(all_data)} samples in {time.time() - start:.1f}s")
if args.eval_split > 0:
# Manual shuffle for streaming (no built-in split)
import random
random.seed(args.seed)
random.shuffle(all_data)
split_idx = int(len(all_data) * (1 - args.eval_split))
train_data = all_data[:split_idx]
eval_data = all_data[split_idx:]
print(f" Train: {len(train_data)} samples, Eval: {len(eval_data)} samples")
else:
train_data = all_data
eval_data = None
else:
# Non-streaming: use proper train_test_split
dataset = load_dataset(args.dataset, split="train")
print(f" Dataset has {len(dataset)} total samples")
# Peek at first sample
sample = dataset[0]
if "messages" in sample:
print(f" Sample has {len(sample['messages'])} messages")
if "images" in sample:
img_count = (
len(sample["images"]) if isinstance(sample["images"], list) else 1
)
print(f" Sample has {img_count} image(s)")
if args.num_samples:
dataset = dataset.select(range(min(args.num_samples, len(dataset))))
print(f" Limited to {len(dataset)} samples")
if args.eval_split > 0:
split = dataset.train_test_split(test_size=args.eval_split, seed=args.seed)
train_data = list(split["train"])
eval_data = list(split["test"])
print(f" Train: {len(train_data)} samples, Eval: {len(eval_data)} samples")
else:
train_data = list(dataset)
eval_data = None
print(f" Dataset ready in {time.time() - start:.1f}s")
# 3. Configure trainer
print("\n[3/5] Configuring trainer...")
# Enable training mode
FastVisionModel.for_training(model)
# Calculate steps per epoch for logging/eval intervals
effective_batch = args.batch_size * args.gradient_accumulation
steps_per_epoch = len(train_data) // effective_batch
# Determine run name and logging steps
if args.num_epochs:
run_name = f"vlm-sft-{args.num_epochs}ep"
logging_steps = max(1, steps_per_epoch // 10) # ~10 logs per epoch
else:
run_name = f"vlm-sft-{args.max_steps}steps"
logging_steps = max(1, args.max_steps // 20)
training_config = SFTConfig(
output_dir=args.save_local,
per_device_train_batch_size=args.batch_size,
gradient_accumulation_steps=args.gradient_accumulation,
warmup_steps=5, # Per notebook (not warmup_ratio)
num_train_epochs=args.num_epochs if args.num_epochs else 1,
max_steps=args.max_steps if args.max_steps else -1, # -1 means use epochs
learning_rate=args.learning_rate,
logging_steps=logging_steps,
optim="adamw_8bit", # Per notebook
weight_decay=0.001,
lr_scheduler_type="cosine" if args.num_epochs else "linear",
seed=args.seed,
# VLM-specific settings (required for Unsloth)
remove_unused_columns=False,
dataset_text_field="",
dataset_kwargs={"skip_prepare_dataset": True},
max_length=args.max_seq_length,
# Logging disabled for testing
report_to="none",
run_name=run_name,
)
# Add evaluation config if eval is enabled
if eval_data:
if args.num_epochs:
# For epoch-based training, eval at end of each epoch
training_config.eval_strategy = "epoch"
print(" Evaluation enabled: every epoch")
else:
training_config.eval_strategy = "steps"
training_config.eval_steps = max(1, args.max_steps // 5)
print(f" Evaluation enabled: every {training_config.eval_steps} steps")
# Use older 'tokenizer=' parameter (not processing_class) - required for Unsloth VLM
trainer = SFTTrainer(
model=model,
tokenizer=tokenizer, # Full processor, not processor.tokenizer
data_collator=UnslothVisionDataCollator(model, tokenizer),
train_dataset=train_data,
eval_dataset=eval_data, # None if no eval
args=training_config,
)
# 4. Train
print(f"\n[4/5] Training for {duration_str}...")
if args.num_epochs:
print(
f" (~{steps_per_epoch} steps/epoch, {int(steps_per_epoch * args.num_epochs)} total steps)"
)
start = time.time()
train_result = trainer.train()
train_time = time.time() - start
total_steps = train_result.metrics.get(
"train_steps", args.max_steps or steps_per_epoch * args.num_epochs
)
print(f"\nTraining completed in {train_time / 60:.1f} minutes")
print(f" Speed: {total_steps / train_time:.2f} steps/s")
# Print training metrics
if train_result.metrics:
train_loss = train_result.metrics.get("train_loss")
if train_loss:
print(f" Final train loss: {train_loss:.4f}")
# Print eval results if eval was enabled
if eval_data:
print("\nRunning final evaluation...")
eval_results = trainer.evaluate()
eval_loss = eval_results.get("eval_loss")
if eval_loss:
print(f" Final eval loss: {eval_loss:.4f}")
if train_loss:
ratio = eval_loss / train_loss
if ratio > 1.5:
print(
f" ⚠️ Eval loss is {ratio:.1f}x train loss - possible overfitting"
)
else:
print(
f" ✓ Eval/train ratio: {ratio:.2f} - model generalizes well"
)
# 5. Save and push
print("\n[5/5] Saving model...")
# Save locally
model.save_pretrained(args.save_local)
tokenizer.save_pretrained(args.save_local)
print(f"Saved locally to {args.save_local}/")
# Push to Hub
print(f"\nPushing to {args.output_repo}...")
model.push_to_hub(args.output_repo, tokenizer=tokenizer)
print(f"Model available at: https://huggingface.co/{args.output_repo}")
print("\n" + "=" * 70)
print("Done!")
print("=" * 70)
if __name__ == "__main__":
# Show example usage if no arguments
if len(sys.argv) == 1:
print("=" * 70)
print("VLM Fine-tuning with Unsloth")
print("=" * 70)
print("\nFine-tune Vision-Language Models with optional train/eval split.")
print("\nFeatures:")
print(" - ~60% less VRAM with Unsloth optimizations")
print(" - 2x faster training vs standard methods")
print(" - Epoch-based or step-based training")
print(" - Optional evaluation to detect overfitting")
print(" - Trackio integration for monitoring")
print("\nEpoch-based training (recommended for full datasets):")
print("\n uv run vlm-streaming-sft-unsloth-qwen.py \\")
print(" --num-epochs 1 \\")
print(" --eval-split 0.2 \\")
print(" --output-repo your-username/vlm-finetuned")
print("\nHF Jobs example (1 epoch with eval):")
print(
"\n hf jobs uv run --flavor a100-large --secrets HF_TOKEN --timeout 4h -- \\"
)
print(
" https://huggingface.co/datasets/uv-scripts/training/raw/main/vlm-streaming-sft-unsloth-qwen.py \\"
)
print(" --num-epochs 1 \\")
print(" --eval-split 0.2 \\")
print(" --output-repo your-username/vlm-finetuned")
print("\nStep-based training (for streaming or quick tests):")
print("\n uv run vlm-streaming-sft-unsloth-qwen.py \\")
print(" --streaming \\")
print(" --max-steps 500 \\")
print(" --output-repo your-username/vlm-finetuned")
print("\nFor full help: uv run vlm-streaming-sft-unsloth-qwen.py --help")
print("=" * 70)
sys.exit(0)
main()
|