Datasets:
Tags:
Not-For-All-Audiences
Upload gemma4_heretic_vlm.ipynb
Browse files- gemma4_heretic_vlm.ipynb +1 -1
gemma4_heretic_vlm.ipynb
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
{"cells":[{"cell_type":"code","execution_count":null,"metadata":{"id":"pb9bxY0OE81H"},"outputs":[],"source":["from google.colab import drive\n","drive.mount('/content/drive')"]},{"cell_type":"code","source":["#@markdown # Cell 1a: REVISED β Install + CORRECT Direct GPU Load (No Quantization, Exact Model Card)\n","\n","!pip install -q --upgrade --force-reinstall \"pillow<12.0\"\n","!pip install -q --upgrade transformers accelerate bitsandbytes\n","\n","import torch\n","from transformers import AutoProcessor, AutoModelForMultimodalLM\n","from google.colab import userdata\n","import os\n","\n","# Get HF token from secrets\n","hf_token = userdata.get('HF_TOKEN')\n","if not hf_token:\n"," print(\"β οΈ Please add HF_TOKEN to Colab secrets (key icon on the left sidebar)\")\n","\n","# Model ID\n","model_id = \"coder3101/gemma-4-E2B-it-heretic\"\n","\n","print(f\"π½ Loading Gemma-4-E2B-Heretic **EXACTLY** as recommended on model card...\")\n","\n","processor = AutoProcessor.from_pretrained(model_id, token=hf_token)\n","\n","# βββ THIS IS THE OFFICIAL RECOMMENDED LOADING (fixes vision hangs + gray-image bug)\n","model = AutoModelForMultimodalLM.from_pretrained(\n"," model_id,\n"," token=hf_token,\n"," dtype=\"auto\", # β model card uses \"dtype\" (not torch_dtype)\n"," device_map=\"auto\", # β automatically puts vision + text on GPU\n"," low_cpu_mem_usage=True,\n",")\n","\n","print(\"β
Model loaded DIRECTLY to GPU (vision encoder fully initialized)\")\n","print(f\" Device: {model.device}\")\n","print(f\" Dtype: {model.dtype}\")\n","print(f\" VRAM used: {torch.cuda.memory_allocated() / 1024**3:.2f} GB\")\n","print(\" Ready for Cell 1b (clear) and Cell 2 (captions). No more hangs expected.\")"],"metadata":{"cellView":"form","id":"c7TmhIAuAE6M"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@markdown # Cell 1b: REVISED β Clean VRAM & Confirm GPU Load\n","\n","import torch\n","import gc\n","\n","# Clear any leftover from previous broken loads\n","torch.cuda.empty_cache()\n","gc.collect()\n","\n","print(\"π§Ή VRAM fully cleared.\")\n","\n","# Re-confirm the model is still on GPU (safety check)\n","print(f\"β
Current model device: {model.device}\")\n","print(f\" VRAM allocated: {torch.cuda.memory_allocated() / 1024**3:.2f} GB\")\n","print(f\" GPU: {torch.cuda.get_device_name(0)}\")\n","print(\"\\nβ
Model is ready for Cell 3 debug / Cell 2 captions.\")\n","print(\" Vision tower is now correctly loaded β the previous hanging should be fixed.\")"],"metadata":{"cellView":"form","id":"pUrpfegeAG8v"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@markdown # Cell 2: Upload Images β Generate Accurate Captions β Download ZIP\n","\n","from google.colab import files\n","import zipfile\n","import os\n","from PIL import Image\n","\n","output_dir = \"/content/image_text_pairs\"\n","os.makedirs(output_dir, exist_ok=True)\n","\n","print(\"π€ Upload your image(s) (multiple files allowed)\")\n","uploaded = files.upload()\n","\n","prompt_style = \"Describe this image in detail, including key objects, scene, colors, mood, lighting, and any visible text. Be accurate and comprehensive. you may not use newline or **bold font**. You may not itemize. I want a single block of text , 400 words long. \" #@param {type:\"string\"}\n","\n","generated_count = 0\n","\n","for filename in list(uploaded.keys()):\n"," if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.bmp')):\n"," image_path = f\"/content/{filename}\"\n"," image = Image.open(image_path).convert(\"RGB\")\n","\n"," # Use local file path (fastest + most reliable for this processor)\n"," messages = [\n"," {\n"," \"role\": \"user\",\n"," \"content\": [\n"," {\"type\": \"image\", \"url\": image_path},\n"," {\"type\": \"text\", \"text\": prompt_style}\n"," ]\n"," }\n"," ]\n","\n"," inputs = processor.apply_chat_template(\n"," messages,\n"," add_generation_prompt=True,\n"," tokenize=True,\n"," return_tensors=\"pt\",\n"," return_dict=True\n"," ).to(model.device)\n","\n"," print(f\"πΈ Processing {filename} β generating caption...\")\n","\n"," with torch.no_grad():\n"," outputs = model.generate(\n"," **inputs,\n"," max_new_tokens=512,\n"," do_sample=True,\n"," temperature=0.7,\n"," top_p=0.9,\n"," )\n","\n"," # Decode and clean output (Gemma 4 returns structured dict)\n"," input_len = inputs[\"input_ids\"].shape[-1]\n"," raw = processor.decode(outputs[0][input_len:], skip_special_tokens=False)\n"," parsed = processor.parse_response(raw) if hasattr(processor, \"parse_response\") else raw.strip()\n","\n"," # Extract just the text content\n"," caption = parsed[\"content\"] if isinstance(parsed, dict) and \"content\" in parsed else str(parsed)\n","\n"," print(f\" β
Caption for {filename} ready\\n\")\n","\n"," # Save image + text pair\n"," base_name = os.path.splitext(filename)[0]\n"," with open(os.path.join(output_dir, f\"{base_name}.txt\"), \"w\", encoding=\"utf-8\") as f:\n"," f.write(caption)\n"," image.save(os.path.join(output_dir, filename))\n"," generated_count += 1\n","\n","# Create ZIP and download\n","zip_path = \"/content/image_text_pairs.zip\"\n","with zipfile.ZipFile(zip_path, 'w') as zipf:\n"," for root, _, files_list in os.walk(output_dir):\n"," for file in files_list:\n"," file_path = os.path.join(root, file)\n"," zipf.write(file_path, os.path.relpath(file_path, output_dir))\n","\n","print(f\"\\nπ Done! Generated {generated_count} accurate image-text pairs.\")\n","files.download(zip_path)"],"metadata":{"cellView":"form","id":"SnsYbQqkAUiP"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@title Cell 3: UPDATED β Talk to the LLM + ask it to caption images (Latest-Reply + Image Display Options)\n","\n","import json\n","import os\n","import torch\n","from google.colab import files\n","from IPython.display import Image, display # β Added for small image display\n","\n","#@markdown\n","# ==================== CHAT PARAMETERS ====================\n","user_message = \"Describe this image in detail, including key objects, scene, colors, mood, lighting, and any visible text. Be accurate and comprehensive. you may not use newline or **bold font**. You may not itemize. I want a single block of text , 400 words long. \" #@param {type:\"string\"}\n","attach_image = True #@param {type:\"boolean\"}\n","# β Check this ONLY when you want to upload a NEW image\n","reset_chat = False #@param {type:\"boolean\"}\n","only_show_latest_reply = True #@param {type:\"boolean\"}\n","# β NEW: When checked, the cell will ONLY show the latest LLM reply (instead of full history)\n","show_image_with_reply = True #@param {type:\"boolean\"}\n","# β NEW: When checked (and only_show_latest_reply is also checked), displays the currently loaded image as a small preview with the latest reply\n","# =======================================================\n","\n","chat_history_path = \"/content/chat_history.json\"\n","chat_log_path = \"/content/chat_log.txt\"\n","latest_image_file = \"/content/latest_image_path.txt\"\n","\n","# Safety check β model must be loaded from Cell 1a/1b\n","if 'model' not in globals() or 'processor' not in globals():\n"," print(\"β οΈ ERROR: Model or processor not found. Please run Cell 1a β Cell 1b first!\")\n","else:\n"," print(\"β
Model ready for multimodal chat.\")\n"," print(\"πΈ Latest-image mode ACTIVE + FULL HISTORY MODE:\")\n"," print(\" β Every query sends the ENTIRE chatlog (all previous user + LLM replies) + latest image + current text.\")\n","\n"," # Reset logic (includes latest image)\n"," if reset_chat:\n"," if os.path.exists(chat_history_path):\n"," os.remove(chat_history_path)\n"," if os.path.exists(chat_log_path):\n"," os.remove(chat_log_path)\n"," if os.path.exists(latest_image_file):\n"," os.remove(latest_image_file)\n"," print(\"ποΈ Chat history, log, and latest image have been completely reset.\")\n","\n"," # Load previous conversation (if not reset)\n"," if os.path.exists(chat_history_path) and not reset_chat:\n"," with open(chat_history_path, \"r\", encoding=\"utf-8\") as f:\n"," messages = json.load(f)\n"," print(f\" π Loaded full chat history ({len(messages)} messages) β will be sent to the LLM.\")\n"," else:\n"," messages = []\n"," print(\" π Starting fresh conversation.\")\n","\n"," # Load latest image path (persistent across cell runs)\n"," latest_image_path = None\n"," if os.path.exists(latest_image_file):\n"," with open(latest_image_file, \"r\", encoding=\"utf-8\") as f:\n"," latest_image_path = f.read().strip()\n"," if not os.path.exists(latest_image_path):\n"," latest_image_path = None\n","\n"," # Add new user message (if provided)\n"," image_path = None\n"," if user_message.strip():\n"," # === IMAGE HANDLING: upload new OR reuse latest ===\n"," if attach_image:\n"," print(\"π€ Upload the image to set as the NEW latest image...\")\n"," uploaded = files.upload()\n"," if uploaded:\n"," filename = next(iter(uploaded.keys()))\n"," if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.bmp')):\n"," image_path = f\"/content/{filename}\"\n"," latest_image_path = image_path\n"," with open(latest_image_file, \"w\", encoding=\"utf-8\") as f:\n"," f.write(image_path)\n"," print(f\" πΈ New latest image set: {filename}\")\n"," else:\n"," print(\"β οΈ Uploaded file is not an image β keeping previous latest image.\")\n","\n"," # Reuse latest image if no new upload\n"," if image_path is None and latest_image_path is not None:\n"," image_path = latest_image_path\n"," print(f\" πΈ Re-using latest image: {os.path.basename(image_path)}\")\n","\n"," # Build user content: image (if available) + text (always included)\n"," user_content = []\n"," if image_path is not None:\n"," user_content.append({\"type\": \"image\", \"url\": image_path})\n"," user_content.append({\"type\": \"text\", \"text\": user_message})\n","\n"," messages.append({\"role\": \"user\", \"content\": user_content})\n","\n"," print(f\"\\nπ€ You: {user_message}\")\n"," if image_path is not None:\n"," print(f\" πΈ (with latest image: {os.path.basename(image_path)})\")\n","\n"," # === KEY CHANGE: Full history (including all LLM replies) is always provided ===\n"," print(f\" π Sending FULL chat history ({len(messages)} total messages) to Gemma-4...\")\n","\n"," # Prepare inputs using the exact same chat template style as Cell 2\n"," inputs = processor.apply_chat_template(\n"," messages, # β Entire history (user + assistant turns) is passed here\n"," add_generation_prompt=True,\n"," tokenize=True,\n"," return_tensors=\"pt\",\n"," return_dict=True\n"," ).to(model.device)\n","\n"," print(\"π€ Generating response... (this may take a few seconds)\")\n","\n"," with torch.no_grad():\n"," outputs = model.generate(\n"," **inputs,\n"," max_new_tokens=512,\n"," do_sample=True,\n"," temperature=0.7,\n"," top_p=0.9,\n"," )\n","\n"," # Decode only the new tokens (same logic as Cell 2)\n"," input_len = inputs[\"input_ids\"].shape[-1]\n"," raw = processor.decode(outputs[0][input_len:], skip_special_tokens=False)\n","\n"," # Use the same parsing as Cell 2 (handles Gemma-4 structured output)\n"," if hasattr(processor, \"parse_response\"):\n"," parsed = processor.parse_response(raw)\n"," else:\n"," parsed = raw.strip()\n","\n"," reply = parsed[\"content\"] if isinstance(parsed, dict) and \"content\" in parsed else str(parsed)\n","\n"," # Add assistant reply to history (so next turn keeps the full conversation)\n"," assistant_content = [{\"type\": \"text\", \"text\": reply}]\n"," messages.append({\"role\": \"assistant\", \"content\": assistant_content})\n","\n"," # Print the LLM reply\n"," print(f\"\\nπ€ Gemma-4-Heretic: {reply}\\n\")\n","\n"," # Save structured history (JSON) for perfect persistence across runs\n"," with open(chat_history_path, \"w\", encoding=\"utf-8\") as f:\n"," json.dump(messages, f, ensure_ascii=False, indent=2)\n","\n"," # Rebuild human-readable chat log TXT (full conversation every time)\n"," with open(chat_log_path, \"w\", encoding=\"utf-8\") as f:\n"," for msg in messages:\n"," role = \"π€ You\" if msg[\"role\"] == \"user\" else \"π€ Gemma-4-Heretic\"\n"," content = msg.get(\"content\", [])\n"," text_part = \"\"\n"," image_info = \"\"\n","\n"," if isinstance(content, list):\n"," for item in content:\n"," if item.get(\"type\") == \"image\":\n"," url = item.get(\"url\", \"\")\n"," filename = os.path.basename(url) if url else \"unknown_image\"\n"," image_info = f\"[πΈ Latest image: {filename}] \"\n"," break\n"," text_part = next((item.get(\"text\", \"\") for item in content if item.get(\"type\") == \"text\"), \"\")\n"," else:\n"," text_part = str(content or \"\")\n","\n"," if image_info:\n"," text_part = image_info + (text_part if text_part else \"\")\n","\n"," f.write(f\"{role}:\\n{text_part}\\n\\n{'β' * 60}\\n\\n\")\n","\n"," print(f\"π Chat log updated β {chat_log_path}\")\n"," print(\" (You can download this TXT anytime from the file browser on the left)\")\n","\n"," # ==================== UPDATED DISPLAY LOGIC ====================\n"," print(\"\\n\" + \"=\"*80)\n","\n"," if only_show_latest_reply:\n"," print(\"π ONLY SHOWING LATEST REPLY (checkbox enabled)\")\n"," latest_reply = None\n"," for msg in reversed(messages):\n"," if msg[\"role\"] == \"assistant\":\n"," content = msg.get(\"content\", [])\n"," if isinstance(content, list):\n"," latest_reply = next((item.get(\"text\", \"\") for item in content if item.get(\"type\") == \"text\"), \"\")\n"," else:\n"," latest_reply = str(content or \"\")\n"," break\n","\n"," if latest_reply:\n"," print(\"π€ Latest Gemma-4-Heretic Reply:\")\n"," print(latest_reply)\n","\n"," if show_image_with_reply and latest_image_path and os.path.exists(latest_image_path):\n"," print(\"\\nπΈ Currently loaded image (attached to this reply):\")\n"," display(Image(filename=latest_image_path, width=400)) # small image preview\n"," print(\" (β Small image displayed above)\")\n"," elif show_image_with_reply:\n"," print(\" (No image currently loaded)\")\n"," else:\n"," print(\"π¬ No LLM reply yet in this conversation.\")\n","\n"," else:\n"," # Original full-history behavior (unchanged)\n"," if os.path.exists(chat_log_path):\n"," print(\"π FULL CHAT HISTORY (from chat_log.txt):\")\n"," with open(chat_log_path, \"r\", encoding=\"utf-8\") as f:\n"," print(f.read())\n"," elif not reset_chat:\n"," print(\"π¬ No messages yet. Type something in the box above and run the cell!\")\n","\n"," print(\"=\"*80)\n","\n"," print(\"\\nβ
Ready for next message!\")\n"," print(\" β The **entire chatlog** (all your messages + all Gemma-4 replies) is sent every time.\")\n"," print(\" β Latest uploaded image is automatically attached to every query.\")\n"," print(\" β Your text input is always sent together with the image.\")\n"," print(\" Check 'attach_image' only when you want to upload a different image.\")\n"," print(\" (Check 'Reset Chat' if you want to start a completely new conversation)\")\n"," print(\"\\n π NEW FEATURES:\")\n"," print(\" β Toggle 'only_show_latest_reply' to show ONLY the latest LLM reply (cleaner output).\")\n"," print(\" β Toggle 'show_image_with_reply' to display the currently loaded image as a small preview with the latest reply.\")"],"metadata":{"cellView":"form","id":"z30ARmSDYTJX"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["LoRa training"],"metadata":{"id":"m8W_d-1iRrr2"}},{"cell_type":"code","source":["import os\n","import zipfile\n","from pathlib import Path\n","import torch\n","import gc\n","from google.colab import files\n","from PIL import Image\n","from google.colab import drive\n","#@markdown Train LoRa on LLM using marching filenames in zip. In the txt files found in zip file , you can divide the Query and Reply desired with '//--//'\n","# ==================== MOUNT GOOGLE DRIVE FIRST ====================\n","print(\"π Checking Google Drive...\")\n","if not os.path.exists('/content/drive/MyDrive'):\n"," print(\"π Mounting Google Drive (this may ask for permission)...\")\n"," drive.mount('/content/drive', force_remount=False)\n","else:\n"," print(\"β
Google Drive already mounted.\")\n","\n","drive_adapter_path = \"/content/drive/MyDrive/gemma_lora_adapter\"\n","os.makedirs(drive_adapter_path, exist_ok=True)\n","print(f\"πΎ LoRA will be saved directly to: {drive_adapter_path}\")\n","\n","# ==================== TRAINING PARAMETERS ====================\n","zip_path = \"\" #@param {type:\"string\"}\n","upload_new_zip = True #@param {type:\"boolean\"}\n","num_epochs = 3 #@param {type:\"slider\", min:1, max:10, step:1}\n","lora_rank = 16 #@param {type:\"integer\"}\n","lora_alpha = 32 #@param {type:\"integer\"}\n","learning_rate = \"2e-4\" #@param {type:\"string\"}\n","batch_size = 1 #@param {type:\"integer\"}\n","gradient_accumulation_steps = 4 #@param {type:\"integer\"}\n","# ===========================================================\n","\n","# Install required packages for LoRA training\n","!pip install -q --upgrade peft trl\n","\n","# Get HF token (reuse from previous cells)\n","from google.colab import userdata\n","hf_token = userdata.get('HF_TOKEN')\n","if not hf_token:\n"," print(\"β οΈ Please add HF_TOKEN to Colab secrets first!\")\n","\n","# Model ID (same as Cell 1a)\n","model_id = \"coder3101/gemma-4-E2B-it-heretic\"\n","\n","# ====================== UNLOAD VRAM FIRST ======================\n","print(\"\\nπ§Ή Unloading VRAM prior to LoRA training...\")\n","torch.cuda.empty_cache()\n","gc.collect()\n","\n","reuse_model = False\n","if 'model' in globals() and 'processor' in globals():\n"," current_device = getattr(model, 'device', None)\n"," print(f\" Detected existing model on device: {current_device}\")\n"," if current_device is not None and current_device.type == 'cpu':\n"," print(\"β
Transformer model found on CPU β reusing existing model (no re-download from HF)\")\n"," reuse_model = True\n"," else:\n"," print(\"π Existing model detected (likely on GPU). Unloading to load efficient 4-bit version...\")\n"," del globals()['model']\n"," if 'processor' in globals():\n"," del globals()['processor']\n"," torch.cuda.empty_cache()\n"," gc.collect()\n","else:\n"," print(\"π No existing model found β will load from Hugging Face.\")\n","\n","# ====================== LOAD / REUSE MODEL ======================\n","print(\"\\nπ Preparing model for LoRA training...\")\n","\n","from transformers import BitsAndBytesConfig, TrainingArguments, Trainer\n","from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training\n","from trl import SFTTrainer # kept for future compatibility\n","\n","if reuse_model:\n"," # Reuse the CPU-loaded model (full precision)\n"," print(\" Reusing existing model + processor\")\n"," # Prepare for kbit training (works on already-loaded model)\n"," model = prepare_model_for_kbit_training(model)\n","else:\n"," # Standard 4-bit load (most common case)\n"," print(\" Loading model in 4-bit for efficient training...\")\n"," quant_config = BitsAndBytesConfig(\n"," load_in_4bit=True,\n"," bnb_4bit_quant_type=\"nf4\",\n"," bnb_4bit_compute_dtype=torch.bfloat16,\n"," bnb_4bit_use_double_quant=True,\n"," )\n","\n"," processor = AutoProcessor.from_pretrained(model_id, token=hf_token)\n","\n"," model = AutoModelForMultimodalLM.from_pretrained(\n"," model_id,\n"," token=hf_token,\n"," quantization_config=quant_config,\n"," device_map=\"auto\",\n"," low_cpu_mem_usage=True,\n"," )\n","\n"," model = prepare_model_for_kbit_training(model)\n","\n","# Apply LoRA (targets all linear layers β perfect for Gemma-4)\n","lora_config = LoraConfig(\n"," r=lora_rank,\n"," lora_alpha=lora_alpha,\n"," target_modules=\"all-linear\",\n"," lora_dropout=0.05,\n"," bias=\"none\",\n"," task_type=\"CAUSAL_LM\",\n",")\n","\n","model = get_peft_model(model, lora_config)\n","model.print_trainable_parameters()\n","\n","print(\"β
Model + LoRA adapter ready (VRAM optimized)\")\n","\n","# ====================== DATASET PREPARATION ======================\n","print(\"\\nπ¦ Preparing dataset from ZIP...\")\n","\n","# Handle ZIP upload or existing path\n","if upload_new_zip or not zip_path or not os.path.exists(zip_path):\n"," print(\"π€ Upload your image-text pairs ZIP file (must contain matching .jpg/.png + .txt files)\")\n"," uploaded = files.upload()\n"," if uploaded:\n"," zip_filename = list(uploaded.keys())[0]\n"," zip_path = f\"/content/{zip_filename}\"\n"," print(f\"β
Using uploaded file: {zip_filename}\")\n"," else:\n"," print(\"β No ZIP uploaded. Aborting.\")\n"," raise SystemExit\n","\n","if not os.path.exists(zip_path):\n"," print(f\"β ZIP file not found: {zip_path}\")\n"," raise SystemExit\n","\n","# Unpack ZIP\n","dataset_dir = \"/content/lora_training_data\"\n","os.makedirs(dataset_dir, exist_ok=True)\n","\n","with zipfile.ZipFile(zip_path, 'r') as z:\n"," z.extractall(dataset_dir)\n","\n","print(f\"β
Extracted dataset to {dataset_dir}\")\n","\n","# Find all matching image + txt pairs\n","image_exts = ('.png', '.jpg', '.jpeg', '.webp', '.bmp')\n","pairs = []\n","\n","for txt_file in Path(dataset_dir).glob(\"**/*.txt\"):\n"," base_name = txt_file.stem\n"," image_path = None\n"," for ext in image_exts:\n"," candidate = txt_file.with_name(base_name + ext)\n"," if candidate.exists():\n"," image_path = str(candidate)\n"," break\n"," if not image_path:\n"," continue\n","\n"," with open(txt_file, \"r\", encoding=\"utf-8\") as f:\n"," text_content = f.read().strip()\n","\n"," # Split into Query and Reply using '//--//'\n"," if '//--//' in text_content:\n"," query_part, reply_part = [x.strip() for x in text_content.split('//--//', 1)]\n"," else:\n"," query_part = \"Describe this image in detail, including key objects, scene, colors, mood, lighting, and any visible text. Be accurate and comprehensive.\"\n"," reply_part = text_content\n","\n"," pairs.append({\n"," \"image_path\": image_path,\n"," \"query\": query_part,\n"," \"reply\": reply_part\n"," })\n","\n","print(f\"β
Found {len(pairs)} valid image-text training pairs.\")\n","\n","if len(pairs) == 0:\n"," print(\"β No matching image+txt pairs found in the ZIP. Aborting.\")\n"," raise SystemExit\n","\n","# ====================== CUSTOM DATASET + COLLATOR ======================\n","class MultimodalTrainingDataset(torch.utils.data.Dataset):\n"," def __init__(self, pairs, processor):\n"," self.pairs = pairs\n"," self.processor = processor\n","\n"," def __len__(self):\n"," return len(self.pairs)\n","\n"," def __getitem__(self, idx):\n"," item = self.pairs[idx]\n"," messages = [\n"," {\"role\": \"user\", \"content\": [\n"," {\"type\": \"image\", \"url\": item[\"image_path\"]},\n"," {\"type\": \"text\", \"text\": item[\"query\"]}\n"," ]},\n"," {\"role\": \"assistant\", \"content\": [{\"type\": \"text\", \"text\": item[\"reply\"]}]}\n"," ]\n","\n"," inputs = self.processor.apply_chat_template(\n"," messages,\n"," add_generation_prompt=False,\n"," tokenize=True,\n"," return_tensors=\"pt\",\n"," return_dict=True\n"," )\n"," inputs[\"labels\"] = inputs[\"input_ids\"].clone()\n","\n"," # Remove batch dim\n"," for k in list(inputs.keys()):\n"," if isinstance(inputs[k], torch.Tensor):\n"," inputs[k] = inputs[k].squeeze(0)\n"," return inputs\n","\n","train_dataset = MultimodalTrainingDataset(pairs, processor)\n","\n","def multimodal_collator(features):\n"," batch = {}\n"," input_ids = [f[\"input_ids\"] for f in features]\n"," attention_mask = [f[\"attention_mask\"] for f in features]\n"," labels = [f[\"labels\"] for f in features]\n","\n"," text_padded = processor.tokenizer.pad(\n"," {\"input_ids\": input_ids, \"attention_mask\": attention_mask},\n"," padding=True,\n"," return_tensors=\"pt\"\n"," )\n"," batch[\"input_ids\"] = text_padded[\"input_ids\"]\n"," batch[\"attention_mask\"] = text_padded[\"attention_mask\"]\n","\n"," labels_padded = processor.tokenizer.pad(\n"," {\"input_ids\": labels},\n"," padding=True,\n"," return_tensors=\"pt\"\n"," )[\"input_ids\"]\n"," labels_padded[labels_padded == processor.tokenizer.pad_token_id] = -100\n"," batch[\"labels\"] = labels_padded\n","\n"," # Vision tensors (pixel_values etc.)\n"," first_item = features[0]\n"," for key in first_item.keys():\n"," if key in [\"input_ids\", \"attention_mask\", \"labels\"]:\n"," continue\n"," if isinstance(first_item[key], torch.Tensor):\n"," vals = [f[key] for f in features]\n"," batch[key] = torch.stack(vals) if vals[0].dim() == 3 else torch.cat(vals)\n","\n"," return batch\n","\n","# ====================== TRAINING ======================\n","print(f\"\\nπ Starting LoRA training on {len(pairs)} pairs for {num_epochs} epochs...\")\n","\n","training_args = TrainingArguments(\n"," output_dir=drive_adapter_path, # β Saved directly to Google Drive\n"," num_train_epochs=num_epochs,\n"," per_device_train_batch_size=batch_size,\n"," gradient_accumulation_steps=gradient_accumulation_steps,\n"," learning_rate=float(learning_rate),\n"," fp16=True,\n"," optim=\"paged_adamw_8bit\",\n"," logging_steps=5,\n"," save_steps=50,\n"," save_total_limit=2,\n"," report_to=\"none\",\n"," remove_unused_columns=False,\n",")\n","\n","trainer = Trainer(\n"," model=model,\n"," args=training_args,\n"," train_dataset=train_dataset,\n"," data_collator=multimodal_collator,\n",")\n","\n","trainer.train()\n","\n","# ====================== SAVE TO DRIVE + ZIP FOR DOWNLOAD ======================\n","print(\"\\nπΎ Saving final LoRA adapter to Google Drive...\")\n","\n","model.save_pretrained(drive_adapter_path)\n","processor.save_pretrained(drive_adapter_path)\n","\n","# Create downloadable ZIP (from Drive folder)\n","zip_adapter_path = \"/content/gemma_lora_adapter.zip\"\n","with zipfile.ZipFile(zip_adapter_path, 'w') as z:\n"," for root, _, files_list in os.walk(drive_adapter_path):\n"," for file in files_list:\n"," file_path = os.path.join(root, file)\n"," arcname = os.path.relpath(file_path, drive_adapter_path)\n"," z.write(file_path, arcname)\n","\n","print(f\"π LoRA training complete!\")\n","print(f\" β
Saved to Google Drive: {drive_adapter_path}\")\n","print(f\" π¦ Zipped copy ready for download β {zip_adapter_path}\")\n","files.download(zip_adapter_path)\n","\n","print(\"\\nβ
You can now use this LoRA adapter from Google Drive in future inference cells.\")\n","print(\" Example: peft_model = PeftModel.from_pretrained(base_model, drive_adapter_path)\")\n","```ββββββββββββββββββββββββββββββββββββββββββββββββββ"],"metadata":{"cellView":"form","id":"4cCNLXWsKHe_"},"execution_count":null,"outputs":[]}],"metadata":{"accelerator":"GPU","colab":{"gpuType":"T4","provenance":[{"file_id":"1IFAN1z44DC5xcoAdXNeupO-nUTedA2uG","timestamp":1775323816042},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1775308348942},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1775233835241},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1775233735620},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1775159289229},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774964848181},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774906863352},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774901938471},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774884683620},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774883563998},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774882033159},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774881268156},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1774879795776},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1763646205520},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1760993725927},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1760450712160},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1756712618300},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1747490904984},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1740037333374},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1736477078136},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1725365086834}]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}
|
|
|
|
| 1 |
+
{"cells":[{"cell_type":"code","source":["#@markdown # Cell 1: Connect Google Drive + Restore HF_TOKEN (Run this FIRST)\n","\n","from google.colab import drive\n","from google.colab import userdata\n","import os\n","from pathlib import Path\n","\n","print(\"π Connecting to Google Drive and setting up HF_TOKEN...\")\n","\n","# Mount Drive\n","drive.mount('/content/drive', force_remount=True)\n","\n","# Create working folder (everything will be saved here)\n","WORKING_DIR = \"/content/drive/MyDrive/Gemma4Captioner\"\n","os.makedirs(WORKING_DIR, exist_ok=True)\n","print(f\"β
Working directory ready: {WORKING_DIR}\")\n","\n","# Restore HF_TOKEN from Colab secrets\n","hf_token = userdata.get('HF_TOKEN')\n","if hf_token:\n"," os.environ[\"HF_TOKEN\"] = hf_token\n"," print(\"β
HF_TOKEN restored from Colab Secrets.\")\n","else:\n"," print(\"β οΈ HF_TOKEN not found. Please click the key icon on the left sidebar, add 'HF_TOKEN', and run this cell again.\")\n","\n","print(\"\\nβ
Cell 1 complete! You can now run Cell 2 to load the model.\")"],"metadata":{"cellView":"form","id":"oQRO5Wo8DXT2"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@markdown # Cell 2: Load Gemma-4 Model (Heretic by default + Vision Latent Helpers)\n","\n","!pip install -q --upgrade --force-reinstall \"pillow<12.0\"\n","!pip install -q --upgrade transformers accelerate bitsandbytes\n","\n","import torch\n","from transformers import AutoProcessor, AutoModelForMultimodalLM\n","from google.colab import userdata\n","from PIL import Image\n","import base64\n","import io\n","\n","# ====================== VISION LATENT IMPROVEMENT HELPERS ======================\n","def get_optimal_vision_size(processor):\n"," \"\"\"Automatically detects the best resolution for Gemma-4's vision encoder (improves latent features).\"\"\"\n"," target_max_dim = 1024\n"," if hasattr(processor, \"image_processor\") and hasattr(processor.image_processor, \"size\"):\n"," size_cfg = processor.image_processor.size\n"," if isinstance(size_cfg, dict):\n"," dims = [v for v in size_cfg.values() if isinstance(v, (int, float))]\n"," if dims:\n"," target_max_dim = int(max(dims))\n"," elif isinstance(size_cfg, (int, float)):\n"," target_max_dim = int(size_cfg)\n"," return target_max_dim\n","\n","def image_to_data_url(img: Image.Image) -> str:\n"," \"\"\"Lossless PNG data URL β cleanest latent representation for the vision encoder.\"\"\"\n"," buffered = io.BytesIO()\n"," img.save(buffered, format=\"PNG\")\n"," img_str = base64.b64encode(buffered.getvalue()).decode(\"utf-8\")\n"," return f\"data:image/png;base64,{img_str}\"\n","\n","#@markdown **Choose your model version:**\n","use_heretic_version = True #@param {type:\"boolean\"}\n","\n","hf_token = os.environ.get(\"HF_TOKEN\") or userdata.get('HF_TOKEN')\n","\n","if use_heretic_version:\n"," model_id = \"coder3101/gemma-4-E2B-it-heretic\"\n"," print(\"π½ Loading **Gemma-4-E2B-Heretic** (your preferred uncensored version)...\")\n"," processor = AutoProcessor.from_pretrained(model_id, token=hf_token)\n"," model = AutoModelForMultimodalLM.from_pretrained(\n"," model_id,\n"," token=hf_token,\n"," dtype=\"auto\",\n"," device_map=\"auto\",\n"," low_cpu_mem_usage=True,\n"," )\n","else:\n"," model_id = \"google/gemma-4-E2B-it\"\n"," print(\"π½ Loading **Official Google Gemma-4-E2B-it**...\")\n"," processor = AutoProcessor.from_pretrained(model_id, token=hf_token)\n"," model = AutoModelForMultimodalLM.from_pretrained(\n"," model_id,\n"," token=hf_token,\n"," torch_dtype=\"auto\",\n"," device_map=\"auto\",\n"," low_cpu_mem_usage=True,\n"," )\n","\n","print(\"β
Model loaded successfully!\")\n","print(f\" Model: {model_id}\")\n","print(f\" Device: {model.device}\")\n","print(f\" VRAM used: {torch.cuda.memory_allocated() / 1024**3:.2f} GB\")\n","print(\" β
Vision latent helpers are now active (optimal resize + lossless PNG)\")\n","print(\"\\nCell 2 complete. Run Cell 3 or Cell 4 next.\")"],"metadata":{"cellView":"form","id":"4btb30LwDZ2r"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@markdown # Cell 3: Interactive Chat β Talk to Gemma-4 with Images (Full History + Enhanced Vision)\n","\n","import json\n","import os\n","import torch\n","from google.colab import files\n","from IPython.display import Image, display\n","\n","#@markdown\n","user_message = \"Describe this image in detail, including key objects, scene, colors, mood, lighting, and any visible text. Be accurate and comprehensive. you may not use newline or **bold font**. You may not itemize. I want a single block of text , 400 words long. \" #@param {type:\"string\"}\n","attach_image = True #@param {type:\"boolean\"}\n","reset_chat = False #@param {type:\"boolean\"}\n","only_show_latest_reply = True #@param {type:\"boolean\"}\n","show_image_with_reply = True #@param {type:\"boolean\"}\n","\n","chat_history_path = \"/content/chat_history.json\"\n","chat_log_path = \"/content/chat_log.txt\"\n","latest_image_file = \"/content/latest_image_path.txt\"\n","\n","if 'model' not in globals() or 'processor' not in globals():\n"," print(\"β οΈ Please run Cell 1 β Cell 2 first!\")\n","else:\n"," print(\"β
Ready for chat with **improved vision latent representation**.\")\n","\n"," if reset_chat:\n"," for p in [chat_history_path, chat_log_path, latest_image_file]:\n"," if os.path.exists(p): os.remove(p)\n"," print(\"ποΈ Chat reset.\")\n","\n"," messages = []\n"," if os.path.exists(chat_history_path) and not reset_chat:\n"," with open(chat_history_path, \"r\", encoding=\"utf-8\") as f:\n"," messages = json.load(f)\n","\n"," latest_image_path = None\n"," if os.path.exists(latest_image_file):\n"," with open(latest_image_file, \"r\", encoding=\"utf-8\") as f:\n"," latest_image_path = f.read().strip()\n","\n"," if user_message.strip():\n"," image_path = None\n"," if attach_image:\n"," print(\"π€ Upload image...\")\n"," uploaded = files.upload()\n"," if uploaded:\n"," filename = next(iter(uploaded.keys()))\n"," if filename.lower().endswith(('.png','.jpg','.jpeg','.webp','.bmp')):\n"," image_path = f\"/content/{filename}\"\n"," latest_image_path = image_path\n"," with open(latest_image_file, \"w\", encoding=\"utf-8\") as f:\n"," f.write(image_path)\n","\n"," if image_path is None and latest_image_path:\n"," image_path = latest_image_path\n","\n"," user_content = []\n"," if image_path:\n"," raw_image = Image.open(image_path).convert(\"RGB\")\n"," target = get_optimal_vision_size(processor)\n"," if max(raw_image.size) != target or min(raw_image.size) < 512:\n"," scale = target / max(raw_image.size)\n"," raw_image = raw_image.resize((int(raw_image.width*scale), int(raw_image.height*scale)), Image.LANCZOS)\n"," image_url = image_to_data_url(raw_image)\n"," user_content.append({\"type\": \"image\", \"url\": image_url})\n"," print(f\" π¬ Image prepared with enhanced latent features ({target}px)\")\n","\n"," user_content.append({\"type\": \"text\", \"text\": user_message})\n"," messages.append({\"role\": \"user\", \"content\": user_content})\n","\n"," inputs = processor.apply_chat_template(\n"," messages, add_generation_prompt=True, tokenize=True, return_tensors=\"pt\", return_dict=True\n"," ).to(model.device)\n","\n"," with torch.no_grad():\n"," outputs = model.generate(**inputs, max_new_tokens=512, do_sample=True, temperature=0.7, top_p=0.9)\n","\n"," input_len = inputs[\"input_ids\"].shape[-1]\n"," raw = processor.decode(outputs[0][input_len:], skip_special_tokens=False)\n"," parsed = processor.parse_response(raw) if hasattr(processor, \"parse_response\") else raw.strip()\n"," reply = parsed[\"content\"] if isinstance(parsed, dict) and \"content\" in parsed else str(parsed)\n","\n"," messages.append({\"role\": \"assistant\", \"content\": [{\"type\": \"text\", \"text\": reply}]})\n","\n"," with open(chat_history_path, \"w\", encoding=\"utf-8\") as f:\n"," json.dump(messages, f, ensure_ascii=False, indent=2)\n","\n"," print(f\"\\nπ€ Gemma-4: {reply}\\n\")\n","\n"," # Display logic (same as before)\n"," print(\"\\n\" + \"=\"*80)\n"," if only_show_latest_reply:\n"," latest_reply = None\n"," for msg in reversed(messages):\n"," if msg[\"role\"] == \"assistant\":\n"," content = msg.get(\"content\", [])\n"," latest_reply = next((item.get(\"text\", \"\") for item in content if item.get(\"type\") == \"text\"), \"\") if isinstance(content, list) else str(content)\n"," break\n"," if latest_reply:\n"," print(\"π€ Latest Reply:\\n\" + latest_reply)\n"," if show_image_with_reply and latest_image_path and os.path.exists(latest_image_path):\n"," display(Image(filename=latest_image_path, width=400))\n"," print(\"=\"*80)"],"metadata":{"cellView":"form","id":"SShL3oqBDdhE"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@markdown # Cell 4: Batch Caption Generator β Upload Multiple Images β 400-Word Captions + ZIP Download\n","\n","from google.colab import files\n","import zipfile\n","import os\n","from PIL import Image\n","\n","output_dir = \"/content/image_text_pairs\"\n","os.makedirs(output_dir, exist_ok=True)\n","\n","print(\"π€ Upload your image(s) (you can select multiple)\")\n","uploaded = files.upload()\n","\n","prompt_style = \"Describe this image in detail, including key objects, scene, colors, mood, lighting, and any visible text. Be accurate and comprehensive. you may not use newline or **bold font**. You may not itemize. I want a single block of text , 400 words long. \" #@param {type:\"string\"}\n","\n","generated_count = 0\n","\n","for filename in list(uploaded.keys()):\n"," if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.bmp')):\n"," image_path = f\"/content/{filename}\"\n","\n"," raw_image = Image.open(image_path).convert(\"RGB\")\n"," target_max_dim = get_optimal_vision_size(processor)\n"," if max(raw_image.size) != target_max_dim or min(raw_image.size) < 512:\n"," scale = target_max_dim / max(raw_image.size)\n"," new_size = (int(raw_image.width * scale), int(raw_image.height * scale))\n"," raw_image = raw_image.resize(new_size, Image.LANCZOS)\n"," image_url = image_to_data_url(raw_image)\n","\n"," print(f\"πΈ Processing {filename} (enhanced latent representation)...\")\n","\n"," messages = [{\"role\": \"user\", \"content\": [\n"," {\"type\": \"image\", \"url\": image_url},\n"," {\"type\": \"text\", \"text\": prompt_style}\n"," ]}]\n","\n"," inputs = processor.apply_chat_template(\n"," messages, add_generation_prompt=True, tokenize=True, return_tensors=\"pt\", return_dict=True\n"," ).to(model.device)\n","\n"," with torch.no_grad():\n"," outputs = model.generate(**inputs, max_new_tokens=512, do_sample=True, temperature=0.7, top_p=0.9)\n","\n"," input_len = inputs[\"input_ids\"].shape[-1]\n"," raw = processor.decode(outputs[0][input_len:], skip_special_tokens=False)\n"," parsed = processor.parse_response(raw) if hasattr(processor, \"parse_response\") else raw.strip()\n"," caption = parsed[\"content\"] if isinstance(parsed, dict) and \"content\" in parsed else str(parsed)\n","\n"," base_name = os.path.splitext(filename)[0]\n"," with open(os.path.join(output_dir, f\"{base_name}.txt\"), \"w\", encoding=\"utf-8\") as f:\n"," f.write(caption)\n"," Image.open(image_path).save(os.path.join(output_dir, filename))\n"," generated_count += 1\n","\n","zip_path = \"/content/image_text_pairs.zip\"\n","with zipfile.ZipFile(zip_path, 'w') as zipf:\n"," for root, _, files_list in os.walk(output_dir):\n"," for file in files_list:\n"," zipf.write(os.path.join(root, file), file)\n","\n","print(f\"\\nπ Done! Generated {generated_count} captions with enhanced vision.\")\n","files.download(zip_path)"],"metadata":{"cellView":"form","id":"vH512u3QDhzF"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["β
Welcome to your new, beginner-friendly Gemma-4 Image Captioning Notebook!\n","\n","This notebook lets you generate long, detailed 400-word captions for any images using Gemma-4-E2B-Heretic (the uncensored version you prefer). \n","It automatically improves the latent image representation (the vision features the model actually βseesβ) so captions are much more accurate and vivid.\n","\n","### Whatβs special about this notebook?\n","- Heretic version (default): Removes safety restrictions β richer, more creative, and fully compliant captions. \n","- Official Google version (optional via checkbox): Same vision quality but slightly more cautious. \n","- Vision latent improvements (built-in): Every image is resized to the modelβs exact preferred resolution + sent as a lossless PNG data URL. This gives the vision encoder the cleanest possible pixel data β stronger latent features β noticeably better captions. \n","- No more βsort-of correctβ descriptions β the model now truly sees the details.\n","\n","### How to use (super simple for new users):\n","1. Run Cell 1 first (connects Drive + restores your HF_TOKEN). \n","2. Run Cell 2 (loads the model β choose Heretic or Official). \n","3. Use Cell 3 for interactive chat with images. \n","4. Use Cell 4 for batch-processing many images + ZIP download. \n","\n","Always run cells in order (top to bottom). \n","Everything is saved to Google Drive automatically if you want persistence.\n"],"metadata":{"id":"THiwFxj3D6Xx"}},{"cell_type":"markdown","source":["LoRa training (Untested)"],"metadata":{"id":"m8W_d-1iRrr2"}},{"cell_type":"code","source":["import os\n","import zipfile\n","from pathlib import Path\n","import torch\n","import gc\n","from google.colab import files\n","from PIL import Image\n","from google.colab import drive\n","#@markdown Train LoRa on LLM using marching filenames in zip. In the txt files found in zip file , you can divide the Query and Reply desired with '//--//'\n","# ==================== MOUNT GOOGLE DRIVE FIRST ====================\n","print(\"π Checking Google Drive...\")\n","if not os.path.exists('/content/drive/MyDrive'):\n"," print(\"π Mounting Google Drive (this may ask for permission)...\")\n"," drive.mount('/content/drive', force_remount=False)\n","else:\n"," print(\"β
Google Drive already mounted.\")\n","\n","drive_adapter_path = \"/content/drive/MyDrive/gemma_lora_adapter\"\n","os.makedirs(drive_adapter_path, exist_ok=True)\n","print(f\"πΎ LoRA will be saved directly to: {drive_adapter_path}\")\n","\n","# ==================== TRAINING PARAMETERS ====================\n","zip_path = \"\" #@param {type:\"string\"}\n","upload_new_zip = True #@param {type:\"boolean\"}\n","num_epochs = 3 #@param {type:\"slider\", min:1, max:10, step:1}\n","lora_rank = 16 #@param {type:\"integer\"}\n","lora_alpha = 32 #@param {type:\"integer\"}\n","learning_rate = \"2e-4\" #@param {type:\"string\"}\n","batch_size = 1 #@param {type:\"integer\"}\n","gradient_accumulation_steps = 4 #@param {type:\"integer\"}\n","# ===========================================================\n","\n","# Install required packages for LoRA training\n","!pip install -q --upgrade peft trl\n","\n","# Get HF token (reuse from previous cells)\n","from google.colab import userdata\n","hf_token = userdata.get('HF_TOKEN')\n","if not hf_token:\n"," print(\"β οΈ Please add HF_TOKEN to Colab secrets first!\")\n","\n","# Model ID (same as Cell 1a)\n","model_id = \"coder3101/gemma-4-E2B-it-heretic\"\n","\n","# ====================== UNLOAD VRAM FIRST ======================\n","print(\"\\nπ§Ή Unloading VRAM prior to LoRA training...\")\n","torch.cuda.empty_cache()\n","gc.collect()\n","\n","reuse_model = False\n","if 'model' in globals() and 'processor' in globals():\n"," current_device = getattr(model, 'device', None)\n"," print(f\" Detected existing model on device: {current_device}\")\n"," if current_device is not None and current_device.type == 'cpu':\n"," print(\"β
Transformer model found on CPU β reusing existing model (no re-download from HF)\")\n"," reuse_model = True\n"," else:\n"," print(\"π Existing model detected (likely on GPU). Unloading to load efficient 4-bit version...\")\n"," del globals()['model']\n"," if 'processor' in globals():\n"," del globals()['processor']\n"," torch.cuda.empty_cache()\n"," gc.collect()\n","else:\n"," print(\"π No existing model found β will load from Hugging Face.\")\n","\n","# ====================== LOAD / REUSE MODEL ======================\n","print(\"\\nπ Preparing model for LoRA training...\")\n","\n","from transformers import BitsAndBytesConfig, TrainingArguments, Trainer\n","from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training\n","from trl import SFTTrainer # kept for future compatibility\n","\n","if reuse_model:\n"," # Reuse the CPU-loaded model (full precision)\n"," print(\" Reusing existing model + processor\")\n"," # Prepare for kbit training (works on already-loaded model)\n"," model = prepare_model_for_kbit_training(model)\n","else:\n"," # Standard 4-bit load (most common case)\n"," print(\" Loading model in 4-bit for efficient training...\")\n"," quant_config = BitsAndBytesConfig(\n"," load_in_4bit=True,\n"," bnb_4bit_quant_type=\"nf4\",\n"," bnb_4bit_compute_dtype=torch.bfloat16,\n"," bnb_4bit_use_double_quant=True,\n"," )\n","\n"," processor = AutoProcessor.from_pretrained(model_id, token=hf_token)\n","\n"," model = AutoModelForMultimodalLM.from_pretrained(\n"," model_id,\n"," token=hf_token,\n"," quantization_config=quant_config,\n"," device_map=\"auto\",\n"," low_cpu_mem_usage=True,\n"," )\n","\n"," model = prepare_model_for_kbit_training(model)\n","\n","# Apply LoRA (targets all linear layers β perfect for Gemma-4)\n","lora_config = LoraConfig(\n"," r=lora_rank,\n"," lora_alpha=lora_alpha,\n"," target_modules=\"all-linear\",\n"," lora_dropout=0.05,\n"," bias=\"none\",\n"," task_type=\"CAUSAL_LM\",\n",")\n","\n","model = get_peft_model(model, lora_config)\n","model.print_trainable_parameters()\n","\n","print(\"β
Model + LoRA adapter ready (VRAM optimized)\")\n","\n","# ====================== DATASET PREPARATION ======================\n","print(\"\\nπ¦ Preparing dataset from ZIP...\")\n","\n","# Handle ZIP upload or existing path\n","if upload_new_zip or not zip_path or not os.path.exists(zip_path):\n"," print(\"π€ Upload your image-text pairs ZIP file (must contain matching .jpg/.png + .txt files)\")\n"," uploaded = files.upload()\n"," if uploaded:\n"," zip_filename = list(uploaded.keys())[0]\n"," zip_path = f\"/content/{zip_filename}\"\n"," print(f\"β
Using uploaded file: {zip_filename}\")\n"," else:\n"," print(\"β No ZIP uploaded. Aborting.\")\n"," raise SystemExit\n","\n","if not os.path.exists(zip_path):\n"," print(f\"β ZIP file not found: {zip_path}\")\n"," raise SystemExit\n","\n","# Unpack ZIP\n","dataset_dir = \"/content/lora_training_data\"\n","os.makedirs(dataset_dir, exist_ok=True)\n","\n","with zipfile.ZipFile(zip_path, 'r') as z:\n"," z.extractall(dataset_dir)\n","\n","print(f\"β
Extracted dataset to {dataset_dir}\")\n","\n","# Find all matching image + txt pairs\n","image_exts = ('.png', '.jpg', '.jpeg', '.webp', '.bmp')\n","pairs = []\n","\n","for txt_file in Path(dataset_dir).glob(\"**/*.txt\"):\n"," base_name = txt_file.stem\n"," image_path = None\n"," for ext in image_exts:\n"," candidate = txt_file.with_name(base_name + ext)\n"," if candidate.exists():\n"," image_path = str(candidate)\n"," break\n"," if not image_path:\n"," continue\n","\n"," with open(txt_file, \"r\", encoding=\"utf-8\") as f:\n"," text_content = f.read().strip()\n","\n"," # Split into Query and Reply using '//--//'\n"," if '//--//' in text_content:\n"," query_part, reply_part = [x.strip() for x in text_content.split('//--//', 1)]\n"," else:\n"," query_part = \"Describe this image in detail, including key objects, scene, colors, mood, lighting, and any visible text. Be accurate and comprehensive.\"\n"," reply_part = text_content\n","\n"," pairs.append({\n"," \"image_path\": image_path,\n"," \"query\": query_part,\n"," \"reply\": reply_part\n"," })\n","\n","print(f\"β
Found {len(pairs)} valid image-text training pairs.\")\n","\n","if len(pairs) == 0:\n"," print(\"β No matching image+txt pairs found in the ZIP. Aborting.\")\n"," raise SystemExit\n","\n","# ====================== CUSTOM DATASET + COLLATOR ======================\n","class MultimodalTrainingDataset(torch.utils.data.Dataset):\n"," def __init__(self, pairs, processor):\n"," self.pairs = pairs\n"," self.processor = processor\n","\n"," def __len__(self):\n"," return len(self.pairs)\n","\n"," def __getitem__(self, idx):\n"," item = self.pairs[idx]\n"," messages = [\n"," {\"role\": \"user\", \"content\": [\n"," {\"type\": \"image\", \"url\": item[\"image_path\"]},\n"," {\"type\": \"text\", \"text\": item[\"query\"]}\n"," ]},\n"," {\"role\": \"assistant\", \"content\": [{\"type\": \"text\", \"text\": item[\"reply\"]}]}\n"," ]\n","\n"," inputs = self.processor.apply_chat_template(\n"," messages,\n"," add_generation_prompt=False,\n"," tokenize=True,\n"," return_tensors=\"pt\",\n"," return_dict=True\n"," )\n"," inputs[\"labels\"] = inputs[\"input_ids\"].clone()\n","\n"," # Remove batch dim\n"," for k in list(inputs.keys()):\n"," if isinstance(inputs[k], torch.Tensor):\n"," inputs[k] = inputs[k].squeeze(0)\n"," return inputs\n","\n","train_dataset = MultimodalTrainingDataset(pairs, processor)\n","\n","def multimodal_collator(features):\n"," batch = {}\n"," input_ids = [f[\"input_ids\"] for f in features]\n"," attention_mask = [f[\"attention_mask\"] for f in features]\n"," labels = [f[\"labels\"] for f in features]\n","\n"," text_padded = processor.tokenizer.pad(\n"," {\"input_ids\": input_ids, \"attention_mask\": attention_mask},\n"," padding=True,\n"," return_tensors=\"pt\"\n"," )\n"," batch[\"input_ids\"] = text_padded[\"input_ids\"]\n"," batch[\"attention_mask\"] = text_padded[\"attention_mask\"]\n","\n"," labels_padded = processor.tokenizer.pad(\n"," {\"input_ids\": labels},\n"," padding=True,\n"," return_tensors=\"pt\"\n"," )[\"input_ids\"]\n"," labels_padded[labels_padded == processor.tokenizer.pad_token_id] = -100\n"," batch[\"labels\"] = labels_padded\n","\n"," # Vision tensors (pixel_values etc.)\n"," first_item = features[0]\n"," for key in first_item.keys():\n"," if key in [\"input_ids\", \"attention_mask\", \"labels\"]:\n"," continue\n"," if isinstance(first_item[key], torch.Tensor):\n"," vals = [f[key] for f in features]\n"," batch[key] = torch.stack(vals) if vals[0].dim() == 3 else torch.cat(vals)\n","\n"," return batch\n","\n","# ====================== TRAINING ======================\n","print(f\"\\nπ Starting LoRA training on {len(pairs)} pairs for {num_epochs} epochs...\")\n","\n","training_args = TrainingArguments(\n"," output_dir=drive_adapter_path, # β Saved directly to Google Drive\n"," num_train_epochs=num_epochs,\n"," per_device_train_batch_size=batch_size,\n"," gradient_accumulation_steps=gradient_accumulation_steps,\n"," learning_rate=float(learning_rate),\n"," fp16=True,\n"," optim=\"paged_adamw_8bit\",\n"," logging_steps=5,\n"," save_steps=50,\n"," save_total_limit=2,\n"," report_to=\"none\",\n"," remove_unused_columns=False,\n",")\n","\n","trainer = Trainer(\n"," model=model,\n"," args=training_args,\n"," train_dataset=train_dataset,\n"," data_collator=multimodal_collator,\n",")\n","\n","trainer.train()\n","\n","# ====================== SAVE TO DRIVE + ZIP FOR DOWNLOAD ======================\n","print(\"\\nπΎ Saving final LoRA adapter to Google Drive...\")\n","\n","model.save_pretrained(drive_adapter_path)\n","processor.save_pretrained(drive_adapter_path)\n","\n","# Create downloadable ZIP (from Drive folder)\n","zip_adapter_path = \"/content/gemma_lora_adapter.zip\"\n","with zipfile.ZipFile(zip_adapter_path, 'w') as z:\n"," for root, _, files_list in os.walk(drive_adapter_path):\n"," for file in files_list:\n"," file_path = os.path.join(root, file)\n"," arcname = os.path.relpath(file_path, drive_adapter_path)\n"," z.write(file_path, arcname)\n","\n","print(f\"π LoRA training complete!\")\n","print(f\" β
Saved to Google Drive: {drive_adapter_path}\")\n","print(f\" π¦ Zipped copy ready for download β {zip_adapter_path}\")\n","files.download(zip_adapter_path)\n","\n","print(\"\\nβ
You can now use this LoRA adapter from Google Drive in future inference cells.\")\n","print(\" Example: peft_model = PeftModel.from_pretrained(base_model, drive_adapter_path)\")\n","```ββββββββββββββββββββββββββββββββββββββββββββββββββ"],"metadata":{"cellView":"form","id":"4cCNLXWsKHe_"},"execution_count":null,"outputs":[]}],"metadata":{"accelerator":"GPU","colab":{"gpuType":"T4","provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/gemma4_heretic_vlm.ipynb","timestamp":1775331762109},{"file_id":"1IFAN1z44DC5xcoAdXNeupO-nUTedA2uG","timestamp":1775323816042},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1775308348942},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1775233835241},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1775233735620},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1775159289229},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774964848181},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774906863352},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774901938471},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774884683620},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774883563998},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774882033159},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774881268156},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1774879795776},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1763646205520},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1760993725927},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1760450712160},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1756712618300},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1747490904984},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1740037333374},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1736477078136},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1725365086834}]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}
|