> For the complete documentation index, see [llms.txt](https://unsloth.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://unsloth.ai/docs/jp/ji-ben/vision-fine-tuning.md).

# ビジョンのファインチューニング

ビジョンモデルをファインチューニングすると、物体／動きの検出など、通常のLLMでは得意でない特定のタスクでモデルの性能を高められます。 **また、** [**VLMをRLで**](/docs/jp/meru/reinforcement-learning-rl-guide/vision-reinforcement-learning-vlm-rl.md)**.** ビジョンのファインチューニング向けの無料ノートブックを多数用意しています:

* [**Qwen3-VL**](/docs/jp/moderu/tutorials/qwen3-how-to-run-and-fine-tune/qwen3-vl-how-to-run-and-fine-tune.md) **(8B) ビジョン:** [**ノートブック**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_VL_\(8B\)-Vision.ipynb)
* [**Ministral 3**](/docs/jp/moderu/tutorials/ministral-3.md): 一般的なQ\&A向けのビジョンファインチューニング: [ノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Pixtral_\(12B\)-Vision.ipynb)\
  一般的なQ\&Aデータセットに、より専門的なデータセットを組み合わせることで、ファインチューニング時にベースモデルの能力を忘れにくくできます。
* **Gemma 3 (4B) ビジョン:** [ノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3_\(4B\)-Vision.ipynb)
* **Llama 3.2 Vision** 放射線画像診断向けのファインチューニング: [ノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Llama3.2_\(11B\)-Vision.ipynb)\
  X線、CTスキャン、超音波をより速く分析するのに、医療従事者をどう支援できるか。
* **Qwen2.5 VL** 手書きをLaTeXに変換するためのファインチューニング: [ノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen2.5_VL_\(7B\)-Vision.ipynb)\
  これにより、複雑な数式を手入力することなく、LaTeXとして簡単に転記できます。

{% hint style="info" %}
データセット内の画像サイズがすべて同じであるようにするのが最善です。学習に時間がかかりすぎたり、リソースを使いすぎたりしないよう、300〜1000pxの寸法を使用してください。
{% endhint %}

### ビジョン／テキストのみのファインチューニングを無効化

ビジョンモデルをファインチューニングするために、今ではモデルのどの部分をファインチューニングするかを選択できるようになりました。ビジョン層のみ、言語層のみ、あるいはアテンション／MLP層のみを選択できます。デフォルトではすべて有効になっています。

```python
model = FastVisionModel.get_peft_model(
    model,
    finetune_vision_layers     = True, # vision レイヤーをファインチューニングしないなら False
    finetune_language_layers   = True, # language レイヤーをファインチューニングしないなら False
    finetune_attention_modules = True, # attention レイヤーをファインチューニングしないなら False
    finetune_mlp_modules       = True, # MLP レイヤーをファインチューニングしないなら False

    r = 16,                           # 大きいほど精度は高くなるが、過学習する可能性あり
    lora_alpha = 16,                  # 少なくとも alpha == r を推奨
    lora_dropout = 0,
    bias = "none",
    random_state = 3407,
    use_rslora = False,               # rank stabilized LoRA をサポートしています
    loftq_config = None,               # そして LoftQ も
    target_modules = "all-linear",    # 今は任意です! 必要ならリストを指定できます
    modules_to_save=[
        "lm_head",
        "embed_tokens",
    ],
)
```

### ビジョン用データコレーター

ビジョン用データセット専用の特別なデータコレーターがあります:

{% code overflow="wrap" %}

```python
from unsloth.trainer import UnslothVisionDataCollator
from trl import SFTTrainer, SFTConfig
trainer = SFTTrainer(
    model = model,
    tokenizer = tokenizer,
    data_collator = UnslothVisionDataCollator(model, tokenizer),
    train_dataset = dataset,
    args = SFTConfig(...),
)
```

{% endcode %}

そして、データコレーターの引数は次のとおりです:

{% code expandable="true" %}

```python
class UnslothVisionDataCollator:
def __init__(
self,
model,
processor,
max_seq_length  = None, # [オプション] これは `FastVisionModel.from_pretrained(max_seq_length = ...)` から自動取得します
formatting_func = None, # テキストを変換する関数
resize = "min", # (10, 10) または "min" でモデルのデフォルト image_size に合わせてリサイズ、または "max"
                # リサイズせず、画像をそのまま保持
ignore_index = -100, # [オプション] デフォルトは -100

# from unsloth.chat_templates import train_on_responses_only
# trainer = train_on_responses_only(
#     trainer,
#     instruction_part = "<|start_header_id|>user<|end_header_id|>\n\n",
#     response_part = "<|start_header_id|>assistant<|end_header_id|>\n\n",
# )
train_on_responses_only = False, # LLMの train_on_responses_only と同等
instruction_part = None, # train_on_responses_only(instruction_part = ...) と同等
response_part    = None, # train_on_responses_only(response_part = ...) と同等
force_match      = True, # 改行も一致させます！

num_proc         = None, # [オプション] GPUの数を自動選択します
completion_only_loss = True, # [オプション] パディングされたビジョントークンを無視します - 常に True にすべきです！
pad_to_multiple_of = None, # [オプション] データコレーターのパディング用
resize_dimension = 0, # 0、1、'max'、'min' が指定可能
                      # （max は高さと幅の最大値に基づいてリサイズし、min は最小サイズ、0 は最初の次元など）
snap_to_patch_size = False, # [オプション] 画像をパッチサイズの倍数に強制します
)
```

{% endcode %}

### マルチ画像学習

マルチ画像でモデルをファインチューニングまたは学習するために、最も簡単な変更は次の置き換えです:

```python
ds_converted = ds.map(
    convert_to_conversation,
)
```

を次のように:

```python
ds_converted = [convert_to_conversation(sample) for sample in dataset]
```

map を使うと、データセットの標準化と Arrow の処理ルールが適用されますが、これらは厳密で定義がより複雑になることがあります。

### ビジョンファインチューニング用データセット

ビジョンまたはマルチモーダルモデルをファインチューニングするためのデータセットは、標準的な質問と回答のペアに似ています [datasets ](/docs/jp/meru/fine-tuning-llms-guide/datasets-guide.md)が、今回は画像入力も含まれます。例えば、 [Llama 3.2 Vision ノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Llama3.2_\(11B\)-Vision.ipynb#scrollTo=vITh0KVJ10qX) では放射線画像のケースを使って、AIが医療従事者によるX線、CTスキャン、超音波の分析をより効率的に支援できることを示しています。

ROCO放射線画像データセットのサンプル版を使用します。データセットにアクセスできます [こちら](https://www.google.com/url?q=https%3A%2F%2Fhuggingface.co%2Fdatasets%2Funsloth%2FRadiology_mini)。このデータセットには、医療状態や疾患を示すX線、CTスキャン、超音波が含まれています。各画像には、それを説明する専門家によるキャプションが付いています。目的は、VLMをファインチューニングして、医療従事者にとって有用な分析ツールにすることです。

データセットを見て、最初の例が何を示しているか確認しましょう:

```
Dataset({
    features: ['image', 'image_id', 'caption', 'cui'],
    num_rows: 1978
})
```

| 画像                                                                                                                                  | キャプション                                        |
| ----------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- |
| <div><figure><img src="/files/9743fe5d359738fca09f4ad17cfefb80e9ba915d" alt="" width="164"><figcaption></figcaption></figure></div> | パノラマX線写真は、右後方上顎に骨溶解性病変を示し、上顎洞底の吸収を伴っています（矢印）。 |

データセットを整形するには、すべてのビジョンファインチューニングタスクを次のようにフォーマットする必要があります:

```python
[
{ "role": "user",
  "content": [{"type": "text",  "text": instruction}, {"type": "image", "image": image} ]
},
{ "role": "assistant",
  "content": [{"type": "text",  "text": answer} ]
},
]
```

VLMに放射線画像の専門家であるよう求める、独自の指示文を作成します。また、指示が1つだけでなく、複数ターンを追加して動的な会話にすることもできます。

{% code expandable="true" %}

```notebook-python
instruction = "あなたは放射線画像診断の専門家です。この画像で見えるものを正確に記述してください。"

def convert_to_conversation(sample):
    conversation = [
        { "role": "user",
          "content" : [
            {"type" : "text",  "text"  : instruction},
            {"type" : "image", "image" : sample["image"]} ]
        },
        { "role" : "assistant",
          "content" : [
            {"type" : "text",  "text"  : sample["caption"]} ]
        },
    ]
    return { "messages" : conversation }
pass
```

{% endcode %}

ファインチューニング用にデータセットを「正しい」形式へ変換しましょう:

```notebook-python
converted_dataset = [convert_to_conversation(sample) for sample in dataset]
```

最初の例は次のような構造になります:

```notebook-python
converted_dataset[0]
```

{% code overflow="wrap" %}

```
{'messages': [{'role': 'user',
   'content': [{'type': 'text',
     'text': 'あなたは放射線画像診断の専門家です。この画像で見えるものを正確に記述してください。'},
    {'type': 'image',
     'image': <PIL.PngImagePlugin.PngImageFile image mode=L size=657x442>}]},
  {'role': 'assistant',
   'content': [{'type': 'text',
     'text': 'パノラマX線写真は、右後方上顎に骨溶解性病変を示し、上顎洞底の吸収を伴っています（矢印）。'}]}]}
```

{% endcode %}

ファインチューニングを行う前に、もしかするとビジョンモデルはすでに画像の解析方法を知っているかもしれません。これが当てはまるか確認しましょう！

{% code expandable="true" %}

```notebook-python
FastVisionModel.for_inference(model) # 推論を有効化！

image = dataset[0]["image"]
instruction = "あなたは放射線画像診断の専門家です。この画像で見えるものを正確に記述してください。"

messages = [
    {"role": "user", "content": [
        {"type": "image"},
        {"type": "text", "text": instruction}
    ]}
]
input_text = tokenizer.apply_chat_template(messages, add_generation_prompt = True)
inputs = tokenizer(
    image,
    input_text,
    add_special_tokens = False,
    return_tensors = "pt",
).to("cuda")

from transformers import TextStreamer
text_streamer = TextStreamer(tokenizer, skip_prompt = True)
_ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 128,
                   use_cache = True, temperature = 1.5, min_p = 0.1)
```

{% endcode %}

そして結果は:

```
このX線写真は、上顎と下顎の歯列を示すパノラマビュー、具体的にはオルソパントモグラム（OPG）のようです。

* パノラマX線写真は正常な歯科構造を示しています。
* 上顎右側に異常領域があり、これは透過像として見える骨領域で、上顎洞に対応しています。

**主な観察事項**

* 左上の歯の間の骨は比較的X線不透過です。
* 画像の上に2本の大きな矢印があり、この領域を詳しく調べる必要があることを示唆しています。1本は左側にあり、もう1本は右側にあります。しかし、
```

詳細は、のデータセットセクションをご覧ください [こちらのノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Llama3.2_\(11B\)-Vision.ipynb#scrollTo=vITh0KVJ10qX).

### &#x20;:mag\_right:ビジョンモデル、VLM向けにアシスタント応答のみで学習する

言語モデルでは、 `from unsloth.chat_templates import train_on_responses_only` を前述のように使用できます。ビジョンモデルでは、追加の引数を `UnslothVisionDataCollator` の一部として使用してください。 [#vision-data-collator](#vision-data-collator "mention") ビジョンデータコレーターの使い方の詳細は、こちらをご覧ください。

{% code overflow="wrap" %}

```python
class UnslothVisionDataCollator:
def __init__(
    self,
    ...
    # from unsloth.chat_templates import train_on_responses_only
    # trainer = train_on_responses_only(
    #     trainer,
    #     instruction_part = "<|start_header_id|>user<|end_header_id|>\n\n",
    #     response_part = "<|start_header_id|>assistant<|end_header_id|>\n\n",
    # )
    train_on_responses_only = False, # LLMの train_on_responses_only と同等
    instruction_part = None, # train_on_responses_only(instruction_part = ...) と同等
    response_part    = None, # train_on_responses_only(response_part = ...) と同等
    force_match      = True, # 改行も一致させます！
)
```

{% endcode %}

たとえば Llama 3.2 Vision では:

```python
UnslothVisionDataCollator(
    model, tokenizer,
    ...
    train_on_responses_only = True,
    instruction_part = "<|start_header_id|>user<|end_header_id|>\n\n",
    response_part = "<|start_header_id|>assistant<|end_header_id|>\n\n",
    ...
)
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://unsloth.ai/docs/jp/ji-ben/vision-fine-tuning.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
