Google発の最新オープンモデル「Gemma 4」徹底解説!Gemma 3からの進化点と実践コード

に公開

Google DeepMindから、オープンモデルの最新世代となるGemma 4がリリースされました。
「パラメータあたりの知能」において前例のないレベルに達したとされており、特に推論能力やエージェントとしての活用能力が劇的に向上しています。

本記事では、Gemma 4の概要と、前モデルであるGemma 3と何が違うのかを比較しながら分かりやすく解説します。また、実際に動かすためのPythonコードも紹介します。


1. Gemma 4のラインナップ

Gemma 4ファミリーは、特定のハードウェア要件や用途に合わせて調整された3つの異なるアーキテクチャ(4つのサイズ)で構成されています。それぞれの主な差別点は、ターゲットとするデバイス推論速度(スループット)、および対応するデータ形式(モダリティ)にあります。

E2B / E4B (Effective 2B / 4B)

これらは「小サイズ」モデルに分類され、モバイルデバイスやエッジデバイス(Google Pixel、Chrome、Raspberry Piなど)での実行に最適化されています。

  • アーキテクチャの特徴: 「E」は「Effective(有効)」パラメータを意味します。Per-Layer Embeddings (PLE) という技術を採用しており、モデルにレイヤーを追加する代わりに、各デコーダーレイヤーに独自の小さな埋め込みテーブルを持たせることで、パラメータ効率を最大化しています。
  • 音声入力への対応: Gemma 4ファミリーの中で唯一、音声入力にネイティブ対応しています。これにより、デバイス上での音声認識や翻訳が可能です。
  • リソース消費: 推論時には有効な20億/40億パラメータ分のみをアクティブにするため、RAMの節約やバッテリー消費の抑制に適しています。
  • コンテキストウィンドウ: 128,000トークンに対応しています。

31B Dense

このモデルは「高密度」モデルであり、サーバーグレードのパフォーマンスを必要とするタスクや、ローカルの強力なワークステーションでの実行を想定しています。

  • アーキテクチャの特徴: パラメータを間引かない高密度(Dense)モデルであり、Gemma 4シリーズの中で最も高い品質と推論能力を提供します。ファインチューニングのベースとしても強力な基盤となります。
  • コンテキストウィンドウ: 最大256,000トークンの長いコンテキストをサポートしており、大規模なドキュメントやリポジトリの処理に適しています。
  • 対応モダリティ: テキストと画像に対応していますが、音声には対応していません。

26B A4B MoE (Mixture-of-Experts)

このモデルは高スループット(処理速度)と高度な推論の両立を目的とした混合エキスパート(MoE)モデルです。

  • アーキテクチャの特徴: 「A」は「Active(アクティブ)」パラメータを指します。総パラメータ数は約252億ですが、推論時にはトークンごとに約38億パラメータのみをアクティブにします。
  • 推論速度: アクティブなパラメータが少ないため、31B Denseと比較して**非常に高速な推論(トークン/秒)**が可能です。
  • メモリ要件: 高速なルーティングを行うため、推論時には260億のパラメータすべてをメモリに読み込む必要があります。そのため、メモリ消費量は4Bモデルよりも31B Denseに近いものとなります。
  • コンテキストウィンドウ: 31Bと同様に256,000トークンをサポートしています。

差別点のまとめ比較表

プロパティ E2B / E4B 31B Dense 26B A4B MoE
主な用途 モバイル・エッジ・音声 最高品質・サーバー 高速推論・スループット
アクティブパラメータ 2B / 4B 30.7B 3.8B
音声対応 あり なし なし
コンテキスト長 128K 256K 256K
メモリ効率技術 PLE - MoE

2. Gemma 3との主な違い

Gemma 3から進化した重要なポイントは大きく分けて4つあります。

① コンテキストウィンドウの拡大

Gemma 3では最大128,000トークン(1Bは32,000)でしたが、Gemma 4では中・大型モデル(26B/31B)において256,000トークンまで拡張されました。これにより、より長大なドキュメントやコードリポジトリ全体を一度に処理できるようになっています。

② 「音声」と「動画」へのネイティブ対応

