# 部署模型到 LM Studio

您可以直接在 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. **在 Chat 中加载它** （或在兼容 OpenAI 的本地 API 后端运行）

<div><figure><img src="https://2657992854-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://2657992854-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 提供一个名为 `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://2657992854-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. 前往 **发现** 选项卡
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，可以将 `.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. 打开 **模型加载器**
3. 选择您导入的模型
4. （可选）调整加载设置（GPU 卸载、上下文长度等）
5. 在界面中正常聊天

### 4) 将您微调的模型作为本地 API 提供服务（兼容 OpenAI）

LM Studio 可以在一个兼容 OpenAI 的 API 后端提供您已加载的模型（适用于 Open WebUI、自定义代理、脚本等应用）。

{% tabs %}
{% tab title="图形界面（开发者选项卡）" %}

1. 在 LM Studio 中加载您的模型
2. 前往 **开发者** 选项卡
3. 启动本地服务器
4. 使用显示的基础 URL（默认通常是 `http://localhost:1234/v1`)
   {% endtab %}

{% tab title="命令行（lms load + lms server start）" %}

#### 1) 列出可用模型

```bash
lms ls
```

#### 2) 加载您的模型（可选标志）

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

注意：

* `--gpu=1.0` 表示“尝试将 100% 卸载到 GPU”
* 您可以设置一个稳定的标识符：

```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, # 根据您的模型需求调整温度
)

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

{% endcode %}

**cURL 示例（聊天补全）：**

{% 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 # 根据您的模型需求调整温度
  }'
```

{% endcode %}

{% hint style="info" %}
**调试提示：** 如果您在排查格式/模板问题，可以通过运行来检查 LM Studio 发送给模型的 *原始* 提示（prompt）： `lms log stream`
{% endhint %}

### 故障排除

#### **模型在 Unsloth 中运行正常，但在 LM Studio 中输出乱码 / 重复**

这几乎总是一个 **提示模板 / 聊天模板 不匹配 的问题**.

LM Studio 将会 **自动检测** 在可能的情况下从 GGUF 元数据中检测提示模板，但自定义或标记不正确的模型可能需要手动覆盖。

**修复方法：**

1. 转到 **我的模型** → 点击您模型旁的齿轮 ⚙️
2. 找到 **提示模板** 并将其设置为与您用于训练的模板相匹配
3. 或者，在聊天侧边栏：启用 **提示模板** 复选框（您可以强制其始终显示）

#### LM Studio 未在“我的模型”中显示我的模型

* 更倾向于 `lms import /path/to/model.gguf`
* 或确认该文件位于正确的文件夹结构： `~/.lmstudio/models/publisher/model/model-file.gguf`

#### 内存不足 / 性能缓慢

* 使用较小的量化（例如： `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/zh/ji-chu/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.
