gemma-tuner-multimodal
Fine-tune Gemma 4 and 3n models with audio, images, and text on Apple Silicon using PyTorch and Metal Performance Shaders.
What this skill does
# Gemma Multimodal Fine-Tuner > Skill by [ara.so](https://ara.so) — Daily 2026 Skills collection. Fine-tune Gemma 4 and Gemma 3n models on text, images, and audio data entirely on Apple Silicon (MPS), with support for streaming large datasets from GCS/BigQuery without filling local storage. --- ## What It Does - **Text LoRA**: instruction-tuning or completion fine-tuning from local CSV - **Image + Text LoRA**: captioning and VQA from local CSV - **Audio + Text LoRA**: the only Apple-Silicon-native path for this modality - **Cloud streaming**: train on terabytes from GCS/BigQuery without local copy - **MPS-native**: no NVIDIA GPU required — runs on MacBook Pro/Air/Mac Studio --- ## Installation ### Prerequisites - macOS 12.3+ with Apple Silicon (arm64) - Python 3.10+ (native arm64, not Rosetta) - Hugging Face account with Gemma access ```bash # Install Python 3.12 if needed brew install [email protected] # Create venv python3.12 -m venv .venv source .venv/bin/activate # Verify arm64 (must show arm64, not x86_64) python -c "import platform; print(platform.machine())" # Install PyTorch pip install torch torchaudio # Clone and install git clone https://github.com/mattmireles/gemma-tuner-multimodal cd gemma-tuner-multimodal pip install -e . # For Gemma 4 support (separate venv recommended) pip install -r requirements/requirements-gemma4.txt ``` ### Authenticate with Hugging Face ```bash huggingface-cli login # Or set environment variable: export HF_TOKEN=your_token_here ``` --- ## CLI Commands ```bash # Check system is ready gemma-macos-tuner system-check # Guided setup wizard (recommended for first run) gemma-macos-tuner wizard # Prepare dataset gemma-macos-tuner prepare <dataset-profile> # Fine-tune a model gemma-macos-tuner finetune <profile> --json-logging # Evaluate a run gemma-macos-tuner evaluate <profile-or-run> # Export merged HF/SafeTensors (merges LoRA when adapter_config.json present) gemma-macos-tuner export <run-dir-or-profile> # Blacklist bad samples from errors gemma-macos-tuner blacklist <profile> # List training runs gemma-macos-tuner runs list ``` --- ## Configuration (`config/config.ini`) The config is hierarchical INI: defaults → groups → models → datasets → profiles. ```ini [defaults] output_dir = output batch_size = 2 gradient_accumulation_steps = 8 learning_rate = 2e-4 num_train_epochs = 3 [model:gemma-3n-e2b-it] group = gemma base_model = google/gemma-3n-E2B-it [model:gemma-4-e2b-it] group = gemma base_model = google/gemma-4-E2B-it [dataset:my-audio-dataset] data_dir = data/datasets/my-audio-dataset audio_column = audio_path text_column = transcript [profile:my-audio-profile] model = gemma-3n-e2b-it dataset = my-audio-dataset modality = audio lora_r = 16 lora_alpha = 32 lora_dropout = 0.05 max_seq_length = 512 ``` Use `GEMMA_TUNER_CONFIG` env var to point to config outside repo root: ```bash export GEMMA_TUNER_CONFIG=/path/to/my/config.ini ``` --- ## Modality Configuration ### Text-Only Fine-Tuning **Instruction tuning** (user/assistant pairs): ```ini [profile:text-instruction] model = gemma-3n-e2b-it dataset = my-text-dataset modality = text text_sub_mode = instruction prompt_column = prompt text_column = response max_seq_length = 2048 lora_r = 16 lora_alpha = 32 ``` **Completion tuning** (full sequence trained): ```ini [profile:text-completion] model = gemma-3n-e2b-it dataset = my-text-dataset modality = text text_sub_mode = completion text_column = text max_seq_length = 2048 ``` **CSV format** for instruction tuning (`data/datasets/my-text-dataset/train.csv`): ```csv prompt,response "What is photosynthesis?","Photosynthesis is the process by which plants..." "Explain LoRA fine-tuning","LoRA (Low-Rank Adaptation) is a parameter-efficient..." ``` ### Image Fine-Tuning ```ini [profile:image-caption] model = gemma-3n-e2b-it dataset = my-image-dataset modality = image image_sub_mode = captioning image_token_budget = 256 prompt_column = prompt text_column = caption max_seq_length = 512 ``` **CSV format** (`data/datasets/my-image-dataset/train.csv`): ```csv image_path,prompt,caption /data/images/img1.jpg,Describe this image,A dog sitting on a green lawn... /data/images/img2.jpg,What is shown here,A bar chart showing quarterly revenue... ``` ### Audio Fine-Tuning ```ini [profile:audio-asr] model = gemma-3n-e2b-it dataset = my-audio-dataset modality = audio audio_column = audio_path text_column = transcript max_seq_length = 512 lora_r = 16 lora_alpha = 32 lora_dropout = 0.05 ``` **CSV format** (`data/datasets/my-audio-dataset/train.csv`): ```csv audio_path,transcript /data/audio/recording1.wav,The patient presents with acute respiratory symptoms /data/audio/recording2.wav,Counsel objects to the characterization of the evidence ``` --- ## Supported Models | Model Key | Hugging Face ID | Notes | |---|---|---| | `gemma-3n-e2b-it` | `google/gemma-3n-E2B-it` | Default, ~2B instruct | | `gemma-3n-e4b-it` | `google/gemma-3n-E4B-it` | ~4B instruct | | `gemma-4-e2b-it` | `google/gemma-4-E2B-it` | Needs requirements-gemma4.txt | | `gemma-4-e4b-it` | `google/gemma-4-E4B-it` | Needs requirements-gemma4.txt | | `gemma-4-e2b` | `google/gemma-4-E2B` | Base, needs Gemma 4 stack | | `gemma-4-e4b` | `google/gemma-4-E4B` | Base, needs Gemma 4 stack | Add custom models with a `[model:your-name]` section using `group = gemma`. --- ## Dataset Directory Layout ``` data/ └── datasets/ └── <dataset-name>/ ├── train.csv # required ├── validation.csv # optional └── test.csv # optional ``` --- ## Output Layout ``` output/ └── {run-id}-{profile}/ ├── metadata.json ├── metrics.json ├── checkpoint-*/ └── adapter_model/ # LoRA artifacts ``` --- ## Python API Examples ### Running Fine-Tuning Programmatically ```python from gemma_tuner.core.config import load_config from gemma_tuner.core.ops import run_finetune # Load config config = load_config("config/config.ini") # Run fine-tuning for a profile run_finetune(profile="my-audio-profile", config=config, json_logging=True) ``` ### Using Device Utilities ```python from gemma_tuner.utils.device import get_device, memory_hint device = get_device() # Returns "mps", "cuda", or "cpu" print(f"Training on: {device}") hint = memory_hint(model_key="gemma-3n-e2b-it") print(hint) ``` ### Loading and Inspecting Datasets ```python from gemma_tuner.utils.dataset_utils import load_csv_dataset train_df, val_df = load_csv_dataset( data_dir="data/datasets/my-text-dataset", text_column="response", prompt_column="prompt" ) print(f"Train samples: {len(train_df)}, Val samples: {len(val_df)}") ``` ### Custom LoRA Config ```python from peft import LoraConfig, get_peft_model from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained( "google/gemma-3n-E2B-it", torch_dtype="auto", device_map="mps" ) lora_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, target_modules=["q_proj", "v_proj", "k_proj", "o_proj"], task_type="CAUSAL_LM" ) model = get_peft_model(model, lora_config) model.print_trainable_parameters() ``` --- ## Common Patterns ### Full Workflow: Text Instruction Tuning ```bash # 1. Prepare your data mkdir -p data/datasets/my-dataset cp train.csv data/datasets/my-dataset/ cp validation.csv data/datasets/my-dataset/ # 2. Add profile to config/config.ini cat >> config/config.ini << 'EOF' [dataset:my-dataset] data_dir = data/datasets/my-dataset [profile:my-text-run] model = gemma-3n-e2b-it dataset = my-dataset modality = text text_sub_mode = instruction prompt_column = prompt text_column = response max_seq_length = 2048 lora_r = 16 lora_alpha = 32 EOF # 3. Prepare dataset gemma-macos-tuner prepare my-dataset # 4. Fine-tune gemma-macos-tuner finetune my-text-run --json-logging # 5. Export merged weights gemma-macos-tuner export my-text-run ``` ### GCS Streaming for Large Datasets ```ini [dataset:large-audio-gcs] sou
Related in Image & Video
watch
IncludedWatch a video (URL or local path). Downloads with yt-dlp, extracts auto-scaled frames with ffmpeg, pulls the transcript from captions (or Whisper API fallback), and hands the result to Claude so it can answer questions about what's in the video.
physical-ai-defect-image-generation
IncludedUse when the user wants to orchestrate defect image generation, run associated setup, or handle outputs on OSMO. The Day 0 path handles cold-start with USD-to-ROI, image-edit augmentation, and AnomalyGen to create initial PCBA datasets. The Day 1 path performs inference and labeling on real images. This skill helps with first-time asset setup, creation of finetuning checkpoints, and configuring deployment. Trigger keywords: defect image generation, dig workflow, dig pipeline, defect image detection workflow, aoi pipeline, aoi anomalygen, usd2roi anomalygen, day 0 pcba, day 1 pcba, day 1 real-photo alignment, day 1 manual roi, metal surface anomaly, glass defect, anomalygen finetune, setup_pcb, setup_metal, setup_glass, setup_pretrained, dig setup, dig datasets, dig pretrained checkpoint, dig image-edit endpoint.
accelint-react-best-practices
IncludedReact performance optimization and best practices. ALWAYS use this skill when working with any React code - writing components, hooks, JSX; refactoring; optimizing re-renders, memoization, state management; reviewing for performance; fixing hydration mismatches; debugging infinite re-renders, stale closures, input focus loss, animations restarting; preventing remounting; implementing transitions, lazy initialization, effect dependencies. Even simple React tasks benefit from these patterns. Covers React 19+ (useEffectEvent, Activity, ref props). Triggers - useEffect, useState, useMemo, useCallback, memo, inline components, nested components, components inside components, re-render, performance, hydration, SSR, Next.js, useDeferredValue, combined hooks.
elevenlabs-agents
IncludedBuild conversational AI voice agents with ElevenLabs Platform using React, JavaScript, React Native, or Swift SDKs. Configure agents, tools (client/server/MCP), RAG knowledge bases, multi-voice, and Scribe real-time STT. Use when: building voice chat interfaces, implementing AI phone agents with Twilio, configuring agent workflows or tools, adding RAG knowledge bases, testing with CLI "agents as code", or troubleshooting deprecated @11labs packages, Android audio cutoff, CSP violations, dynamic variables, or WebRTC config. Keywords: ElevenLabs Agents, ElevenLabs voice agents, AI voice agents, conversational AI, @elevenlabs/react, @elevenlabs/client, @elevenlabs/react-native, @elevenlabs/elevenlabs-js, @elevenlabs/agents-cli, elevenlabs SDK, voice AI, TTS, text-to-speech, ASR, speech recognition, turn-taking model, WebRTC voice, WebSocket voice, ElevenLabs conversation, agent system prompt, agent tools, agent knowledge base, RAG voice agents, multi-voice agents, pronunciation dictionary, voice speed control, elevenlabs scribe, @11labs deprecated, Android audio cutoff, CSP violation elevenlabs, dynamic variables elevenlabs, case-sensitive tool names, webhook authentication
humanizer
IncludedHumanize AI-generated text by detecting and removing patterns typical of LLM output. Rewrites text to sound natural, specific, and human. Uses 28 pattern detectors, 560+ AI vocabulary terms across 3 tiers, and statistical analysis (burstiness, type-token ratio, readability) for comprehensive detection. Use when asked to humanize text, de-AI writing, make content sound more natural/human, review writing for AI patterns, score text for AI detection, or improve AI-generated drafts. Covers content, language, style, communication, and filler categories.
generating-mermaid-diagrams
IncludedSalesforce architecture diagrams using Mermaid with ASCII fallback. Use this skill when generating text-based diagrams for Salesforce architecture, OAuth flows, ERDs, integration sequences, or Agentforce structure. TRIGGER when: user says "diagram", "visualize", "ERD", or asks for sequence diagrams, flowcharts, class diagrams, or architecture visualizations in Mermaid. DO NOT TRIGGER when: user wants PNG/SVG image output (use generating-visual-diagrams), or asks about non-Salesforce systems.