Gemma 3はテキストと画像のマルチモーダル対応でしたが、Gemma 4ではさらに進化しています。

  • 音声: E2BおよびE4Bモデルでは音声入力にネイティブ対応しており、Speech-to-Textや翻訳が可能です。
  • 動画: フレームシーケンスを処理することで、動画の内容理解もサポートしています。

③ 組み込みの「思考モード (Thinking Mode)」

Gemma 4の最大の特徴の一つが、思考モードのネイティブサポートです。
回答を生成する前に、モデルがステップバイステップで推論(内部的な思考プロセス)を行うことができます。これにより、数学や複雑なロジックを必要とするタスクの精度が大幅に向上しました。


3. ベンチマーク比較

Gemma 3 27Bと比較しても、Gemma 4は多くの指標で凌駕しています。

特に数学(AIME)やコーディング(LiveCodeBench)の伸びが顕著であり、推論能力が別次元に到達していることがわかります。


4. まとめ:今すぐ試すには

Gemma 4はApache 2.0ライセンスで公開されており、商用利用も可能です。

  • モデルの入手: Hugging Face, Kaggle, Ollamaからダウンロード可能。
  • 実行ツール: Transformers, llama.cpp, vLLM, MLXなど、主要なツールがリリース初日から対応しています。

Google AI StudioやスマホであればGoogle AI Edge Galleryで試すことが可能です。


5. 挙動の確認 (Pythonコード例)

google/gemma-4-E2B-itであれば、Google ColabのT4(無料枠)スペックで十分に動かすことができます。

基本的なテキスト生成

# Gemma 4を動かすために最新版のtransformersに更新
!pip install --upgrade transformers

import transformers
print(f"Transformers version: {transformers.__version__}")
出力結果
Transformers version: 5.5.0
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

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

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    device_map="auto",
    torch_dtype=torch.bfloat16,
)

messages = [
    {"role": "user", "content": "フィジカルAIについて説明してください"},
]

inputs = tokenizer.apply_chat_template(
    messages, return_tensors="pt", add_generation_prompt=True
).to(model.device)

outputs = model.generate(**inputs, max_new_tokens=512)

prompt_length = inputs["input_ids"].shape[-1]
response = tokenizer.decode(outputs[0][prompt_length:], skip_special_tokens=True)
print(response)
出力結果
 config.json:  4.95k/? [00:00<00:00, 424kB/s]tokenizer_config.json:  2.07k/? [00:00<00:00, 209kB/s]tokenizer.json: 100% 32.2M/32.2M [00:00<00:00, 94.4MB/s]chat_template.jinja:  11.9k/? [00:00<00:00, 1.26MB/s]`torch_dtype` is deprecated! Use `dtype` instead!
model.safetensors: 100% 10.2G/10.2G [01:54<00:00, 59.2MB/s]Loading weights: 100% 2011/2011 [00:41<00:00, 508.50it/s]generation_config.json: 100% 208/208 [00:00<00:00, 22.3kB/s]## フィジカルAI(Physical AI)とは?

**フィジカルAI(Physical AI)**とは、**AI技術を物理的な世界(現実世界)に適用し、物理的なタスクやシステムを自律的、あるいは高度に制御・最適化する**ことを目指すAIの分野です。

従来のAIが主にデータ処理、画像認識、自然言語処理といった「デジタルな世界」でのタスクに焦点を当ててきたのに対し、フィジカルAIは、AIが「**行動し、物理的な世界に影響を与える**」ことを目指します。

簡単に言えば、「**考えて、実行する**」AI、あるいは「**知能を物理的なロボットやシステムに埋め込む**」AIと理解できます。

---

### 1. フィジカルAIの主な特徴

フィジカルAIが目指すのは、単なるシミュレーションや推奨ではなく、**現実世界での具体的な成果**です。

* **物理的な相互作用(Physical Interaction):** ロボットアームを動かす、物理的な材料を操作する、環境内のセンサーから情報を取得し、物理的なアクションを起こすなど、現実世界との直接的なやり取りが中心になります。
* **自律性(Autonomy):** 人間からの継続的な指示なしに、目標を設定し、障害物を回避しながらタスクを計画・実行する能力が求められます。
* **現実世界への適応(Adaptability):** 予期せぬ環境の変化(例えば、床が滑る、物体が移動する)に対して、リアルタイムで判断し、行動を修正する能力が必要です。
* **センサーとアクチュエータの統合:** カメラ、LiDAR、触覚センサーといった「感覚(センサー)」から得た情報を、モーターやアクチュエータ(実行装置)に変換して物理的な動作に結びつける統合能力が重要になります。

