> ## Content Index
> Fetch the complete content index at: https://www.hubwiz.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# Unsloth+Ollama低成本定制LLM
- URL: https://www.hubwiz.com/blog/low-cost-llm-customization-with-unsloth-and-ollama/
- Published: 2024-12-14T19:56:49.000Z
- Updated: 2024-12-14T19:56:49.000Z
- Description: 我们将探讨如何利用 Ollama 进行高效的模型部署，深入研究量化的世界，并掌握使用最少资源进行微调的艺术。
- Author: admin
- Tags: TOOL, UNSLOTH, OLLAMA, #Import 2026-10-14 14:41

当我坐在办公桌前，盯着我那台值得信赖的 8GB MacBook Pro 时，我不禁感到兴奋与沮丧交织。大型语言模型 (LLM) 的世界充满了各种可能性，但每个教程和指南似乎都需要高端 GPU 或昂贵的云解决方案。作为一名预算有限的开发人员，我想知道：我还能成为这场人工智能革命的一部分吗？

这个问题让我踏上了探索、优化和创造性解决问题的旅程。我决心找到一种方法来使用强大的 LLM，即使没有顶级硬件。经过无数小时的研究和实验，我发现了一些技术和工具，让我能够在我那台普通的机器上本地下载、微调和运行开源模型。

在本指南中，我将分享我的劳动成果。我们将探讨如何利用 Ollama 进行高效的模型部署，深入研究量化的世界（资源受限环境中的游戏规则改变者），并掌握使用最少资源进行微调的艺术。无论你是学生、业余爱好者还是使用有限硬件的专业人士，这篇文章都会向你展示如何将计算受限的机器变成 AI 强国。

## 1、本地 LLM 开发的关键概念

在深入探讨技术细节之前，让我们先探讨一些关键概念，这些概念对于我们在资源受限的硬件上进行本地 LLM 开发至关重要。

### 1.1 开源模型

