Логотип Gemma Trainer

Gemma Trainer

ОрганизацияПопулярное
google-gemma
gemma-trainer

Trigger this skill when the user wants to train, fine-tune, or adapt Gemma models (e.g. SFT, DPO, RLHF, Reward Modeling) on local hardware. Covers TRL, Unsloth, dataset preparation, validation, and GGUF/LiteRT conversion.

Обзор

Издательgoogle-gemma
Репозиторийgemma-skills
Название навыкаgemma-trainer
Звёзды
1K
Форки
79
Встроенные файлы
5
ЛицензияApache-2.0
Ссылки
  • Инструкции в формате Markdown

    Файл SKILL.md, который модель загружает по необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Файлы в комплекте: 5

    Скрипты, шаблоны и справочные материалы, которые модель может читать во время работы. Файлы доступны только для чтения и никогда не выполняются.

  • Открытый исходный код

    Опубликовано на GitHub: google-gemma. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Gemma Trainer в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/google-gemma/gemma-skills/tree/main/skills/gemma-trainer
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Новый навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/google-gemma/gemma-skills.git /tmp/gemma-skills
mkdir -p .claude/skills
cp -r /tmp/gemma-skills/skills/gemma-trainer .claude/skills/gemma-trainer
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Gemma Trainer в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Gemma Trainer, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Gemma Trainer не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими API-ключами.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Gemma Training and Fine-Tuning Skill

1. Core Principles: Local Fine-Tuning Setup

When training locally, memory efficiency and execution speed are huge. Always guide the user to follow these best practices:

  • Prioritize Unsloth: For local single-GPU training, always recommend Unsloth. It supports Gemma 4 natively, uses up to 70% less memory, and is up to 2x faster than standard Hugging Face PEFT training.
  • Fall Back to TRL: For multi-GPU environments (using DDP/FSDP) or when Unsloth is unavailable, use Hugging Face TRL (SFTTrainer, DPOTrainer) coupled with PEFT and bitsandbytes (for QLoRA).
  • Always use QLoRA (4-bit Quantization): Crucial for fitting Gemma models (like Gemma 4 12B/31B) into consumer VRAM.
  • Manage Context Window & Max Length: Although Gemma 4 supports up to a 256K context window, recommend training with a context window of 2048 to 8192 tokens locally to prevent Out-Of-Memory (OOM) errors.

2. Choosing the Right Training Method

Help the user choose the correct workflow based on their goal:

  • Supervised Fine-Tuning (SFT): Teaching new domains, specialized task instructions, or custom output structures.
    • Prerequisites: Raw text, instruction pairs, or chat logs.
    • Output: Adaptor trained on prompt/completion pairs.
  • Direct Preference Optimization (DPO): Aligning model style, behavior, tone, or safety with human preferences.
    • Prerequisites: A previously SFT-trained Gemma model and preferred pairwise datasets.
    • Output: Aligning model weights directly without a separate reward head.
  • Reward Modeling (RM): Training a scoring system to evaluate response quality.
    • Prerequisites: Binary preference pairwise datasets.
    • Output: A classification-style reward head on top of Gemma.

3. Dataset Preparation & Validation

Formatting issues are the #1 cause of poor training runs. Ensure you validate files using the utility script [assets/dataset_prep.py].

Gemma Chat Prompt Format

Ensure the dataset matches Gemma's official chat template:

<|turn>system
Your instruction here<turn|>
<|turn>user
Your query here<turn|>
<|turn>model
Your response here<turn|>

To avoid formatting drift, use the tokenizer's apply_chat_template during dataset tokenization.

Format Specifications

  • SFT (Supervised Fine-Tuning): Format as a list of conversation turns.
    json
    {
      "messages": [
        {"role": "user", "content": "Tell me a joke."},
        {"role": "model", "content": "Why did the computer go to the doctor? It had a virus!"}
      ]
    }
  • DPO (Direct Preference Optimization): Requires pairwise samples containing a prompt, a chosen (better) response, and a rejected (worse) response.
    json
    {
      "prompt": "Write a python function to compute factorial.",
      "chosen": "def factorial(n):\n    return 1 if n <= 1 else n * factorial(n - 1)",
      "rejected": "factorial is computed using recursion or loops. Just import math."
    }
  • Reward Modeling: Format identically to DPO datasets. The RewardTrainer evaluates the pair and learns to output a higher logit score for chosen than for rejected.

Dataset Distillation & Synthesis (Teacher-Student)

Local knowledge distillation allows you to train small, lightweight student models (such as Gemma 4 E2B) using high-quality dataset outputs generated by larger, highly capable teacher models (such as Gemma 4 31B or Gemma 4 26B A4B).

Use the [assets/distill_dataset.py] utility script to generate fine-tuning datasets on your local machine.

4. Fine-Tuning Workflows

