> 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-v3.1-how-to-run-locally.md).

# DeepSeek-V3.1: ローカルでの実行方法

DeepSeek の V3.1 と **Terminus** アップデートでは、ハイブリッド推論推論が導入され、「think」と「non-think」を1つのモデルに統合しています。完全な 671B パラメータモデルには 715GB のディスク容量が必要です。量子化された動的 2 ビット版は 245GB（サイズを 75% 削減）です。GGUF: [**DeepSeek-V3.1-GGUF**](https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF)

{% hint style="success" %}
**NEW:** DeepSeek-V3.1-Terminus が公開されました: [DeepSeek-V3.1-Terminus-GGUF](https://huggingface.co/unsloth/DeepSeek-V3.1-Terminus-GGUF)\
\
[**2025年9月10日更新:**](/docs/jp/ji-ben/unsloth-dynamic-2.0-ggufs/unsloth-dynamic-ggufs-on-aider-polyglot.md) より厳しいベンチマークを求める声に応えて、Aider Polyglot の結果を紹介します！ 当社の Dynamic 3-bit DeepSeek V3.1 GGUF は **75.6%**&#x3092;記録し、多くのフル精度 SOTA LLM を上回っています。 [詳細はこちら。](/docs/jp/ji-ben/unsloth-dynamic-2.0-ggufs/unsloth-dynamic-ggufs-on-aider-polyglot.md)

当社の DeepSeek-V3.1 GGUF には、Unsloth の [チャットテンプレート修正](#chat-template-bug-fixes) が llama.cpp 対応バックエンド向けに含まれています。
{% endhint %}

すべてのアップロードでは Unsloth [Dynamic 2.0](/docs/jp/ji-ben/unsloth-dynamic-2.0-ggufs.md) を使用しており、SOTA の 5-shot MMLU と KL Divergence 性能を実現しています。つまり、量子化された DeepSeek LLM を最小限の精度低下で実行およびファインチューニングできます。

**チュートリアル ナビゲーション:**

<a href="#run-in-llama.cpp" class="button secondary">llama.cpp で実行</a><a href="#run-in-ollama-open-webui" class="button secondary">Ollama/Open WebUI で実行</a>

## :gear: 推奨設定

1 ビット動的量子化 TQ1\_0（重要でない MoE 層は 1bit、重要な MoE は 2～4bit、残りは 6～8bit）は 170GB のディスク容量を使用します。これは **1x24GB カードと 128GB の RAM** で、MoE オフロードと組み合わせてうまく動作します。また、 **Ollama でもネイティブに動作します**!

{% hint style="info" %}
必ず `--jinja` を llama.cpp の量子化版で使用する必要があります。これにより当社の [修正済みチャットテンプレート](#chat-template-bug-fixes) が使われ、正しいテンプレートが有効になります！ 使用しない場合、誤った結果が出る可能性があります `--jinja`
{% endhint %}

2 ビット量子化版は 1x 24GB GPU に収まります（MoE 層は RAM にオフロード）。この構成で、さらに 128GB RAM があれば、およそ 5 トークン/秒が期待できます。この 2 ビット版を実行するには少なくとも 226GB RAM を推奨します。最適な性能のためには、少なくとも 226GB のユニファイドメモリ、または 226GB の RAM+VRAM 合計が必要で、5+ トークン/秒を見込めます。生成速度を上げ、より長いコンテキストを収める方法については、 [こちらをお読みください](#improving-generation-speed).

{% hint style="success" %}
必須ではありませんが、最良の性能のためには、VRAM + RAM の合計をダウンロードする量子化版のサイズと同じにしてください。そうでない場合でも、llama.cpp ではハードドライブ / SSD オフロードが機能しますが、推論は遅くなります。
{% endhint %}

## :butterfly:チャットテンプレートのバグ修正

DeepSeek V3.1 のチャットテンプレートには、llama.cpp や他のエンジンで正しく動作しない問題がいくつかあったため、修正しました:

1. DeepSeek V3.1 はハイブリッド推論モデルであり、チャットテンプレートを変更して推論を有効にできます。チャットテンプレートでは `thinking = True` が導入されましたが、他のモデルでは `enable_thinking = True` を使用します。そこで、 `enable_thinking` を代わりにキーワードとして使えるようにしました。
2. llama.cpp の jinja レンダラーは [minja](https://github.com/google/minja) 経由では、 `.split()` コマンドに追加引数を使うことができません。そのため、 `.split(text, 1)` は Python では動作しますが、minja では動作しません。llama.cpp がエラーなく正しく動作するよう、これを変更する必要がありました。\
   \
   他の量子化版を使うと、次のエラーが発生します:\
   `terminate called after throwing an instance of 'std::runtime_error' what(): split method must have between 1 and 1 positional arguments and between 0 and 0 keyword arguments at row 3, column 1908` 当社のすべての量子化版で修正済みです！

### 🐳公式推奨設定

によると [DeepSeek](https://huggingface.co/deepseek-ai/DeepSeek-V3.1)、V3.1 推論の推奨設定は次の通りです:

* 次を設定します <mark style="background-color:green;">**temperature 0.6**</mark> 反復や一貫性の欠如を減らすためです。
* 設定 <mark style="background-color:green;">**top\_p を 0.95 に**</mark> （推奨）
* **128K のコンテキスト長** 以下
* 使用してください `--jinja` llama.cpp の各バリアントでは - 当社では **いくつかのチャットテンプレートの問題も修正しました！**
* **使用してください** `enable_thinking = True` これにより reasoning / thinking モードを使用できます。デフォルトでは非推論に設定されています。

#### :1234: チャットテンプレート / プロンプト形式

強制的に指定する必要はありません `<think>\n` 、ただし追加しても構いません！ 指定されたプレフィックスでは、DeepSeek V3.1 は non-thinking モードでクエリへの応答を生成します。DeepSeek V3 とは異なり、追加のトークン `</think>`.

```
<｜begin▁of▁sentence｜>{system prompt}<｜User｜>{query}<｜Assistant｜></think>
```

BOS は強制的に追加され、各やり取りは EOS で区切られます。推論中の BOS トークン二重化を防ぐため、呼び出すのは `tokenizer.encode(..., add_special_tokens = False)` のみにしてください。チャットテンプレートが BOS トークンも自動追加するためです。llama.cpp / GGUF 推論では、BOS は自動追加されるのでスキップしてください。

#### :notebook\_with\_decorative\_cover: Non-Thinking モード（ `thinking = False`または `enable_thinking = False` を使用し、これがデフォルトです）

**最初のターン**

プレフィックス: `<｜begin▁of▁sentence｜>{system prompt}<｜User｜>{query}<｜Assistant｜></think>`

指定されたプレフィックスでは、DeepSeek V3.1 は non-thinking モードでクエリへの応答を生成します。DeepSeek V3 とは異なり、追加のトークン `</think>`.

**マルチターン**

コンテキスト: `<｜begin▁of▁sentence｜>{system prompt}<｜User｜>{query}<｜Assistant｜></think>{response}<｜end▁of▁sentence｜>...<｜User｜>{query}<｜Assistant｜></think>{response}<｜end▁of▁sentence｜>`

プレフィックス: `<｜User｜>{query}<｜Assistant｜></think>`

コンテキストとプレフィックスを連結することで、クエリに対する正しいプロンプトが得られます。

#### :books: Thinking モード（ `thinking = True`または `enable_thinking = True` を使用し、これがデフォルトです）

**最初のターン**

プレフィックス: `<｜begin▁of▁sentence｜>{system prompt}<｜User｜>{query}<｜Assistant｜><think>`

Thinking モードのプレフィックスは DeepSeek-R1 に似ています。

**マルチターン**

コンテキスト: `<｜begin▁of▁sentence｜>{system prompt}<｜User｜>{query}<｜Assistant｜></think>{response}<｜end▁of▁sentence｜>...<｜User｜>{query}<｜Assistant｜></think>{response}<｜end▁of▁sentence｜>`

プレフィックス: `<｜User｜>{query}<｜Assistant｜><think>`

マルチターンのテンプレートは non-thinking のマルチターン チャットテンプレートと同じです。これは、最後のターンの thinking トークンは削除されますが、 `</think>` はコンテキストの各ターンに保持されることを意味します。

#### :bow\_and\_arrow: ツール呼び出し

ツール呼び出しは non-thinking モードでサポートされています。形式は次の通りです:

`<｜begin▁of▁sentence｜>{system prompt}{tool_description}<｜User｜>{query}<｜Assistant｜></think>` ここで tool\_description は system prompt の後の領域に挿入されます。

## :arrow\_forward:DeepSeek-V3.1 実行チュートリアル:

### :llama: Ollama/Open WebUI で実行

{% stepper %}
{% step %}
インストール `ollama` まだであれば先に行ってください！ モデルの他のバリアントを実行するには、 [こちらをご覧ください](#run-in-llama.cpp).

```bash
apt-get update
apt-get install pciutils -y
curl -fsSL https://ollama.com/install.sh | sh
```

{% endstep %}

{% step %}
モデルを実行します！ 失敗した場合は、別のターミナルで `ollama serve`を呼び出せることに注意してください！ 当社の修正と推奨パラメータ（temperature など）はすべて、 `params` として Hugging Face のアップロードに含めています！\
\&#xNAN;**（NEW）Ollama で DeepSeek-V3.1 モデルを使うには、当社の TQ1\_0（170GB 量子化版）を使用できます:**

```bash
OLLAMA_MODELS=unsloth ollama serve &

OLLAMA_MODELS=unsloth ollama run hf.co/unsloth/DeepSeek-V3.1-Terminus-GGUF:TQ1_0
```

{% endstep %}

{% step %}
他の量子化版を実行するには、まず下記コードのように GGUF 分割ファイルを 1 つにマージする必要があります。その後、モデルをローカルで実行する必要があります。

```bash
./llama.cpp/llama-gguf-split --merge \
  DeepSeek-V3.1-Terminus-GGUF/DeepSeek-V3.1-Terminus-UD-Q2_K_XL/DeepSeek-V3.1-Terminus-UD-Q2_K_XL-00001-of-00006.gguf \
	merged_file.gguf
```

```bash
OLLAMA_MODELS=unsloth ollama serve &

OLLAMA_MODELS=unsloth ollama run merged_file.gguf
```

{% endstep %}

{% step %}
Open WebUI も [ステップバイステップのチュートリアル](https://docs.openwebui.com/tutorials/integrations/deepseekr1-dynamic/) を作成しており、R1 の実行方法について説明しています。V3.1 では、R1 を新しい V3.1 量子化版に置き換えるだけで済みます。
{% endstep %}
{% endstepper %}

### ✨ llama.cpp で実行

{% stepper %}
{% step %}
最新の `llama.cpp` を取得してください [GitHub はこちら](https://github.com/ggml-org/llama.cpp)。以下のビルド手順に従うこともできます。 `-DGGML_CUDA=ON` を `-DGGML_CUDA=OFF` に変更してください。GPU がない場合、または CPU 推論だけを行いたい場合です。

```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=OFF -DGGML_CUDA=ON -DLLAMA_CURL=ON
cmake --build llama.cpp/build --config Release -j --clean-first --target llama-quantize llama-cli llama-gguf-split llama-mtmd-cli llama-server
cp llama.cpp/build/bin/llama-* llama.cpp
```

{% endstep %}

{% step %}
もし `llama.cpp` を使って直接モデルを読み込みたい場合は、以下を実行できます。（:Q2\_K\_XL）は量子化タイプです。Hugging Face 経由でのダウンロード（ポイント 3）も可能です。これは `ollama run` に似ています。 `export LLAMA_CACHE="folder"` を使って、 `llama.cpp` が特定の場所に保存するよう強制できます。モデルの最大コンテキスト長は 128K のみであることを覚えておいてください。

{% hint style="success" %}
ぜひ試してください `-ot ".ffn_.*_exps.=CPU"` これはすべての MoE 層を CPU にオフロードします！ これにより、すべての非 MoE 層を 1 GPU に収められるようになり、生成速度が向上します。GPU 容量に余裕がある場合は、より多くの層に合わせて regex 式をカスタマイズできます。

GPU メモリにもう少し余裕があるなら、 `-ot ".ffn_(up|down)_exps.=CPU"` を試してください。これは up と down projection の MoE 層をオフロードします。

さらに GPU メモリに余裕があるなら、 `-ot ".ffn_(up)_exps.=CPU"` を試してください。これは up projection の MoE 層のみをオフロードします。

最後に、次を使ってすべての層をオフロードします `-ot ".ffn_.*_exps.=CPU"` これは最も少ない VRAM を使用します。

regex をカスタマイズすることもできます。たとえば、 `-ot "\.(6|7|8|9|[0-9][0-9]|[0-9][0-9][0-9])\.ffn_(gate|up|down)_exps.=CPU"` は、gate、up、down の MoE 層を、ただし 6 層目以降のみオフロードすることを意味します。
{% endhint %}

```bash
export LLAMA_CACHE="unsloth/DeepSeek-V3.1-GGUF"
./llama.cpp/llama-cli \
    -hf unsloth/DeepSeek-V3.1-Terminus-GGUF:UD-Q2_K_XL \
    --jinja \
    --n-gpu-layers 99 \
    --temp 0.6 \
    --top-p 0.95 \
    --min-p 0.01 \
    --ctx-size 16384 \
    --seed 3407 \
    -ot ".ffn_.*_exps.=CPU"
```

{% endstep %}

{% step %}
（インストール後）次の方法でモデルをダウンロードします `pip install huggingface_hub hf_transfer` ）。 `UD-`Q2\_K\_XL（動的 2bit 量子化版）または、 `Q4_K_M` のような他の量子化版を選べます。 <mark style="background-color:green;">**当社は 2.7bit の動的量子化版の使用を推奨します**</mark><mark style="background-color:green;">**&#x20;**</mark><mark style="background-color:green;">**`UD-Q2_K_XL`**</mark><mark style="background-color:green;">**&#x20;**</mark><mark style="background-color:green;">**サイズと精度のバランスを取るためです**</mark>.

```python
# !pip install huggingface_hub hf_transfer
import os
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "0" # レート制限にかかることがあるため、無効化するには 0 に設定
from huggingface_hub import snapshot_download
snapshot_download(
    repo_id = "unsloth/DeepSeek-V3.1-Terminus-GGUF",
    local_dir = "unsloth/DeepSeek-V3.1-Terminus-GGUF",
    allow_patterns = ["*UD-Q2_K_XL*"], # Dynamic 2bit Dynamic 1bit には "*UD-TQ1_0*" を使用
)
```

{% endstep %}

{% step %}
編集できます `--threads 32` CPU スレッド数用、 `--ctx-size 16384` コンテキスト長用、 `--n-gpu-layers 2` GPU に何層オフロードするか用です。GPU メモリ不足になる場合は調整してみてください。CPU のみの推論なら削除してください。

{% code overflow="wrap" %}

```bash
./llama.cpp/llama-cli \
    --model unsloth/DeepSeek-V3.1-Terminus-GGUF/UD-Q2_K_XL/DeepSeek-V3.1-Terminus-UD-Q2_K_XL-00001-of-00006.gguf \
    --jinja \
    --n-gpu-layers 99 \
    --temp 0.6 \
    --top-p 0.95 \
    --min-p 0.01 \
    --ctx-size 16384 \
    --seed 3407 \
    -ot ".ffn_.*_exps.=CPU"
```

{% endcode %}
{% endstep %}

{% step %}
RAM と VRAM の合計が十分でない場合は、1bit 版（170GB）を取得してください:

```python
from huggingface_hub import snapshot_download
snapshot_download(
    repo_id = "unsloth/DeepSeek-V3.1-Terminus-GGUF",
    local_dir = "unsloth/DeepSeek-V3.1-Terminus-GGUF",
    allow_patterns = ["*UD-TQ1_0*"], # Dynamic 2bit には "*UD-Q2_K_XL*" を使用
)
```

{% endstep %}
{% endstepper %}

### ✨ llama-server と OpenAI の completion ライブラリでデプロイ

デプロイに llama-server を使うには、次のコマンドを使用します:

{% code overflow="wrap" %}

```bash
./llama.cpp/llama-server \
    --model unsloth/DeepSeek-V3.1-Terminus-GGUF/DeepSeek-V3.1-Terminus-UD-TQ1_0.gguf \
    --alias "unsloth/DeepSeek-V3.1-Terminus" \
    --n-gpu-layers 999 \
    -ot ".ffn_.*_exps.=CPU" \
    --prio 3 \
    --min-p 0.01 \
    --ctx-size 16384 \
    --port 8001 \
    --jinja
```

{% endcode %}

その後、 `pip install openai` :

```python
の後に OpenAI の Python ライブラリを使用します
import json
openai_client = OpenAI(
    base_url = "http://127.0.0.1:8001/v1",
    api_key = "sk-no-key-required",
)
completion = openai_client.chat.completions.create(
    model = "unsloth/DeepSeek-V3.1-Terminus",
    messages = [{"role": "user", "content": "2+2 は何ですか？"},],
)
print(completion.choices[0].message.content)
```

## :minidisc:モデルのアップロード

**当社のすべてのアップロード** - imatrix ベースでないものや dynamic でないものを含め、会話、コーディング、言語タスク向けに特化して最適化された当社のキャリブレーション データセットを利用しています。

* 以下は完全な DeepSeek-V3.1 モデルのアップロードです:

また、 [IQ4\_NL](https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/IQ4_NL) および [Q4\_1](https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/Q4_1) の量子化版もアップロードしました。これらは ARM と Apple デバイスでそれぞれ特に高速に動作します。

<table data-full-width="false"><thead><tr><th>MoE ビット数</th><th>タイプ + リンク</th><th>ディスクサイズ</th><th>詳細</th></tr></thead><tbody><tr><td>1.66bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF?show_file_info=DeepSeek-V3.1-UD-TQ1_0.gguf">TQ1_0</a></td><td><strong>170GB</strong></td><td>1.92/1.56bit</td></tr><tr><td>1.78bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/UD-IQ1_S">IQ1_S</a></td><td><strong>185GB</strong></td><td>2.06/1.56bit</td></tr><tr><td>1.93bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/UD-IQ1_M">IQ1_M</a></td><td><strong>200GB</strong></td><td>2.5/2.06/1.56</td></tr><tr><td>2.42bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/UD-IQ2_XXS">IQ2_XXS</a></td><td><strong>216GB</strong></td><td>2.5/2.06bit</td></tr><tr><td>2.71bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/UD-Q2_K_XL">Q2_K_XL</a></td><td><strong>251GB</strong></td><td>3.5/2.5bit</td></tr><tr><td>3.12bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/UD-IQ3_XXS">IQ3_XXS</a></td><td><strong>273GB</strong></td><td>3.5/2.06bit</td></tr><tr><td>3.5bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/UD-Q3_K_XL">Q3_K_XL</a></td><td><strong>296GB</strong></td><td>4.5/3.5bit</td></tr><tr><td>4.5bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/UD-Q4_K_XL">Q4_K_XL</a></td><td><strong>384GB</strong></td><td>5.5/4.5bit</td></tr><tr><td>5.5bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/UD-Q5_K_XL">Q5_K_XL</a></td><td><strong>481GB</strong></td><td>6.5/5.5bit</td></tr></tbody></table>

また、 [BF16 形式](https://huggingface.co/unsloth/DeepSeek-V3.1-BF16)、および元の [FP8（float8）形式](https://huggingface.co/unsloth/DeepSeek-V3.1).

## :snowboarder: 生成速度の向上

VRAM に余裕がある場合は、より多くの MoE 層、または層全体そのものをオフロードしてみてください。

通常、 `-ot ".ffn_.*_exps.=CPU"` はすべての MoE 層を CPU にオフロードします！ これにより、すべての非 MoE 層を 1 GPU に収められるようになり、生成速度が向上します。GPU 容量に余裕がある場合は、より多くの層に合わせて regex 式をカスタマイズできます。

GPU メモリにもう少し余裕があるなら、 `-ot ".ffn_(up|down)_exps.=CPU"` を試してください。これは up と down projection の MoE 層をオフロードします。

さらに GPU メモリに余裕があるなら、 `-ot ".ffn_(up)_exps.=CPU"` を試してください。これは up projection の MoE 層のみをオフロードします。

regex をカスタマイズすることもできます。たとえば、 `-ot "\.(6|7|8|9|[0-9][0-9]|[0-9][0-9][0-9])\.ffn_(gate|up|down)_exps.=CPU"` は、gate、up、down の MoE 層を、ただし 6 層目以降のみオフロードすることを意味します。

その [最新の llama.cpp リリース](https://github.com/ggml-org/llama.cpp/pull/14363) では高スループット モードも導入されています。 `llama-parallel`を使用してください。詳細は [こちら](https://github.com/ggml-org/llama.cpp/tree/master/examples/parallel)。また、 **KV キャッシュを 4bits に量子化する** こともでき、たとえば VRAM / RAM の移動量を減らして、生成処理を高速化することも可能です。

## 📐長いコンテキスト（完全な 128K）を収める方法

より長いコンテキストを収めるには、 **KV キャッシュ量子化** を使って K および V キャッシュをより低いビットに量子化できます。これにより RAM / VRAM のデータ移動が減るため、生成速度も向上する場合があります。K 量子化で許可されるオプション（デフォルトは `f16`）は以下の通りです。

`--cache-type-k f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1`

使用すべきです `_1` の各バリアントは、わずかに遅くなるものの、多少精度が向上します。たとえば `q4_1, q5_1`

V キャッシュも量子化できますが、そのためには **Flash Attention 対応付きで llama.cpp をコンパイルする** 必要があります。 `-DGGML_CUDA_FA_ALL_QUANTS=ON`経由で対応を有効にし、 `--flash-attn` を使って有効化します。その後、 `--cache-type-k` :

`--cache-type-v f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1`


---

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