![](https://www.hubwiz.com/blog/content/images/2024/12/image-598.png)

开源 vs, 闭源

开源模型是我们方法的支柱。这些是机器学习模型，其代码和权重可供任何人免费使用、修改和分发。示例包括来自 LLAMA 系列、GPT-2 和 BERT 的模型。通过使用开源模型，我们可以避免与专有模型相关的高成本，并获得根据我们的特定需求定制它们的灵活性。

### 1.2 量化：使模型轻量化

![](https://www.hubwiz.com/blog/content/images/2024/12/image-599.png)

将 FP32 转换为 INT4

量化是一种降低模型中使用的数字精度的技术，通常从 32 位浮点数转换为 4 位整数等低位表示。此过程显著减少了模型的内存占用和计算要求，通常对性能的影响最小。对于我们资源受限的设置，量化不仅仅是一种优化——它是一种必需品，它使我们能够运行原本对于我们的系统来说太大的模型。

### 1.3 PEFT（参数高效微调）

![](https://www.hubwiz.com/blog/content/images/2024/12/image-600.png)

PEFT 是一组技术，允许我们通过仅更新模型参数的一小部分来微调大型模型。这种方法大大降低了微调的计算和内存要求，使其在资源有限的硬件上可行。我们将在微调过程中使用一种称为 LoRA（低秩自适应）的特定 PEFT 技术。

### 1.4 Ollama：你的本地 LLM 伴侣

![](https://www.hubwiz.com/blog/content/images/2024/12/image-601.png)

Ollama 是一款改变游戏规则的工具，可让我们在本地运行大型语言模型。它在设计时考虑到了效率，非常适合资源受限的环境，例如我们的 8GB MacBook Pro。Ollama 简化了在本地机器上下载、运行和管理 LLM 的过程，消除了设置这些模型所涉及的大部分复杂性。

### 1.5 GGUF：本地优化格式

GGUF 是一种针对语言模型的高效加载和运行进行了优化的文件格式。它对量化模型特别有用，是 Ollama 使用的格式。将我们微调的模型转换为 GGUF 将使我们能够在本地机器上高效地部署它们。

### 1.6 Unsloth：加速 LLM 训练和推理

![](https://www.hubwiz.com/blog/content/images/2024/12/image-602.png)

Unsloth 是一个功能强大的库，可优化 LLM 训练和推理。它提供了几个关键优势：

- 2 倍更快的微调和推理速度
- 高效的量化技术，可减少内存使用量
- 与 Hugging Face 的 Transformers 库无缝集成
- 支持各种模型架构，如 Llama、Mistral、Phi-3 等
- 自动 RoPE 缩放，实现灵活的序列长度
- 4 倍更快的 4 位量化模型下载速度

Unsloth 对于我们资源受限的设置是必需的，因为它使我们能够更有效地使用更大的模型，减少训练时间，并使我们能够运行可能对我们的硬件要求过高的模型。

通过理解这些关键概念，我们现在可以深入研究在本地使用 LLM 的实际方面。在以下部分中，我们将介绍在本地下载、微调和部署模型的过程，将这些概念付诸实践。

## 2、设置和安装步骤

步骤 1.) 下载 [Ollama](https://ollama.com/download/mac?ref=hubwiz.com) 以有效管理你的本地 LLM。

![](https://www.hubwiz.com/blog/content/images/2024/12/image-603.png)

步骤 2.) 打开一个新的 Google colab [笔记本](https://colab.research.google.com/?ref=hubwiz.com)或将 Unsloths [cookbook ](https://colab.research.google.com/drive/1WZDi7APtQ9VsvOrQSSC5DDtxq159j8iZ?usp=sharing&ref=hubwiz.com)复制到你的驱动器中。我们将使用 Unsloth 的 `Llama-3.2-3B-Instruct-bnb-4bit` 模型，并在编程书籍的 Hugging Face 数据集上对其进行微调。

步骤 3.) pip install unsloth python sdk:

```
%%capture
!pip install unsloth
# Also get the latest nightly Unsloth!
!pip uninstall unsloth -y && pip install --upgrade --no-cache-dir --no-deps git+https://github.com/unslothai/unsloth.git
```

步骤 4.) 加载模型

```
from unsloth import FastLanguageModel
import torch
max_seq_length = 2048 
dtype = None 
load_in_4bit = True

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name = "unsloth/Llama-3.2-3B-Instruct-bnb-4bit",
    max_seq_length = max_seq_length,
    dtype = dtype,
    load_in_4bit = load_in_4bit,
)
```

步骤 5.) 应用 LoRA 进行微调

```
model = FastLanguageModel.get_peft_model(
    model,
    r = 16, 
    target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
                      "gate_proj", "up_proj", "down_proj",],
    lora_alpha = 16,
    lora_dropout = 0, 
    bias = "none",    
    
    use_gradient_checkpointing = "unsloth", 
    random_state = 3407,
    use_rslora = False,  
    loftq_config = None, 
)
```

步骤 6.) 下载并准备数据：

```
from datasets import load_dataset
from unsloth import to_sharegpt
from unsloth import standardize_sharegpt
from unsloth import apply_chat_template

chat_template = """Below describes some details about a programming topic from a book.Provide information and explanations based on these details.
### Topic Details:
{INPUT}

### Explanation:
{OUTPUT}"""

dataset = load_dataset("open-phi/programming_books_llama", split = "train")
dataset = dataset.train_test_split(test_size = 0.5, seed = 3407)
dataset = to_sharegpt(
    dataset,
    merged_prompt = \
        "[[Topic: {topic}]]"\
        "[[\nHuman: Based on the topic '{topic}', please provide information about the following:\n{queries}]]"\
        "[[\nAssistant: Certainly! I'd be happy to help you with information about {topic}. Let's go through your queries:\n\n{context}]]"\
        "[[\nHuman: Thank you for that information. Can you elaborate on these key concepts related to {topic}?\n{concepts}]]"\
        "[[\nAssistant: Of course! I'd be glad to elaborate on those key concepts related to {topic}. Here's a more detailed explanation:\n\n{outline}]]"\
        "[[\nHuman: That's very helpful. Could you summarize the main points we've discussed about {topic}?]]"\
        "[[\nAssistant: Certainly! Here's a summary of the main points we've discussed about {topic}:\n\n]]",
    output_column_name = "markdown",
    conversation_extension = 5, 
)
standerized_dataset = standardize_sharegpt(dataset)
dataset = apply_chat_template(
    standerized_dataset,
    tokenizer = tokenizer,
    chat_template = chat_template,
    default_system_message = "You are an expert coding assistant",
)
```

步骤 7.) 初始化监督微调训练器/训练模型：

```
from trl import SFTTrainer
from transformers import TrainingArguments
from unsloth import is_bfloat16_supported
trainer = SFTTrainer(
    model = model,
    tokenizer = tokenizer,
    train_dataset = dataset,
    dataset_text_field = "text",
    max_seq_length = max_seq_length,
    dataset_num_proc = 2,
    packing = False, # Can make training 5x faster for short sequences.
    args = TrainingArguments(
        per_device_train_batch_size = 2,
        gradient_accumulation_steps = 4,
        warmup_steps = 5,
        max_steps = 60,
        # num_train_epochs = 1, # For longer training runs!
        learning_rate = 2e-4,
        fp16 = not is_bfloat16_supported(),
        bf16 = is_bfloat16_supported(),
        logging_steps = 1,
        optim = "adamw_8bit",
        weight_decay = 0.01,
        lr_scheduler_type = "linear",
        seed = 3407,
        output_dir = "outputs",
        report_to = "none", # Use this for WandB etc
    ),
)
trainer.get_train_dataloader().shuffle = True
trainer_stats = trainer.train()
```

步骤 8.) 将模型保存到q4\_k\_m GGUF:

