# LM Studio へのモデルデプロイ

ファインチューニングしたLLMをLM Studioで直接実行およびデプロイできます。 [LM Studio](https://lmstudio.ai/) は、の実行とデプロイを容易にします **GGUF** モデル（llama.cpp形式）。

次を使用できます [LM Studioノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/FunctionGemma_\(270M\)-LMStudio.ipynb) または以下の手順に従ってください：

1. **Unslothでファインチューニングしたモデルをにエクスポートします `.gguf`**
2. **GGUFをLM Studioにインポート／ダウンロードします**
3. **チャットで読み込みます** （またはOpenAI互換のローカルAPIの背後で実行します）

<div><figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FUZEwmNLcs5Oc7bIT7iXV%2Fprefinetune-unsloth.png?alt=media&#x26;token=ceb701d3-1f32-406e-a5be-2a7bde4cb4b6" alt="" width="375"><figcaption><p>LM Studioでのファインチューニング前</p></figcaption></figure> <figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FvLEmVH22LQ4hjAA3SGIV%2Fpostfinetune-unsloth.png?alt=media&#x26;token=5a473857-6700-4f0a-89c6-0c72c6b507c4" alt="" width="375"><figcaption><p>LM Studioでのファインチューニング後</p></figcaption></figure></div>

### 1) GGUFにエクスポート（Unslothから）

すでにをエクスポートしている場合は、にスキップしてください `.gguf`にスキップ **LM Studioへのインポート**.

```python
# ローカルに保存（フォルダ内にGGUFアーティファクトを作成）
model.save_pretrained_gguf("my_model_gguf", tokenizer, quantization_method = "q4_k_m")
# model.save_pretrained_gguf("my_model_gguf", tokenizer, quantization_method = "q8_0")
# model.save_pretrained_gguf("my_model_gguf", tokenizer, quantization_method = "f16")

# またはGGUFをHugging Face Hubにプッシュ
model.push_to_hub_gguf("hf_username/my_model_gguf", tokenizer, quantization_method = "q4_k_m")
```

{% hint style="info" %}
`q4_k_m` は通常ローカル実行のデフォルトです。

`q8_0` はほぼフル精度に近い品質の最適解です。

`f16` は最大／最も遅いですが、元の非量子化精度です。
{% endhint %}

### 2) GGUFをLM Studioにインポート

{% tabs %}
{% tab title="CLIインポート（lms import）" %}
LM Studioは、というCLIを提供しています `lms` はローカルのをインポートできます `.gguf` をLM Studioのmodelsフォルダに。

**GGUFファイルをインポート：**

```bash
lms import /path/to/model.gguf
```

**元のファイルを保持（移動ではなくコピー）：**

```bash
lms import /path/to/model.gguf --copy
```

<details>

<summary><strong>よりカスタマイズ可能なプライベート設定を表示</strong></summary>

**モデルをそのままにする（シンボリックリンク）：**

これは専用ドライブに保存された大きなモデルに便利です。

```bash
lms import /path/to/model.gguf --symbolic-link
```

**プロンプトをスキップしてターゲットネームスペースを自分で選択：**

```bash
lms import /path/to/model.gguf --user-repo my-user/my-finetuned-models
```

**ドライラン（何が起こるかを表示）：**

```bash
lms import /path/to/model.gguf --dry-run
```

</details>

インポート後、モデルはLM Studioの下に表示されるはずです **マイモデル**.

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FqAgsPwtQv6sSLdRJi6vp%2Flms-modeldirectory-fxngemma.png?alt=media&#x26;token=ea11eaed-5684-4a0d-91fc-d540e703a54c" alt=""><figcaption></figcaption></figure>
{% endtab %}

{% tab title="Hugging Faceから" %}
GGUFリポジトリをHugging Faceにプッシュした場合、LM Studio内から直接ダウンロードできます。

**オプションA：LM Studioのアプリ内ダウンローダーを使用**

1. LM Studioを開く
2. に移動 **発見（Discover）** タブ
3. を検索 `hf_username/repo_name` （またはHugging FaceのURLを貼り付け）
4. ダウンロードしたい量子化（例： `Q4_K_M`)

**オプションB：CLIダウンローダーを使用**

```bash
# リポ名でHFからダウンロード
lms get hf_username/my_model_gguf

# @で量子化を指定
lms get hf_username/my_model_gguf@Q4_K_M
```

{% endtab %}

{% tab title="手動インポート（フォルダ構造）" %}
CLIを使用したくない場合は、をLM Studioの期待するモデルディレクトリ構造に配置できます。 `.gguf` ファイルをLM Studioの期待するモデルディレクトリ構造に配置できます。

LM Studioはモデルを次のように期待します：

```
~/.lmstudio/models/
└── publisher/
    └── model/
        └── model-file.gguf
```

例：

```
~/.lmstudio/models/
└── my-name/
    └── my-finetune/
        └── my-finetune-Q4_K_M.gguf
```

