惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Google DeepMind News
Google DeepMind News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
宝玉的分享
宝玉的分享
量子位
博客园 - 叶小钗
博客园_首页
Know Your Adversary
Know Your Adversary
S
Schneier on Security
罗磊的独立博客
C
Cyber Attacks, Cyber Crime and Cyber Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Simon Willison's Weblog
Simon Willison's Weblog
美团技术团队
WordPress大学
WordPress大学
大猫的无限游戏
大猫的无限游戏
Hacker News: Ask HN
Hacker News: Ask HN
Application and Cybersecurity Blog
Application and Cybersecurity Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Security Latest
Security Latest
月光博客
月光博客
Spread Privacy
Spread Privacy
C
Cybersecurity and Infrastructure Security Agency CISA
人人都是产品经理
人人都是产品经理
J
Java Code Geeks
C
CERT Recently Published Vulnerability Notes
Last Week in AI
Last Week in AI
Attack and Defense Labs
Attack and Defense Labs
NISL@THU
NISL@THU
H
Hacker News: Front Page
N
News and Events Feed by Topic
小众软件
小众软件
T
Threatpost
V2EX - 技术
V2EX - 技术
T
Tailwind CSS Blog
阮一峰的网络日志
阮一峰的网络日志
Project Zero
Project Zero
L
LINUX DO - 热门话题
Apple Machine Learning Research
Apple Machine Learning Research
C
CXSECURITY Database RSS Feed - CXSecurity.com
TaoSecurity Blog
TaoSecurity Blog
P
Privacy International News Feed
Latest news
Latest news
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
酷 壳 – CoolShell
酷 壳 – CoolShell
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
AWS News Blog
AWS News Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 【当耐特】
Hugging Face - Blog
Hugging Face - Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Fine-Tuning Gemma 4 for Function Calling with TRL's New Multimodal Tool Support
pulkitgovrani · 2026-05-24 · via DEV Community

This is a submission for the Gemma 4 Challenge: Write About Gemma 4

Gemma 4 ships with native function calling built in — trained from scratch, not prompt-engineered. But "built in" and "tuned for your specific tools" are different things.

If you have a set of internal APIs, a specific tool schema, or edge-case behaviors that the base model handles inconsistently, fine-tuning on your own function-calling data is the right move. TRL (Transformer Reinforcement Learning library) added multimodal tool response support in the same release window as Gemma 4, making this the first time you can fine-tune a multimodal model on tool use — including image outputs from tools.

This guide walks through the full pipeline: data format, fine-tuning with QLoRA, and evaluation.


What TRL's Multimodal Tool Support Actually Adds

Before this update, TRL's SFTTrainer (Supervised Fine-Tuning) could train on text tool calls and text tool responses. The new version adds:

  • Image outputs from tools — a tool that returns an image (chart, rendered diagram, screenshot) can now be part of the training trajectory
  • Multi-turn tool use sequences — full call → response → reasoning → next call chains
  • Gemma 4 chat template — native support for Gemma 4's system/user/assistant/tool format

For pure text tool calling, the older approach still works. The multimodal support matters when your agent needs to reason about visual outputs from tool calls.


Prerequisites

pip install trl>=0.12.0 transformers>=4.50 datasets peft accelerate bitsandbytes

For 4-bit quantization (recommended for consumer GPUs):

pip install bitsandbytes>=0.43.0


Data Format

Your training data needs to be structured as multi-turn conversations with tool calls and responses. TRL's SFTTrainer expects the Gemma 4 chat format:

