> 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/meru/install/intel.md).

# UnslothでIntel GPU上のLLMをファインチューニングする

Intel GPU上で大規模言語モデルを学習・ファインチューニングする方法を学びましょう。

Unslothを使って、ローカルのIntelデバイス上でLLMをファインチューニングできるようになりました！独自のカスタムモデルを学習するための始め方を、詳しく説明したガイドをご覧ください。

始める前に、以下が揃っていることを確認してください:

* **Intel GPU:** Data Center GPU Max Series、Arc Series、または Intel Ultra AIPC
* **OS:** Linux（Ubuntu 22.04+ 推奨）または Windows 11（推奨）
* **Windows のみ：** Intel oneAPI Base Toolkit 2025.2.1 をインストール（バージョン 2025.2.1 を選択）
* **Intel Graphics ドライバー:** Windows/Linux向けの最新推奨ドライバー
* **Python:** 3.10+

{% hint style="info" %}
Intel GPU に Unsloth Studio をインストールしますか？こちらを参照: [Studio インストールガイドの Intel GPU](/docs/jp/shii/studio/install.md#intel-gpus) インストーラーが自動で XPU PyTorch を選んだ場合の対処法と、固定する方法。
{% endhint %}

### Intelサポート付きでUnslothをビルド

{% stepper %}
{% step %}

#### 新しい conda 環境を作成（任意）

```bash
conda create -n unsloth-xpu python==3.10
conda activate unsloth-xpu
```

{% endstep %}

{% step %}

#### Unslothをインストール

```bash
git clone https://github.com/unslothai/unsloth.git
cd unsloth
pip install .[intel-gpu-torch290]
```

{% hint style="info" %}
Linuxのみ: インストール [vLLM](/docs/jp/ji-chu/inference-and-deployment/vllm-guide.md) (任意)\
vLLM もインストールできます。 [推論](/docs/jp/ji-chu/inference-and-deployment.md) そして [RL](/docs/jp/meru/reinforcement-learning-rl-guide.md)。次のガイドに従ってください: [vLLM のガイド](https://docs.vllm.ai/en/latest/getting_started/installation/gpu/#intel-xpu).
{% endhint %}
{% endstep %}

{% step %}

#### 環境を確認

```python
import torch
print(f"PyTorch version: {torch.__version__}")
print(f"XPU available: {torch.xpu.is_available()}")
print(f"XPU device count: {torch.xpu.device_count()}")
print(f"XPU device name: {torch.xpu.get_device_name(0)}")
```

{% endstep %}

{% step %}

#### ファインチューニングを開始します。

そのまま Unsloth を直接使うこともできます [ノートブック](/docs/jp/meru/unsloth-notebooks.md) または専用の [ファインチューニング](/docs/jp/meru/fine-tuning-llms-guide.md) または [強化学習](/docs/jp/meru/reinforcement-learning-rl-guide.md) ガイドをご覧ください。
{% endstep %}
{% endstepper %}

### Windowsのみ - ランタイム構成

管理者権限のコマンドプロンプトで、Windows レジストリの長いパスのサポートを有効にします:

```bash
powershell -Command "Set-ItemProperty -Path "HKLM:\\SYSTEM\\CurrentControlSet\\Control\\FileSystem" -Name "LongPathsEnabled" -Value 1
```

このコマンドは 1 台のマシンで一度だけ設定すれば十分です。毎回の実行前に設定する必要はありません。その後、

1. level-zero-win-sdk-1.20.2.zip を次からダウンロード: [GitHub](https://github.com/oneapi-src/level-zero/releases/tag/v1.20.2)
2. level-zero-win-sdk-1.20.2.zip を展開します
3. コマンドプロンプトで、conda 環境 unsloth-xpu の下で:

```bash
call "C:\Program Files (x86)\Intel\oneAPI\setvars.bat" -
set ZE_PATH=path\to\the\unzipped\level-zero-win-sdk-1.20.2
```

### 例1: SFT を使った QLoRA ファインチューニング

この例では、Intel GPU 上で 4-bit QLoRA を使って Qwen3-32B モデルをファインチューニングする方法を示します。QLoRA はメモリ要件を大幅に削減するため、一般向けハードウェアでも大規模モデルをファインチューニングできるようになります。

{% code expandable="true" %}

```python
from unsloth import FastLanguageModel, FastModel
from trl import SFTTrainer, SFTConfig
from datasets import load_dataset
max_seq_length = 2048 # 内部で RoPE スケーリングをサポートしているので、どれでも選べます！
# LAION データセットを取得
url = "https://huggingface.co/datasets/laion/OIG/resolve/main/unified_chip2.jsonl"
dataset = load_dataset("json", data_files = {"train" :
url}, split = "train")

# 高速ダウンロードとOOM回避のためにサポートしている 4bit 事前量子化モデル。
fourbit_models = [
"unsloth/Qwen3-32B-bnb-4bit",
"unsloth/Qwen3-14B-bnb-4bit",
"unsloth/Qwen3-8B-bnb-4bit",
"unsloth/Qwen3-4B-bnb-4bit",
"unsloth/Qwen3-1.7B-bnb-4bit",
"unsloth/Qwen3-0.6B-bnb-4bit",
# "unsloth/Qwen2.5-32B-bnb-4bit",
# "unsloth/Qwen2.5-14B-bnb-4bit",
# "unsloth/Qwen2.5-7B-bnb-4bit",
# "unsloth/Qwen2.5-3B-bnb-4bit",
# "unsloth/Qwen2.5-1.5B-bnb-4bit",
# "unsloth/Qwen2.5-0.5B-bnb-4bit",
# "unsloth/Llama-3.2-3B-bnb-4bit",
# "unsloth/Llama-3.2-1B-bnb-4bit",
# "unsloth/Llama-3.1-8B-bnb-4bit",
# "unsloth/Llama-3.1-70B-bnb-4bit",
# "unsloth/mistral-7b-bnb-4bit",
# "unsloth/Phi-4",
# "unsloth/Phi-3.5-mini-instruct",
# "unsloth/Phi-3-medium-4k-instruct",
# "unsloth/Phi-3-mini-4k-instruct",
# "unsloth/gemma-2-9b-bnb-4bit",
# "unsloth/gemma-2-27b-bnb-4bit",
] # 他のモデルは https://huggingface.co/unsloth で確認できます

model, tokenizer = FastLanguageModel.from_pretrained(
model_name = "unsloth/Qwen3-32B-bnb-4bit",
max_seq_length = max_seq_length,
load_in_4bit = True,
# token = "hf_...", # meta-llama/Llama-2-7b-hf のようなゲート付きモデルを使う場合に使用
)

model = FastLanguageModel.get_peft_model(
model,
r = 16, # 0より大きい任意の数を選択！ 推奨値は 8, 16, 32, 64, 128
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",
],
lora_alpha = 16,
lora_dropout = 0, # 任意の値に対応していますが、= 0 が最適化されています
bias = "none", # 任意の値をサポートしますが、"none" が最適化されています
use_gradient_checkpointing = "unsloth", # 非常に長いコンテキストでは True または "unsloth"
random_state = 3407,
use_rslora = False, # rank stabilized LoRA をサポートしています
loftq_config = None, # そしてLoftQ
)

trainer = SFTTrainer(
model = model,
tokenizer = tokenizer,
train_dataset = dataset,
dataset_text_field = "text",
max_seq_length = max_seq_length,
dataset_num_proc = 1, # Windows では推奨
packing = False, # 短いシーケンスでは学習を 5 倍高速化できます。
args = SFTConfig(
per_device_train_batch_size = 2,
gradient_accumulation_steps = 4,
warmup_steps = 5,
max_steps = 60,
learning_rate = 2e-4,
logging_steps = 1,
optim = "adamw_8bit",
weight_decay = 0.01,
lr_scheduler_type = "linear",
seed = 3407,
dataset_num_proc=1, # Windows では推奨
),
)

trainer.train()
```

{% endcode %}

### 例2: 強化学習 GRPO

GRPO は [強化学習](/docs/jp/meru/reinforcement-learning-rl-guide.md) 人間の好みに合わせて言語モデルを調整するための手法です。この例では、複数の報酬関数を使って、モデルに特定の XML 出力形式に従わせる方法を示します。

#### GRPO とは？

GRPO は従来の RLHF を次の点で改善します:

* グループベースの正規化を使って、より安定した学習を実現
* 複数の報酬関数をサポートし、多目的最適化を可能にする
* PPO よりメモリ効率が高い

{% code expandable="true" %}

```python
from unsloth import FastLanguageModel
import re
from trl import GRPOConfig, GRPOTrainer
from datasets import load_dataset, Dataset

max_seq_length = 1024  # 長い推論トレースでは増やしてもよい
lora_rank = 32  # ランクが大きいほど賢くなるが、遅くなる
max_prompt_length = 256

# データセットを読み込み、準備する
SYSTEM_PROMPT = """
次の形式で応答してください:
<reasoning>
...
</reasoning>
<answer>
...
</answer>
"""

XML_COT_FORMAT = """\
<reasoning>
{reasoning}
</reasoning>
<answer>
{answer}
</answer>
"""


def extract_xml_answer(text: str) -> str:
    answer = text.split("<answer>")[-1]
    answer = answer.split("</answer>")[0]
    return answer.strip()


def extract_hash_answer(text: str) -> str | None:
    if "####" not in text:
        return None
    return text.split("####")[1].strip()


# 1-shot プロンプト用に中間メッセージのコメントを外してください
def get_gsm8k_questions(split: str = "train") -> Dataset:
    data = load_dataset("openai/gsm8k", "main")[split]  # type: ignore
    data = data.map(
        lambda x: {  # type: ignore
            "prompt": [
                {"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user", "content": x["question"]},
            ],
            "answer": extract_hash_answer(x["answer"]),
        }
    )  # type: ignore
    return data  # type: ignore


# 報酬関数
def correctness_reward_func(prompts, completions, answer, **kwargs) -> list[float]:
    responses = [completion[0]["content"] for completion in completions]
    q = prompts[0][-1]["content"]
    extracted_responses = [extract_xml_answer(r) for r in responses]
    print(
        "-" * 20,
        f"質問:\n{q}",
        f"\n答え:\n{answer[0]}",
        f"\n応答:\n{responses[0]}",
        f"\n抽出結果:\n{extracted_responses[0]}",
    )
    return [2.0 if r == a else 0.0 for r, a in zip(extracted_responses, answer)]


def int_reward_func(completions, **kwargs) -> list[float]:
    responses = [completion[0]["content"] for completion in completions]
    extracted_responses = [extract_xml_answer(r) for r in responses]
    return [0.5 if r.isdigit() else 0.0 for r in extracted_responses]


def strict_format_reward_func(completions, **kwargs) -> list[float]:
    """補完結果が特定の形式になっているかを確認する報酬関数。"""
    pattern = r"^<reasoning>\n.*?\n</reasoning>\n<answer>\n.*?\n</answer>\n$"
    responses = [completion[0]["content"] for completion in completions]
    matches = [re.match(pattern, r) for r in responses]
    return [0.5 if match else 0.0 for match in matches]


def soft_format_reward_func(completions, **kwargs) -> list[float]:
    """補完結果が特定の形式になっているかを確認する報酬関数。"""
    pattern = r"<reasoning>.*?</reasoning>\s*<answer>.*?</answer>"
    responses = [completion[0]["content"] for completion in completions]
    matches = [re.match(pattern, r) for r in responses]
    return [0.5 if match else 0.0 for match in matches]


def count_xml(text: str) -> float:
    count = 0.0
    if text.count("<reasoning>\n") == 1:
        count += 0.125
    if text.count("\n</reasoning>\n") == 1:
        count += 0.125
    if text.count("\n<answer>\n") == 1:
        count += 0.125
    count -= len(text.split("\n</answer>\n")[-1]) * 0.001
    if text.count("\n</answer>") == 1:
        count += 0.125
    count -= (len(text.split("\n</answer>")[-1]) - 1) * 0.001
    return count


def xmlcount_reward_func(completions, **kwargs) -> list[float]:
    contents = [completion[0]["content"] for completion in completions]
    return [count_xml(c) for c in contents]


if __name__ == "__main__":
    model, tokenizer = FastLanguageModel.from_pretrained(
        model_name="unsloth/Qwen3-0.6B",
        max_seq_length=max_seq_length,
        load_in_4bit=False,  # LoRA 16bit の場合は False
        fast_inference=False,  # vLLM の高速推論を有効化
        max_lora_rank=lora_rank,
        gpu_memory_utilization=0.7,  # メモリ不足なら減らす
        device_map="xpu:0",
    )

    model = FastLanguageModel.get_peft_model(
        model,
        r=lora_rank,  # 0 より大きい任意の値を選択！ 推奨: 8, 16, 32, 64, 128
        target_modules=[
            "q_proj",
            "k_proj",
            "v_proj",
            "o_proj",
            "gate_proj",
            "up_proj",
            "down_proj",
        ],  # メモリ不足なら QKVO を削除
        lora_alpha=lora_rank,
        use_gradient_checkpointing="unsloth",  # 長文コンテキストのファインチューニングを有効化
        random_state=3407,
    )

    dataset = get_gsm8k_questions()

    training_args = GRPOConfig(
        learning_rate=5e-6,
        adam_beta1=0.9,
        adam_beta2=0.99,
        weight_decay=0.1,
        warmup_ratio=0.1,
        lr_scheduler_type="cosine",
        optim="adamw_torch",
        logging_steps=1,
        per_device_train_batch_size=1,
        gradient_accumulation_steps=1,  # より滑らかな学習のために 4 へ増やす
        num_generations=4,  # メモリ不足なら減らす
        max_prompt_length=max_prompt_length,
        max_completion_length=max_seq_length - max_prompt_length,
        # num_train_epochs=1,  # 完全な学習実行では 1 に設定
        max_steps=20,
        save_steps=250,
        max_grad_norm=0.1,
        report_to="none",  # Weights & Biases を使用できます
        output_dir="outputs",
    )

    trainer = GRPOTrainer(
        model=model,
        processing_class=tokenizer,
        reward_funcs=[
            xmlcount_reward_func,
            soft_format_reward_func,
            strict_format_reward_func,
            int_reward_func,
            correctness_reward_func,
        ],
        args=training_args,
        train_dataset=dataset,
        dataset_num_proc=1,  # Windows では推奨
    )

    trainer.train()

```

{% endcode %}

## トラブルシューティング

### メモリ不足 (OOM) エラー

メモリが不足した場合は、次の解決策を試してください:

1. **バッチサイズを下げる:** 下げる `per_device_train_batch_size`.
2. **より小さなモデルを使う:** メモリ要件を減らすために、より小さなモデルから始めてください。
3. **シーケンス長を短くする:** 下げる `max_seq_length`.
4. **LoRA ランクを下げる:** 次を使います: `r=8` の代わりに `r=16` または `r=32`.
5. **GRPO では、生成数を減らす:** 下げる `num_generations`.

### (Windowsのみ) Intel Ultra AIPC の iGPU 共有メモリ

Windows で最新の GPU ドライバーを使用している Intel Ultra AIPC では、統合 GPU の共有 GPU メモリは通常、既定で **57%** のシステムメモリに設定されています。より大きなモデル（例: **Qwen3-32B**）や、より長い最大シーケンス長、より大きいバッチサイズ、より大きな LoRA ランクの LoRA アダプターなどをファインチューニングで使用する場合は、iGPU に割り当てるシステムメモリの割合を増やすことで、利用可能な VRAM を増やせます。

レジストリを変更することで調整できます:

* パス: `Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\GraphicsDrivers\MemoryManager`
* 変更するキー:\
  `SystemPartitionCommitLimitPercentage` (より大きな割合に設定)


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://unsloth.ai/docs/jp/meru/install/intel.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