Supervised Fine-Tuning (SFT)

Use the [assets/sft_train.py] asset to launch a local QLoRA fine-tuning session.

  • LoRA Hyperparameters:
    • Rank (r): 16 or 32 (Higher rank captures complex behaviors but consumes more memory).
    • Alpha (lora_alpha): 32 or 64 (Rule of thumb: lora_alpha = 2 * r).
    • Dropout (lora_dropout): 0.05 or 0.1 (Forcing the model to learn more robust features rather than relying on specific paths).
    • Target Modules: Use PEFT's Gemma 4 defaults scope to the LM layers.
    • Learning Rate: 2e-4 for QLoRA; 2e-5 for full fine-tuning.

Direct Preference Optimization (DPO)

Use the [assets/dpo_train.py] template to execute alignment.

  • Rules for DPO:
    • Always perform SFT on the base model using your instruction format before running DPO. Running DPO directly on an out-of-domain base model usually fails or degrades output formatting.
    • Set beta (DPO temperature parameter) to 0.1. Values between 0.1 and 0.5 control how strictly the model adheres to the reference policy.

Reward Modeling (RM)

Use the [assets/reward_train.py] template to train an evaluation model.

  • Initializes the model with a sequence classification head (AutoModelForSequenceClassification with num_labels=1).
  • Trains the single scalar reward value to distinguish preferred responses.

5. Multimodal Fine-Tuning (Vision & Audio)

Gemma 4 models are natively multimodal. To fine-tune them on images or audio:

Vision SFT

  • Use Gemma 4 E2B/E4B/12B/26B/31B models.
  • Use standard Hugging Face SFTTrainer with a custom visual data collator.
  • Prepare your dataset containing local image paths or PIL images, alongside corresponding conversation instructions:
    json
    {
      "messages": [
        {"role": "user", "content": [
            {"type": "image", "url": "path/to/image.png"},
            {"type": "text", "text": "Describe this image."}
        ]},
        {"role": "assistant", "content": [
            {"type": "text", "text": "An abstract oil painting with vibrant warm gradients."}
        ]}
      ]
    }
    

Audio SFT

  • Use Gemma 4 E2B/E4B/12B models.
  • Feed raw audio arrays (sampled at 16kHz) through the model processor to produce input_features.
  • Maintain conversational formatting, replacing image type with audio type in the message format.
    json
    {
      "messages": [
        {"role": "user", "content": [
            {"type": "text", "text": "Describe this audio."},
            {"type": "audio", "url": "path/to/audio.wav"}
        ]},
        {"role": "assistant", "content": [
            {"type": "text", "text": "This is an audio file of a bird chirping."}
        ]}
      ]
    }

6. Post-Training & Deployment Utilities

GGUF Conversion

Once your LoRA training is finished, you can convert your model to GGUF format.

Option 1: Native Export via Unsloth (Recommended)

If you trained your model using Unsloth, you can export directly to GGUF natively. This automatically handles merging and quantization.

Fetch Saving to GGUF for the best practice.

Option 2: Manual Conversion with llama.cpp

If you did not use Unsloth, you can convert your merged Hugging Face model directory manually using llama.cpp.

On-Device Deployment with LiteRT-LM (.litertlm)

LiteRT-LM is optimized for running models like Gemma 4 E2B and Gemma 4 E4B on mobile, web, and IoT hardware with hardware acceleration (CPU, GPU, NPU). Fetch LiteRT-LM guide for the best practice.

Встроенные файлы

Модель читает эти файлы по мере необходимости, пока навык загружен. Они доступны только для чтения и никогда не выполняются.

Часто задаваемые вопросы

Что делает навык ИИ Gemma Trainer?

Trigger this skill when the user wants to train, fine-tune, or adapt Gemma models (e.g. SFT, DPO, RLHF, Reward Modeling) on local hardware. Covers TRL, Unsloth, dataset preparation, validation, and GGUF/LiteRT conversion.

Зачем использовать Gemma Trainer в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Gemma Trainer — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Gemma Trainer в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/google-gemma/gemma-skills/tree/main/skills/gemma-trainer. TypingMind прочитает файл SKILL.md, включит сопутствующие файлы в пакет и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Gemma Trainer?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Gemma Trainer?

С любым количеством. Если модель поддерживает навыки, вы можете использовать с ней Gemma Trainer: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama и другие — всё в TypingMind с вашими собственными ключами API.

Бесплатен ли навык ИИ Gemma Trainer?

Да. Навык опубликован на GitHub автором google-gemma по лицензии Apache-2.0. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это многоразовый набор инструкций, который объясняет модели ИИ, как выполнять конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты для вызова — код, который где-то выполняется и возвращает результат. Навык ИИ вместо этого даёт модели знания и порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте свою рабочую ИИ-среду сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