# Each example is a list of messages
example = [
    {
        "role": "system",
        "content": "You are a data analysis assistant with access to a Python code executor and a charting tool."
    },
    {
        "role": "user",
        "content": "What's the trend in our monthly revenue for Q1 2026?"
    },
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [
            {
                "type": "function",
                "function": {
                    "name": "execute_python",
                    "arguments": '{"code": "import pandas as pd\\ndf = pd.read_csv(\'revenue.csv\')\\nprint(df[df[\'quarter\']==\'Q1\'].groupby(\'month\')[\'revenue\'].sum())"}'
                }
            }
        ]
    },
    {
        "role": "tool",
        "name": "execute_python",
        "content": "month\nJanuary     842000\nFebruary    891000\nMarch       967000\nName: revenue, dtype: int64"
    },
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [
            {
                "type": "function",
                "function": {
                    "name": "create_chart",
                    "arguments": '{"data": [842000, 891000, 967000], "labels": ["Jan", "Feb", "Mar"], "type": "line", "title": "Q1 2026 Monthly Revenue"}'
                }
            }
        ]
    },
    {
        "role": "tool",
        "name": "create_chart",
        "content": [
            {"type": "image", "image": "<PIL.Image object>"},  # chart image
            {"type": "text", "text": "Chart generated successfully"}
        ]
    },
    {
        "role": "assistant",
        "content": "Q1 revenue shows a clear upward trend: January $842K → February $891K → March $967K. That's 14.8% growth over the quarter, with acceleration in March (+8.5% vs February's +5.8%). The chart shows a steepening curve, which is a positive signal."
    }
]

The key difference from text-only tool calling: the tool role message can now contain {"type": "image", ...} content — the image output from the tool becomes part of the training trajectory.


Building a Training Dataset

For fine-tuning to work, you need enough examples to cover your tool schemas and the edge cases you care about. A minimum viable dataset for a specific domain is usually 100-500 examples.

from datasets import Dataset

def build_training_examples():
    """
    Build your domain-specific function calling examples.
    Each example should demonstrate:
    1. Correct tool selection
    2. Correct argument formatting
    3. Correct reasoning from tool output
    4. Edge case handling (tool errors, multiple calls, no tool needed)
    """
    examples = []

    # Example: correct tool selection
    examples.append([
        {"role": "system", "content": "You have access to: get_weather(city: str), search_web(query: str), calculator(expression: str)"},
        {"role": "user", "content": "What's 15% of $847?"},
        {
            "role": "assistant",
            "content": None,
            "tool_calls": [{"type": "function", "function": {"name": "calculator", "arguments": '{"expression": "847 * 0.15"}'}}]
        },
        {"role": "tool", "name": "calculator", "content": "127.05"},
        {"role": "assistant", "content": "15% of $847 is **$127.05**."}
    ])

    # Example: no tool needed
    examples.append([
        {"role": "system", "content": "You have access to: get_weather(city: str), search_web(query: str), calculator(expression: str)"},
        {"role": "user", "content": "What's the capital of France?"},
        {"role": "assistant", "content": "The capital of France is Paris."}
        # No tool call — model should answer directly from knowledge
    ])

    # Example: tool error handling
    examples.append([
        {"role": "system", "content": "You have access to: get_weather(city: str)"},
        {"role": "user", "content": "What's the weather in Atlantis?"},
        {
            "role": "assistant",
            "content": None,
            "tool_calls": [{"type": "function", "function": {"name": "get_weather", "arguments": '{"city": "Atlantis"}'}}]
        },
        {"role": "tool", "name": "get_weather", "content": '{"error": "City not found"}'},
        {"role": "assistant", "content": "I couldn't retrieve weather for Atlantis — it wasn't found in the weather service. Could you double-check the city name?"}
    ])

    return examples

raw_examples = build_training_examples()
dataset = Dataset.from_dict({"messages": raw_examples})


QLoRA Fine-Tuning with SFTTrainer

import torch
from transformers import AutoTokenizer, AutoModelForImageTextToText, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model
from trl import SFTTrainer, SFTConfig

model_id = "google/gemma-4-E4B-it"

# 4-bit quantization config
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_use_double_quant=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
)

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForImageTextToText.from_pretrained(
    model_id,
    quantization_config=bnb_config,
    device_map="auto",
)

# LoRA config — target the attention and MLP projection layers
lora_config = LoraConfig(
    r=16,
    lora_alpha=32,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
    lora_dropout=0.05,
    bias="none",
    task_type="CAUSAL_LM",
)

model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
# trainable params: ~20M || all params: ~8B || trainable%: ~0.25%

# Training config
training_config = SFTConfig(
    output_dir="./gemma4-finetuned",
    num_train_epochs=3,
    per_device_train_batch_size=1,
    gradient_accumulation_steps=8,        # effective batch size: 8
    learning_rate=2e-4,
    warmup_ratio=0.05,
    lr_scheduler_type="cosine",
    bf16=True,
    logging_steps=10,
    save_strategy="epoch",
    max_seq_length=4096,
    dataset_text_field=None,              # we're using messages format
    remove_unused_columns=False,
)

