> 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/moderu/tutorials/deepseek-r1-how-to-run-locally.md).

# DeepSeek-R1: ローカルでの実行方法

llama.cppを使ってDeepSeek-R1用の1.58ビットDynamic Quantを実行する方法のガイド。

{% hint style="success" %}
ご覧ください <https://docs.unsloth.ai/basics/deepseek-r1-0528-how-to-run-locally> 更新版の DeepSeek R1-0528（2025年5月28日版）について
{% endhint %}

## llama.cpp を使用する（推奨）

1. 〜を忘れないでください `<｜User｜>` そして `<｜Assistant｜>` トークン！ - あるいはチャットテンプレートフォーマッタを使ってください
2. 最新の `llama.cpp` 場所: [github.com/ggml-org/llama.cpp](https://github.com/ggml-org/llama.cpp)。以下のビルド手順に従うこともできます。 **Apple Mac / Metalデバイスの場合**、次を設定します `-DGGML_CUDA=OFF` その後は通常どおり続けてください。Metalサポートはデフォルトで有効です。

```bash
apt-get update
apt-get install pciutils build-essential cmake curl libcurl4-openssl-dev -y
git clone https://github.com/ggml-org/llama.cpp
cmake llama.cpp -B llama.cpp/build \
    -DBUILD_SHARED_LIBS=ON -DGGML_CUDA=ON -DLLAMA_CURL=ON
cmake --build llama.cpp/build --config Release -j --clean-first --target llama-quantize llama-cli llama-gguf-split
cp llama.cpp/build/bin/llama-* llama.cpp
```

3. 使用するのが最適です `--min-p 0.05` 非常にまれなトークン予測を抑えるためです。特に 1.58bit モデルではこれがうまく機能することがわかりました。
4. 以下からモデルをダウンロードします:

```python
# pip install huggingface_hub hf_transfer
# import os # より高速なダウンロードのためのオプション
# os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"

from huggingface_hub import snapshot_download
snapshot_download(
  repo_id = "unsloth/DeepSeek-R1-GGUF",
  local_dir = "DeepSeek-R1-GGUF",
  allow_patterns = ["*UD-IQ1_S*"], # 1.58bit 用に量子化タイプ UD-IQ1_S を選択
)
```

6. Q4\_0 K 量子化キャッシュの例 **注意: -no-cnv は自動会話モードを無効にします**

```bash
./llama.cpp/llama-cli \
    --model DeepSeek-R1-GGUF/DeepSeek-R1-UD-IQ1_S/DeepSeek-R1-UD-IQ1_S-00001-of-00003.gguf \\
    --cache-type-k q4_0 \\
    -no-cnv --prio 2 \\
    --temp 0.6 \
    --ctx-size 8192 \\
    --seed 3407 \\
    --prompt "<｜User｜>1+1は何ですか？<｜Assistant｜>"
```

出力例:

```txt
 <think>
 よし、1+1 がいくつか考えないと。うーん、どこから始めればいいんだろう？ 学校では数を足すのは基本だと習ったけれど、ちゃんと理解しているか確認したい。
 考えてみよう、1+1。つまり、1つの物にもう1つを足すわけだ。たとえばリンゴにもう1つリンゴを足すようなものかな。1個のリンゴがあって、誰かがもう1個くれたら、今は2個のリンゴがある。だから、1+1 は 2 になるはずだ。納得できる。
 でも、数学は時々ややこしいことがある。ほかの答えになる可能性はあるだろうか？ たとえば別の数体系なら？ でも、この質問は素直で、通常の数を使っていると思う。2進数や16進数などではないし。
 算数では、加算は量をまとめることだというのも覚えている。だから、1 が 2 つあれば、それを合わせると合計は 2 になる。うん、それで合っていそうだ。
 1+1 が 2 にならない場面はあるだろうか？ 思いつかない...
```

4. GPU（たとえば RTX 4090）に 24GB あれば、複数の層を GPU にオフロードしてより高速に処理できます。複数の GPU があるなら、さらに多くの層をオフロードできるはずです。

```bash
./llama.cpp/llama-cli \
    --model DeepSeek-R1-GGUF/DeepSeek-R1-UD-IQ1_S/DeepSeek-R1-UD-IQ1_S-00001-of-00003.gguf \\
    --cache-type-k q4_0 \\
    -no-cnv --prio 2 \\
    --n-gpu-layers 7 \\
    --temp 0.6 \
    --ctx-size 8192 \\
    --seed 3407 \\
    --prompt "<｜User｜>Python で Flappy Bird ゲームを作ってください。<｜Assistant｜>"
```

5. こちらのブログ記事で述べた Flappy Bird の例をテストするには: <https://unsloth.ai/blog/deepseekr1-dynamic>、1.58bit の動的量子化を使って以下のように 2 つ目の例を生成できます:

<table data-column-title-hidden data-view="cards" data-full-width="false"><thead><tr><th></th><th></th><th></th><th data-hidden data-card-cover data-type="files"></th></tr></thead><tbody><tr><td>オリジナルの DeepSeek R1</td><td></td><td></td><td><a href="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-3c484081174c631653c8c7bf7e7674f05255f740%2FInShot_20250127_043158375_H8Uu6tyJXYAFwUEIu04Am.gif?alt=media">InShot_20250127_043158375_H8Uu6tyJXYAFwUEIu04Am.gif</a></td></tr><tr><td>1.58bit 動的量子化</td><td></td><td></td><td><a href="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-c41eac0fea9362017e94123ee8f9793df21b8e97%2FInShot_20250127_042648160_lrtL8-eRhl4qtLaUDSU87.gif?alt=media">InShot_20250127_042648160_lrtL8-eRhl4qtLaUDSU87.gif</a></td></tr></tbody></table>

使用したプロンプトは以下のとおりです:

{% code overflow="wrap" %}

```
<｜User｜>Python で Flappy Bird ゲームを作ってください。次の内容を含める必要があります:
1. pygame を使用する必要があります。
2. 背景色はランダムに選ばれる明るい色にしてください。最初は薄い青色にします。
3. SPACE を何度も押すと鳥が加速します。
4. 鳥の形は四角、円、三角形のいずれかをランダムに選びます。色はランダムに暗い色を選びます。
5. 画面下部に、ランダムに選ばれた濃い茶色または黄色の地面を配置します。
6. スコアを右上に表示します。パイプを通過してぶつからなければ加算してください。
7. 十分な間隔を空けて、ランダムな間隔でパイプを配置します。色はランダムに濃い緑、薄い茶色、または暗いグレー系の色にします。
8. 負けたら最高スコアを表示します。文字は画面内に表示してください。q または Esc を押すとゲームを終了します。再開はもう一度 SPACE を押します。
最終的なゲームは Python の markdown セクション内に入れてください。最終的な markdown セクションの前にコードのエラーを確認し、修正してください。<｜Assistant｜>
```

{% endcode %}

この例を使って llama.cpp を呼び出すには、次のようにします:

```bash
./llama.cpp/llama-cli \
    --model DeepSeek-R1-GGUF/DeepSeek-R1-UD-IQ1_S/DeepSeek-R1-UD-IQ1_S-00001-of-00003.gguf \\
    --cache-type-k q4_0 \\
    -no-cnv --prio 2 \\
    --n-gpu-layers 7 \\
    --temp 0.6 \
    --ctx-size 8192 \\
    --seed 3407 \\
    --prompt "<｜User｜>Python で Flappy Bird ゲームを作ってください。次の内容を含める必要があります:\n1. pygame を使用する必要があります。\n2. 背景色はランダムに選ばれる明るい色にしてください。最初は薄い青色にします。\n3. SPACE を何度も押すと鳥が加速します。\n4. 鳥の形は四角、円、三角形のいずれかをランダムに選びます。色はランダムに暗い色を選びます。\n5. 画面下部に、ランダムに選ばれた濃い茶色または黄色の地面を配置します。\n6. スコアを右上に表示します。パイプを通過してぶつからなければ加算してください。\n7. 十分な間隔を空けて、ランダムな間隔でパイプを配置します。色はランダムに濃い緑、薄い茶色、または暗いグレー系の色にします。\n8. 負けたら最高スコアを表示します。文字は画面内に表示してください。q または Esc を押すとゲームを終了します。再開はもう一度 SPACE を押します。\n最終的なゲームは Python の markdown セクション内に入れてください。最終的な markdown セクションの前にコードのエラーを確認し、修正してください。<｜Assistant｜>"
```

5. また、たとえば Ollama で使うために重みをまとめたい場合は、このスクリプトを使ってください:

```bash
./llama.cpp/llama-gguf-split --merge \\
    DeepSeek-R1-GGUF/DeepSeek-R1-UD-IQ1_S-00001-of-00003.gguf \\
    merged_file.gguf
```

6. DeepSeek R1 には 61 層あります。たとえば 24GB GPU または 80GB GPU なら、切り捨て後の層数をオフロードできると考えられます（メモリ不足になる場合は 1 減らしてください）:

| 量子化     | ファイルサイズ | 24GB GPU | 80GB GPU | 2x80GB GPU |
| ------- | ------- | -------- | -------- | ---------- |
| 1.58bit | 131GB   | 7        | 33       | 全 61 層     |
| 1.73bit | 158GB   | 5        | 26       | 57         |
| 2.22bit | 183GB   | 4        | 22       | 49         |
| 2.51bit | 212GB   | 2        | 19       | 32         |

### Mac / Apple デバイスでの実行

Apple Metal デバイスでは --n-gpu-layers に注意してください。メモリ不足になるようなら、値を下げてください。128GB のユニファイドメモリ搭載マシンなら、59 層ほどをオフロードできるはずです。

```bash
./llama.cpp/llama-cli \
    --model DeepSeek-R1-GGUF/DeepSeek-R1-UD-IQ1_S/DeepSeek-R1-UD-IQ1_S-00001-of-00003.gguf \\
    --cache-type-k q4_0 \\
    --prio 2 \\
    --temp 0.6 \
    --ctx-size 8192 \\
    --seed 3407 \\
    --n-gpu-layers 59 \\
    -no-cnv \\
    --prompt "<｜User｜>Python で Flappy Bird ゲームを作ってください。<｜Assistant｜>"
```

### Ollama/Open WebUI で実行

Open WebUI は、R1 の実行方法についてのステップごとのチュートリアルをこちらで公開しています: <https://docs.openwebui.com/tutorials/integrations/llm-providers/deepseekr1-dynamic>

\
GGUF で Ollama を使って推論したい場合は、まず以下のコードのように 3 つの分割 GGUF ファイルを 1 つにまとめる必要があります。その後、モデルをローカルで実行します。

```bash
./llama.cpp/llama-gguf-split --merge \\
  DeepSeek-R1-GGUF/DeepSeek-R1-UD-IQ1_S/DeepSeek-R1-UD-IQ1_S-00001-of-00003.gguf \\
	merged_file.gguf
```

## DeepSeek のチャットテンプレート

すべての蒸留版と元の 671B R1 モデルは同じチャットテンプレートを使用します:

`<｜begin▁of▁sentence｜><｜User｜>1+1は何ですか？<｜Assistant｜>答えは 2 です。<｜end▁of▁sentence｜><｜User｜>もっと説明して！<｜Assistant｜>`

BOS は強制的に追加され、EOS が各やり取りを区切ります。推論時の二重 BOS トークンを避けるには、次だけを呼び出してください *tokenizer.encode(..., add\_special\_tokens = False)* チャットテンプレートでも BOS トークンが自動で追加されるためです。\
llama.cpp / GGUF の推論では、自動追加されるので BOS は省略してください。

`<｜User｜>1+1は何ですか？<｜Assistant｜>`

\<think> と \</think> トークンには専用のトークンが割り当てられます。Qwen と Llama の蒸留版では、一部のトークンが再マップされています。一方、たとえば Qwen には BOS トークンがなかったため、代わりに <|object\_ref\_start|> を使う必要がありました。\
\
**トークナイザー ID の対応表:**

| トークン                      | R1     | 蒸留版 Qwen | 蒸留版 Llama |
| ------------------------- | ------ | -------- | --------- |
| \<think>                  | 128798 | 151648   | 128013    |
| \</think>                 | 128799 | 151649   | 128014    |
| <\|begin\_of\_sentence\|> | 0      | 151646   | 128000    |
| <\|end\_of\_sentence\|>   | 1      | 151643   | 128001    |
| <\|User\|>                | 128803 | 151644   | 128011    |
| <\|Assistant\|>           | 128804 | 151645   | 128012    |
| パディングトークン                 | 2      | 151654   | 128004    |

モデル内の元のトークン:

| トークン                  | Qwen 2.5 32B Base        | Llama 3.3 70B Instruct            |
| --------------------- | ------------------------ | --------------------------------- |
| \<think>              | <\|box\_start\|>         | <\|reserved\_special\_token\_5\|> |
| \</think>             | <\|box\_end\|>           | <\|reserved\_special\_token\_6\|> |
| <｜begin▁of▁sentence｜> | <\|object\_ref\_start\|> | <\|begin\_of\_text\|>             |
| <｜end▁of▁sentence｜>   | <\|endoftext\|>          | <\|end\_of\_text\|>               |
| <｜User｜>              | <\|im\_start\|>          | <\|reserved\_special\_token\_3\|> |
| <｜Assistant｜>         | <\|im\_end\|>            | <\|reserved\_special\_token\_4\|> |
| パディングトークン             | <\|vision\_pad\|>        | <\|finetune\_right\_pad\_id\|>    |

蒸留版と元の R1 版のすべてでは、誤ってパディングトークンに <｜end▁of▁sentence｜> が割り当てられているようです。これは、特にこれらの推論モデルの上にさらにファインチューニングしたい場合、ほとんど良い考えではありません。多くのフレームワークが EOS トークンを -100 としてマスクするため、これが原因で無限に生成が続いてしまいます。\
\
私たちは、正しいパディングトークンで蒸留版と元の R1 版のすべてを修正しました（Qwen は <|vision\_pad|>、Llama は <|finetune\_right\_pad\_id|>、R1 は <｜▁pad▁｜>、または私たちが追加した <｜PAD▁TOKEN｜> を使用します）。

## GGUF R1 表

<table data-full-width="true"><thead><tr><th>MoE ビット数</th><th>型</th><th>ディスクサイズ</th><th>精度</th><th>リンク</th><th>詳細</th></tr></thead><tbody><tr><td>1.58bit</td><td>UD-IQ1_S</td><td><strong>131GB</strong></td><td>まずまず</td><td><a href="https://huggingface.co/unsloth/DeepSeek-R1-GGUF/tree/main/DeepSeek-R1-UD-IQ1_S">リンク</a></td><td>MoE 全体を 1.56bit にしたもの。 <code>down_proj</code> MoE の 2.06/1.56bit 混合で</td></tr><tr><td>1.73bit</td><td>UD-IQ1_M</td><td><strong>158GB</strong></td><td>良い</td><td><a href="https://huggingface.co/unsloth/DeepSeek-R1-GGUF/tree/main/DeepSeek-R1-UD-IQ1_M">リンク</a></td><td>MoE 全体を 1.56bit にしたもの。 <code>down_proj</code> MoE では 2.06bit のまま</td></tr><tr><td>2.22bit</td><td>UD-IQ2_XXS</td><td><strong>183GB</strong></td><td>より良い</td><td><a href="https://huggingface.co/unsloth/DeepSeek-R1-GGUF/tree/main/DeepSeek-R1-UD-IQ2_XXS">リンク</a></td><td>MoE 全体を 2.06bit にしたもの。 <code>down_proj</code> MoE の 2.5/2.06bit 混合で</td></tr><tr><td>2.51bit</td><td>UD-Q2_K_XL</td><td><strong>212GB</strong></td><td>最高</td><td><a href="https://huggingface.co/unsloth/DeepSeek-R1-GGUF/tree/main/DeepSeek-R1-UD-Q2_K_XL">リンク</a></td><td>MoE 全体を 2.5bit にしたもの。 <code>down_proj</code> MoE の 3.5/2.5bit 混合で</td></tr></tbody></table>


---

# 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/moderu/tutorials/deepseek-r1-how-to-run-locally.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.