---

### 2. フィジカルAIが活用される分野

フィジカルAIの技術は、物理的な制約や複雑性が高い分野で大きなブレイクスルーをもたらします。

#### ① ロボティクスと自動化
* **汎用ロボット:** 人間と同じように多様な物理的タスク(家事、製造ラインでの組み立て、災害現場での救助など)を遂行できるロボット。
* **精密操作:** 繊細な部品の組み立て

思考モード(Thinking Mode)の活用とストリーミング

モデルの思考機能を使用して応答を生成するには、enable_thinking=Trueを渡します。プロセッサは正しい思考トークンをプロンプトに挿入し、応答する前にモデルに思考を指示します。

MODEL_ID = "google/gemma-4-E2B-it"

from transformers import AutoProcessor, AutoModelForMultimodalLM, TextStreamer

model = AutoModelForMultimodalLM.from_pretrained(MODEL_ID, dtype="auto", device_map="auto")
processor = AutoProcessor.from_pretrained(MODEL_ID)

message = [
    {
        "role": "user", "content": "水の化学式は何ですか?"
    }
]

text = processor.apply_chat_template(message, tokenize=False, add_generation_prompt=True, enable_thinking=True)
inputs = processor(text=text, return_tensors="pt").to(model.device)

streamer = TextStreamer(processor)
outputs = model.generate(**inputs, streamer=streamer, max_new_tokens=1024)
出力結果
<bos><|turn>system
<|think|><turn|>
<|turn>user
水の化学式は何ですか?<turn|>
<|turn>model
<|channel>thought
Thinking Process:

1.  **Analyze the Request:** The user is asking: "水の化学式は何ですか?" (What is the chemical formula of water?)
2.  **Identify the Subject:** The subject is "water" (水).
3.  **Determine the Chemical Formula:** The chemical formula for water is $\text{H}_2\text{O}$.
4.  **Formulate the Answer (in Japanese):**
    *   State the chemical formula clearly.
    *   (Optional but helpful) Briefly explain what the formula means (Hydrogen, Oxygen).
5.  **Review and Refine:** The answer should be accurate and directly address the question.

    *   *Draft:* 水の化学式は $\text{H}_2\text{O}$ です。
6.  **Final Output Generation.** (This leads to the provided answer.)<channel|>水の化学式は **$\text{H}_2\text{O}$** です。

これは、水分子が水素原子(H)2つと酸素原子(O)1つから構成されていることを示しています。<turn|>

テキストが生成されると、応答には推論ブロックと、特別なトークンで区切られた最終的な回答の両方が含まれます。parse_responseユーティリティを使用して、それらをthinkingとanswerを含む辞書に簡単に抽出できます。

response = processor.decode(outputs[0][input_len:], skip_special_tokens=False)
result = processor.parse_response(response)

for key, value in result.items():
  if key == "role":
    print(f"Role: {value}")
  elif key == "thinking":
    print(f"\n=== Thoughts ===\n{value}")
  elif key == "content":
    print(f"\n=== Answer ===\n{value}")
  elif key == "tool_calls":
    print(f"\n=== Tool Calls ===\n{value}")
  else:
    print(f"\n{key}: {value}...\n")
出力結果
Role: assistant

=== Thoughts ===
Thinking Process:

1.  **Analyze the Request:** The user is asking: "水の化学式は何ですか?" (What is the chemical formula of water?)
2.  **Identify the Subject:** The subject is "water" (水).
3.  **Determine the Chemical Formula:** The chemical formula for water is $\text{H}_2\text{O}$.
4.  **Formulate the Answer (in Japanese):**
    *   State the chemical formula clearly.
    *   (Optional but helpful) Briefly explain what the formula means (Hydrogen, Oxygen).
5.  **Review and Refine:** The answer should be accurate and directly address the question.

    *   *Draft:* 水の化学式は $\text{H}_2\text{O}$ です。
6.  **Final Output Generation.** (This leads to the provided answer.)

=== Answer ===
水の化学式は **$\text{H}_2\text{O}$** です。

これは、水分子が水素原子(H)2つと酸素原子(O)1つから構成されていることを示しています。