```
if True: model.save_pretrained_gguf("model", tokenizer, quantization_method = "q4_k_m")
```

现在 Unsloth 允许你自动微调并创建 Modelfile，并将微调后的模型导出到 Ollama，但我发现自己创建这个更容易。

![](https://www.hubwiz.com/blog/content/images/2024/12/image-604.png)

步骤 9.) 与 Ollama 集成

在你的 IDE（我使用cursor）中创建一个文件夹、一个名为“Modelfile”的文本文件，并添加你保存的 gguf 文件。

你的 Modelfile.txt 应如下所示：

```
FROM "./Users/earlperry/Desktop/mymodels/unsloth.Q4_K_M.gguf"

TEMPLATE """Below are some instructions that describe some tasks. Write responses that appropriately complete each request.{{ if .Prompt }}

### Instruction:
{{ .Prompt }}{{ end }}

### Response:
{{ .Response }}<|end_of_text|>"""

PARAMETER stop "<|eot_id|>"
PARAMETER stop "<|start_header_id|>"
PARAMETER stop "<|end_header_id|>"
PARAMETER stop "<|end_of_text|>"
PARAMETER stop "<|reserved_special_token_"
PARAMETER temperature 1.5
PARAMETER min_p 0.1
```

在 Ollama 中运行模型：

```
#create model in Ollama
ollama create prog-llama -f Modelfile.txt
#Run model in Ollama
ollama run prog-llama
```

## 3、结束语

通过结合 Ollama、Unsloth 和开源模型，本指南展示了使用最先进的 LLM 并不需要花费太多。通过利用量化和 PEFT 等技术，你可以克服硬件限制，但仍能取得令人印象深刻的成果。无论你是探索 AI 的学生，还是预算有限的创新专业人士，此设置都为参与 AI 革命提供了一条实用途径。开始微调并释放 AI 的力量——所有这些都可以在你的小型机器上完成。

---

原文链接：[Unleashing AI Power on a Budget:Fine-tuning LLMs with Ollama and Unsloth](https://medium.com/@earlperry562/unleashing-ai-power-on-a-budget-fine-tuning-llms-with-ollama-and-unsloth-89b5e5a1aa7e?ref=hubwiz.com)

汇智网翻译整理，转载请标明出处