その後、LM Studioを開いて確認してください **マイモデル**.

**ヒント：** LM Studioのタブからモデルディレクトリを管理／検証できます **マイモデル** タブで。
{% endtab %}
{% endtabs %}

### 3) LM Studioで読み込み、チャットする

1. LM Studioを開く → **チャット**
2. adb push \<path\_to\_model.pte on your computer> /data/local/tmp/llama **モデルローダー**
3. インポートしたモデルを選択
4. （オプション）読み込み設定を調整（GPUオフロード、コンテキスト長など）
5. UIで通常通りチャットする

### 4) ファインチューニングしたモデルをローカルAPI（OpenAI互換）として提供する

LM Studioは読み込んだモデルをOpenAI互換APIの背後で提供できます（Open WebUI、カスタムエージェント、スクリプトなどのアプリに便利）。

{% tabs %}
{% tab title="GUI（Developerタブ）" %}

1. LM Studioでモデルを読み込む
2. に移動 **開発者（Developer）** タブ
3. ローカルサーバーを起動する
4. 表示されているベースURLを使用（デフォルトは通常） `http://localhost:1234/v1`)
   {% endtab %}

{% tab title="CLI（lms load + lms server start）" %}

#### 1) 利用可能なモデルを一覧表示

```bash
lms ls
```

#### 2) モデルを読み込む（オプションフラグ）

```bash
lms load <model-identifier> --gpu=auto --context-length=8192
```

注意：

* `--gpu=1.0` は「GPUに100%オフロードを試みる」を意味します
* 安定した識別子を設定できます：

```bash
lms load <model-identifier> --identifier="my-finetuned-model"
```

#### 3) サーバーを起動

```bash
lms server start --port 1234
```

{% endtab %}
{% endtabs %}

**クイックテスト：モデルを一覧表示**

```bash
curl http://localhost:1234/v1/models
```

**Python例（OpenAI SDK）：**

{% code expandable="true" %}

```python
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:1234/v1",
    api_key="lm-studio",  # LM Studioは実際のキーを必要としない場合があります；これは一般的なプレースホルダーです
)

resp = client.chat.completions.create(
    model="model-identifier-from-lm-studio",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello! What did I fine-tune you to do?"},
    ],
    temperature=0.7, # モデルのニーズに応じてtemperatureを調整
)

print(resp.choices[0].message.content)
```

{% endcode %}

**cURL例（chat completions）：**

{% code expandable="true" %}

```bash
curl http://localhost:1234/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "model-identifier-from-lm-studio",
    "messages": [
      {"role": "user", "content": "Say this is a test!"}
    ],
    "temperature": 0.7 # モデルのニーズに応じてtemperatureを調整
  }'
```

{% endcode %}

{% hint style="info" %}
**デバッグのヒント：** フォーマット／テンプレートのトラブルシューティングをしている場合、LM Studioがモデルに送っている *生の* プロンプトを次のコマンドで検査できます： `lms log stream`
{% endhint %}

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

#### **モデルはUnslothで動作するがLM Studioの出力が意味不明／繰り返す**

これはほとんどの場合、 **プロンプトテンプレート／チャットテンプレートの不一致です**.

LM Studioは可能な場合、GGUFメタデータからプロンプトテンプレートを **自動検出** しますが、カスタムモデルやタグ付けが誤っているモデルは手動オーバーライドが必要な場合があります。

**修正：**

1. に移動します **マイモデル** → モデルの横にある歯車⚙️をクリック
2. を探す **プロンプトテンプレート** そして、トレーニングに使ったテンプレートと一致するように設定します
3. または、Chatサイドバーで： 有効にします **プロンプトテンプレート** ボックス（常に表示するように強制できます）

#### LM Studioが「マイモデル」に自分のモデルを表示しない

* を優先 `lms import /path/to/model.gguf`
* またはファイルが正しいフォルダ構造にあることを確認してください： `~/.lmstudio/models/publisher/model/model-file.gguf`

#### OOM／動作が遅い

* より小さい量子化を使用してください（例： `Q4_K_M`)
* コンテキスト長を短くする
* GPUオフロードを調整する（LM Studioの「モデルごとのデフォルト」／読み込み設定）

***

### さらに情報

* [LM Studio + Unslothブログ記事](https://lmstudio.ai/blog/functiongemma-unsloth) （FunctionGemmaのウォークスルー）：&#x20;
* LM Studuo [モデルのインポートドキュメント](https://lmstudio.ai/docs/app/advanced/import-model)
* LM Studio [プロンプトテンプレートのドキュメント](https://lmstudio.ai/docs/app/advanced/prompt-template)
* LM Studio [OpenAI互換APIのドキュメント](https://lmstudio.ai/docs/developer/openai-compat)


---

# Agent Instructions: 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/inference-and-deployment/lm-studio.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.