trainer = SFTTrainer(
    model=model,
    args=training_config,
    train_dataset=dataset,
    tokenizer=tokenizer,
    peft_config=lora_config,
)

trainer.train()
trainer.save_model("./gemma4-finetuned")

Memory requirements on E4B:

  • 4-bit quantized base model: ~4GB
  • LoRA adapters + optimizer states: ~6GB
  • Activations + gradient checkpointing: ~4GB
  • Total: ~14GB — fits on a 16GB consumer GPU

Evaluating Tool Call Accuracy

After fine-tuning, evaluation should measure the things that matter:

from transformers import pipeline

pipe = pipeline(
    "text-generation",
    model="./gemma4-finetuned",
    tokenizer=tokenizer,
    torch_dtype=torch.bfloat16,
    device_map="auto",
)

def evaluate_tool_calling(test_cases: list[dict]) -> dict:
    results = {"correct_tool": 0, "correct_args": 0, "no_hallucination": 0, "total": 0}

    for case in test_cases:
        response = pipe(case["messages"], max_new_tokens=256)[0]["generated_text"]

        # Check: did it call the right tool?
        expected_tool = case["expected_tool"]
        called_right_tool = expected_tool in response if expected_tool else "tool_calls" not in response

        # Check: were the arguments well-formed JSON?
        import json, re
        args_match = re.search(r'"arguments":\s*"({.*?})"', response)
        valid_args = False
        if args_match:
            try:
                json.loads(args_match.group(1).encode().decode('unicode_escape'))
                valid_args = True
            except:
                pass

        # Check: did it hallucinate a tool not in the schema?
        available_tools = case.get("available_tools", [])
        hallucinated = any(
            f'"name": "{t}"' in response
            for t in re.findall(r'"name":\s*"(\w+)"', response)
            if t not in available_tools
        )

        results["total"] += 1
        results["correct_tool"] += int(called_right_tool)
        results["correct_args"] += int(valid_args)
        results["no_hallucination"] += int(not hallucinated)

    return {k: v/results["total"] for k, v in results.items() if k != "total"}

metrics = evaluate_tool_calling(test_cases)
print(f"Correct tool selection: {metrics['correct_tool']:.1%}")
print(f"Valid argument JSON:    {metrics['correct_args']:.1%}")
print(f"No hallucinated tools:  {metrics['no_hallucination']:.1%}")


What Fine-Tuning Buys You Here

Gemma 4's base function-calling capability (86.4% agentic tool use on benchmarks) is already strong. Fine-tuning is worth doing when:

Your tool schema is unusual. If your tools have nested objects, enum parameters, or optional fields that the base model handles inconsistently, SFT on your schema stabilizes behavior.

You need edge case control. "When no tool is needed, answer directly" is a policy decision. "When the tool returns an error, do X not Y" is a policy decision. Fine-tuning encodes these policies reliably.

You have domain-specific tool semantics. A create_report function in your system means something specific to your domain. The base model doesn't know that.

You need multimodal tool outputs. If your pipeline includes tools that return images (charts, rendered documents, screenshots), the TRL multimodal support is the only path to training on those trajectories.


Exporting the LoRA Adapter

# Merge LoRA into base model for deployment
from peft import PeftModel

base_model = AutoModelForImageTextToText.from_pretrained(model_id, torch_dtype=torch.bfloat16)
merged_model = PeftModel.from_pretrained(base_model, "./gemma4-finetuned")
merged_model = merged_model.merge_and_unload()
merged_model.save_pretrained("./gemma4-merged")
tokenizer.save_pretrained("./gemma4-merged")

# Or keep as adapter for smaller disk footprint
# Just load the base + apply the adapter at inference time

The LoRA adapter is ~80MB. The base model is ~8GB. For deployment, keeping them separate is often more practical — you can swap adapters for different tool schemas without reloading the base model.


The Combination That Makes This Interesting

Gemma 4 with native function calling + thinking mode + multimodal tool outputs + fine-tuning for your specific schema is a stack that simply didn't exist six months ago in open-weight form.

An agent that reasons about image outputs from tools, fine-tuned to your internal APIs, running locally with no data leaving your infrastructure: that's the practical combination this tutorial enables.

The pieces are all available. This is how you connect them.