画像の入力(マルチモーダル処理)

画像を入力とし、その内容について推論させることも可能です。

from PIL import Image
import matplotlib.pyplot as plt

prompt = "この画像には何が写っていますか?"
image_url = "https://raw.githubusercontent.com/google-gemma/cookbook/refs/heads/main/Demos/sample-data/GoldenGate.png"

# 画像のダウンロード
!wget -q {image_url} -O image.png
image = Image.open("image.png")

# 画像の表示
print("=== Downloaded image ===")
fig, ax = plt.subplots(1, 1, figsize=(5, 5))
ax.imshow(image)
ax.set_title("Image 1")
ax.axis("off")
plt.tight_layout()
plt.show()

message = [
    {
        "role": "user", "content": [
          {"type": "image"},
          {"type": "text", "text": prompt}
        ]
    }
]

text = processor.apply_chat_template(message, tokenize=False, add_generation_prompt=True, enable_thinking=True)
inputs = processor(text=text, images=image, return_tensors="pt").to(model.device)
input_len = inputs["input_ids"].shape[-1]

outputs = model.generate(**inputs, max_new_tokens=1024)
response = processor.decode(outputs[0][input_len:], skip_special_tokens=False)

# 出力をパースして思考プロセスと回答を分離
result = processor.parse_response(response)

for key, value in result.items():
    if key == "role":
        print(f"Role: {value}")
    elif key == "thinking":
        print(f"\n=== Thoughts ===\n{value}")
    elif key == "content":
        print(f"\n=== Answer ===\n{value}")
    elif key == "tool_calls":
        print(f"\n=== Tool Calls ===\n{value}")
    else:
        print(f"\n{key}: {value}...\n")
出力結果
 === Downloaded image ===
Role: assistant

=== Thoughts ===
Here's a thinking process to arrive at the suggested answer:

1.  **Analyze the Request:** The user provided an image and asked, "この画像は何を表していますか?" (What does this image represent?). The image also has some unusual characters/text at the very bottom (`ernāzi`), which should be ignored for the core identification task, but the main focus is the visual content.

2.  **Analyze the Image (Visual Inventory):**
    *   **Dominant Structure:** A very large suspension bridge with distinctive red/orange towers and cables. This is immediately recognizable as the Golden Gate Bridge.
    *   **Setting:** Water (a bay or strait), hills/mountains in the background, and a shoreline/landmass in the foreground.
    *   **Foreground Detail:** A dark, rocky outcrop/island in the water.
    *   **Atmosphere/Lighting:** Clear, bright, sunny day (clear blue sky).
    *   **Context Clues (Implied Location):** Based on the Golden Gate Bridge, the location is San Francisco/Marin County, California.

3.  **Identify the Subject:** The image clearly depicts the Golden Gate Bridge spanning the San Francisco Bay.

4.  **Formulate the Answer (in Japanese, as requested):**

    *   *Draft 1 (Literal Identification):* これはゴールデンゲートブリッジです。サンフランシスコの景色です。 (This is the Golden Gate Bridge. It is a view of San Francisco.)
    *   *Refinement (Adding Detail/Context):* Make the description more comprehensive and engaging. Mention the location and the type of structure.

5.  **Final Japanese Output Construction (Polishing the Tone):** (This leads to the suggested response.)

    *   *Start with the main identification.*
    *   *Describe the scene.*
    *   *Provide context (where it is).*

6.  **Review against the original request:** Does the answer accurately describe the image? Yes. (Self-Correction: Ensure the Japanese is natural.) (The final output is good.)

=== Answer ===
この画像は、**ゴールデンゲートブリッジ (Golden Gate Bridge)** を表しています。

これは、アメリカ合衆国カリフォルニア州サンフランシスコの象徴的なランドマークであり、サンフランシスコ湾を架橋している壮大な吊り橋です。

**画像から読み取れる要素:**

* **主要な構造物:** 赤い塔とケーブルを持つ巨大な吊り橋(ゴールデンゲートブリッジ)。
* **背景:** 湾や海、遠くの山々が見えます。
* **前景:** 水面に浮かぶ岩や、岸辺の一部が写っています。

ゴールデンゲートブリッジは、その美しい赤い色と、霧の多い日の対比で世界的に有名です。


参考資料:

Discussion