| { | |
| "cells": [ | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "# CA4: Fine-tuning PaliGemma on CLEVR-COGEN-A\n", | |
| "\n", | |
| "This notebook trains a PaliGemma-3B vision-language model on the CLEVR-COGEN-A counting task using LoRA + 8-bit quantization. The flow follows the course rules: overview \u2192 config (imports, seeds, hyperparameters) \u2192 data \u2192 model \u2192 training/evaluation \u2192 qualitative samples." | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "metadata": {}, | |
| "execution_count": null, | |
| "outputs": [], | |
| "source": [ | |
| "import os\n", | |
| "import random\n", | |
| "import json\n", | |
| "import logging\n", | |
| "from dataclasses import dataclass\n", | |
| "from typing import Any, Dict, List\n", | |
| "\n", | |
| "import numpy as np\n", | |
| "import torch\n", | |
| "from datasets import load_dataset\n", | |
| "from peft import LoraConfig, get_peft_model\n", | |
| "from transformers import (\n", | |
| " BitsAndBytesConfig,\n", | |
| " PaliGemmaForConditionalGeneration,\n", | |
| " PaliGemmaProcessor,\n", | |
| " Trainer,\n", | |
| " TrainingArguments,\n", | |
| ")\n", | |
| "import evaluate\n", | |
| "\n", | |
| "# Logging and determinism\n", | |
| "logging.basicConfig(level=logging.INFO)\n", | |
| "logger = logging.getLogger(__name__)\n", | |
| "SEED = 42\n", | |
| "random.seed(SEED)\n", | |
| "np.random.seed(SEED)\n", | |
| "torch.manual_seed(SEED)\n", | |
| "if torch.cuda.is_available():\n", | |
| " torch.cuda.manual_seed_all(SEED)\n", | |
| " torch.backends.cudnn.deterministic = True\n", | |
| " torch.backends.cudnn.benchmark = False\n", | |
| "\n", | |
| "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", | |
| "logger.info(f\"Device: {device}\")\n", | |
| "\n", | |
| "# Centralized configuration\n", | |
| "config = {\n", | |
| " \"model_id\": os.getenv(\"MODEL_ID\", \"google/paligemma-3b-mix-224\"),\n", | |
| " \"dataset_split\": \"train[:20%]\", # 20% subset per assignment\n", | |
| " \"test_size\": 0.1,\n", | |
| " \"max_length\": 300,\n", | |
| " \"train_batch_size\": 4,\n", | |
| " \"eval_batch_size\": 4,\n", | |
| " \"grad_accum\": 4,\n", | |
| " \"learning_rate\": 1e-4,\n", | |
| " \"num_epochs\": 1,\n", | |
| " \"eval_steps\": 100,\n", | |
| " \"save_steps\": 100,\n", | |
| " \"logging_steps\": 10,\n", | |
| " \"lora_rank\": 64,\n", | |
| " \"lora_alpha\": 64,\n", | |
| " \"lora_dropout\": 0.05,\n", | |
| " \"output_dir\": \"./paligemma-clevr-finetuned\",\n", | |
| "}\n", | |
| "\n", | |
| "# Optional smoke test: set MAX_STEPS env var (e.g., 20) to cap training\n", | |
| "SMOKE_MAX_STEPS = os.getenv(\"MAX_STEPS\")\n", | |
| "MAX_STEPS = int(SMOKE_MAX_STEPS) if SMOKE_MAX_STEPS else -1\n", | |
| "RUN_TRAINING = os.getenv(\"RUN_TRAINING\", \"false\").lower() in {\"1\", \"true\", \"yes\"}\n", | |
| "logger.info(f\"Run training: {RUN_TRAINING}; max_steps={MAX_STEPS}\")\n" | |
| ] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "## Data Loading and Preprocessing\n", | |
| "\n", | |
| "Loads the CLEVR-COGEN-A subset, applies a 90/10 train/validation split, and prepares inputs for PaliGemma. Text prompts are prefixed with `<image>` as required by the processor. Padding tokens are masked with `-100` so they are ignored in the loss." | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "metadata": {}, | |
| "execution_count": null, | |
| "outputs": [], | |
| "source": [ | |
| "# Load dataset (20% subset) and split\n", | |
| "raw_dataset = load_dataset(\"leonardPKU/clevr_cogen_a_train\", split=config[\"dataset_split\"])\n", | |
| "split_datasets = raw_dataset.train_test_split(test_size=config[\"test_size\"], seed=SEED)\n", | |
| "train_dataset = split_datasets[\"train\"]\n", | |
| "val_dataset = split_datasets[\"test\"]\n", | |
| "logger.info(f\"Train samples: {len(train_dataset)} | Val samples: {len(val_dataset)}\")\n", | |
| "\n", | |
| "# Processor\n", | |
| "processor = PaliGemmaProcessor.from_pretrained(config[\"model_id\"])\n", | |
| "\n", | |
| "\n", | |
| "def preprocess_function(batch: Dict[str, Any]) -> Dict[str, Any]:\n", | |
| " questions = batch[\"problem\"]\n", | |
| " images = batch[\"image\"]\n", | |
| " answers = batch[\"solution\"]\n", | |
| "\n", | |
| " processed_images = []\n", | |
| " prompts = []\n", | |
| " targets = []\n", | |
| " for q, img, ans in zip(questions, images, answers):\n", | |
| " try:\n", | |
| " img = img.convert(\"RGB\").resize((224, 224))\n", | |
| " processed_images.append(img)\n", | |
| " prompts.append(f\"<image> {q}\")\n", | |
| " targets.append(str(ans))\n", | |
| " except Exception as exc: # skip invalid samples\n", | |
| " logger.warning(\"Skipping sample due to image issue: %s\", exc)\n", | |
| "\n", | |
| " if not processed_images:\n", | |
| " return {}\n", | |
| "\n", | |
| " encoder_inputs = processor(\n", | |
| " images=processed_images,\n", | |
| " text=prompts,\n", | |
| " padding=\"max_length\",\n", | |
| " truncation=True,\n", | |
| " max_length=config[\"max_length\"],\n", | |
| " return_tensors=\"pt\",\n", | |
| " )\n", | |
| "\n", | |
| " decoder_inputs = processor.tokenizer(\n", | |
| " text_target=targets,\n", | |
| " padding=\"max_length\",\n", | |
| " truncation=True,\n", | |
| " max_length=config[\"max_length\"],\n", | |
| " return_tensors=\"pt\",\n", | |
| " )\n", | |
| "\n", | |
| " labels = decoder_inputs[\"input_ids\"].clone()\n", | |
| " labels[decoder_inputs[\"attention_mask\"] == 0] = -100\n", | |
| " encoder_inputs[\"labels\"] = labels\n", | |
| " return encoder_inputs\n", | |
| "\n", | |
| "\n", | |
| "processed_train_dataset = train_dataset.map(\n", | |
| " preprocess_function, batched=True, remove_columns=train_dataset.column_names\n", | |
| ")\n", | |
| "processed_val_dataset = val_dataset.map(\n", | |
| " preprocess_function, batched=True, remove_columns=val_dataset.column_names\n", | |
| ")\n", | |
| "\n", | |
| "processed_train_dataset.set_format(type=\"torch\")\n", | |
| "processed_val_dataset.set_format(type=\"torch\")\n", | |
| "logger.info(\"Preprocessing complete\")\n" | |
| ] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "## Model, Quantization, and LoRA Configuration\n", | |
| "\n", | |
| "Loads the PaliGemma model with 8-bit quantization (BitsAndBytes) and applies LoRA adapters to attention and MLP projections. Only ~3% of parameters are trainable." | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "metadata": {}, | |
| "execution_count": null, | |
| "outputs": [], | |
| "source": [ | |
| "bnb_config = BitsAndBytesConfig(\n", | |
| " load_in_8bit=True,\n", | |
| " llm_int8_threshold=6.0,\n", | |
| ")\n", | |
| "\n", | |
| "model = PaliGemmaForConditionalGeneration.from_pretrained(\n", | |
| " config[\"model_id\"],\n", | |
| " device_map=\"auto\",\n", | |
| " quantization_config=bnb_config,\n", | |
| ")\n", | |
| "\n", | |
| "lora_config = LoraConfig(\n", | |
| " r=config[\"lora_rank\"],\n", | |
| " lora_alpha=config[\"lora_alpha\"],\n", | |
| " lora_dropout=config[\"lora_dropout\"],\n", | |
| " target_modules=[\n", | |
| " \"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\",\n", | |
| " \"gate_proj\", \"up_proj\", \"down_proj\",\n", | |
| " ],\n", | |
| " task_type=\"CAUSAL_LM\",\n", | |
| ")\n", | |
| "\n", | |
| "model = get_peft_model(model, lora_config)\n", | |
| "model.config.use_cache = False # required for training with gradient checkpointing if enabled\n", | |
| "\n", | |
| "# Parameter stats\n", | |
| "trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", | |
| "total = sum(p.numel() for p in model.parameters())\n", | |
| "logger.info(f\"Trainable params: {trainable/1e6:.1f}M ({100*trainable/total:.2f}%)\")\n" | |
| ] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "## Training Configuration and Metrics\n", | |
| "\n", | |
| "Defines Trainer setup, ROUGE metrics, and optional smoke-test knob via `MAX_STEPS`. Set `RUN_TRAINING=True` (env var) to execute full training." | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "metadata": {}, | |
| "execution_count": null, | |
| "outputs": [], | |
| "source": [ | |
| "rouge = evaluate.load(\"rouge\")\n", | |
| "\n", | |
| "def compute_metrics(eval_pred):\n", | |
| " predictions, labels = eval_pred\n", | |
| " labels = np.where(labels != -100, labels, processor.tokenizer.pad_token_id)\n", | |
| " decoded_preds = processor.batch_decode(predictions, skip_special_tokens=True)\n", | |
| " decoded_labels = processor.batch_decode(labels, skip_special_tokens=True)\n", | |
| " scores = rouge.compute(predictions=decoded_preds, references=decoded_labels)\n", | |
| " return {\n", | |
| " \"rouge1\": scores[\"rouge1\"],\n", | |
| " \"rouge2\": scores[\"rouge2\"],\n", | |
| " \"rougeL\": scores[\"rougeL\"],\n", | |
| " }\n", | |
| "\n", | |
| "training_args = TrainingArguments(\n", | |
| " output_dir=config[\"output_dir\"],\n", | |
| " num_train_epochs=config[\"num_epochs\"],\n", | |
| " per_device_train_batch_size=config[\"train_batch_size\"],\n", | |
| " per_device_eval_batch_size=config[\"eval_batch_size\"],\n", | |
| " gradient_accumulation_steps=config[\"grad_accum\"],\n", | |
| " evaluation_strategy=\"steps\",\n", | |
| " eval_steps=config[\"eval_steps\"],\n", | |
| " save_strategy=\"steps\",\n", | |
| " save_steps=config[\"save_steps\"],\n", | |
| " logging_steps=config[\"logging_steps\"],\n", | |
| " learning_rate=config[\"learning_rate\"],\n", | |
| " load_best_model_at_end=True,\n", | |
| " metric_for_best_model=\"eval_loss\",\n", | |
| " report_to=\"none\",\n", | |
| " remove_unused_columns=False,\n", | |
| " fp16=torch.cuda.is_available(),\n", | |
| " max_steps=MAX_STEPS,\n", | |
| ")\n", | |
| "\n", | |
| "trainer = Trainer(\n", | |
| " model=model,\n", | |
| " args=training_args,\n", | |
| " train_dataset=processed_train_dataset,\n", | |
| " eval_dataset=processed_val_dataset,\n", | |
| " tokenizer=processor.tokenizer,\n", | |
| " compute_metrics=compute_metrics,\n", | |
| ")\n" | |
| ] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "## Run Training / Evaluation\n", | |
| "\n", | |
| "Set `RUN_TRAINING=True` (environment variable) for a full run. For a quick smoke test, set `MAX_STEPS` (e.g., 20)." | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "metadata": {}, | |
| "execution_count": null, | |
| "outputs": [], | |
| "source": [ | |
| "if RUN_TRAINING:\n", | |
| " logger.info(\"Starting training...\")\n", | |
| " train_result = trainer.train()\n", | |
| " trainer.save_model(config[\"output_dir\"])\n", | |
| " metrics = trainer.evaluate()\n", | |
| " logger.info(\"Eval metrics: %s\", json.dumps(metrics, indent=2))\n", | |
| "else:\n", | |
| " logger.info(\"Training skipped. Set RUN_TRAINING=True to train. For smoke tests set MAX_STEPS.\")\n" | |
| ] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "## Qualitative Check\n", | |
| "\n", | |
| "Utility to generate a prediction for one validation sample." | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "metadata": {}, | |
| "execution_count": null, | |
| "outputs": [], | |
| "source": [ | |
| "def generate_answer(sample_id: int = 0) -> Dict[str, str]:\n", | |
| " sample = val_dataset[sample_id]\n", | |
| " image = sample[\"image\"].convert(\"RGB\").resize((224, 224))\n", | |
| " prompt = f\"<image> {sample['problem']}\"\n", | |
| " inputs = processor(text=prompt, images=image, return_tensors=\"pt\").to(device)\n", | |
| " with torch.inference_mode():\n", | |
| " outputs = model.generate(**inputs, max_new_tokens=10)\n", | |
| " prediction = processor.batch_decode(outputs, skip_special_tokens=True)[0]\n", | |
| " return {\n", | |
| " \"question\": sample[\"problem\"],\n", | |
| " \"ground_truth\": str(sample[\"solution\"]),\n", | |
| " \"prediction\": prediction,\n", | |
| " }\n", | |
| "\n", | |
| "# Example usage (uncomment to run after training)\n", | |
| "# generate_answer(0)\n" | |
| ] | |
| } | |
| ], | |
| "metadata": { | |
| "kernelspec": { | |
| "display_name": "Python 3", | |
| "language": "python", | |
| "name": "python3" | |
| }, | |
| "language_info": { | |
| "name": "python", | |
| "version": "3.10" | |
| } | |
| }, | |
| "nbformat": 4, | |
| "nbformat_minor": 5 | |
| } |
Xet Storage Details
- Size:
- 13.3 kB
- Xet hash:
- 748696fb5d4ba8c29404fbd9a641d762ead3b937d33d94c8f4c141136d5b0e28
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.