跳转到内容
搜索文档

使用 HuggingFace AutoTrain 微调模型

最后更新 查看 MarkdownAgent 设置

微调 AI 模型让你有机会向模型添加额外训练数据。Workers AI 支持 Low-Rank Adaptation(LoRA)adapter,可用于微调我们的模型。

在本教程中,我们将探索如何创建自己的 LoRA。我们将重点介绍使用 AutoTrain 进行 LLM 微调

1. 使用训练数据创建 CSV 文件

首先创建 CSV(Comma Separated Values)文件。此文件仅有一列名为 text。通过单独一行添加单词 text 来设置表头。

现在你需要确定要向模型添加什么内容。

示例格式如下:

### Human: What is the meaning of life? ### Assistant: 42.

如果训练行包含换行符,应使用引号包裹。

"human: What is the meaning of life? \n bot: 42."

不同模型(如 Mistral)会提供特定的 chat template/instruction 格式

<s>[INST] What is the meaning of life? [/INST] 42</s>

2. 配置 HuggingFace Autotrain Advanced Notebook

打开 HuggingFace Autotrain Advanced Notebook

为了给 AutoTrain 提供足够内存,需要选择不同的 Runtime。在 Notebook 顶部菜单中选择 Runtime > Change Runtime Type。选择 A100。

Notebook 包含几个需要修改的交互式部分。

Project Config

修改以下字段

  • project_name:选择便于日后记忆的描述性名称
  • model_name:从我们支持的官方 HuggingFace 基础模型中选择之一:
    • mistralai/Mistral-7B-Instruct-v0.2
    • google/gemma-2b-it
    • google/gemma-7b-it
    • meta-llama/llama-2-7b-chat-hf

可选部分:Push to Hub

虽然使用 AutoTrain 不强制要求,但创建 HuggingFace 账户 有助于将微调产物保存在便于日后查阅的仓库中。

如果不进行 HuggingFace 设置,仍可从 Notebook 下载文件。

如有需要,请按照 Notebook 中的说明 创建账户和 token。

Section: Hyperparameters

我们只需修改其中几个字段,以确保在 Cloudflare Workers AI 上正常工作。

  • quantization(量化):将下拉菜单改为 none
  • lora-r:将值改为 8

3. 将 CSV 文件上传到 Notebook

Notebook 有文件夹结构,可通过点击左侧导航栏的文件夹图标访问。

创建名为 data 的文件夹。

你可以将 CSV 文件拖入 Notebook。

确保文件名为 train.csv

4. 执行 Notebook

在 Notebook 菜单中,选择 Runtime > Run All。

它将依次运行 Notebook 的每个 cell,先进行安装,然后配置并运行 AutoTrain 会话。

根据 train.csv 文件大小,这可能需要一些时间。

如果遇到以下错误,是由内存不足(Out of Memory)引起。你可能需要将 runtime 改为更大的 GPU 后端。

subprocess.CalledProcessError: Command '['/usr/bin/python3', '-m', 'autotrain.trainers.clm', '--training_config', 'blog-instruct/training_params.json']' died with <Signals.SIGKILL: 9>.

5. 下载 LoRA

可选:HuggingFace

如果推送到 HuggingFace,你将找到上面 project_name 中命名的新 model card。model card 默认为私有。导航到文件并下载以下列出的文件。

Notebook

在 Notebook 中也可以找到所需文件。会出现与 project_name 匹配的新文件夹。

下载以下文件:

  • adapter_model.safetensors
  • adapter_config.json

6. 更新 Adapter Config

需要在下载的 adapter_config.json 中添加一行。

"model_type": "mistral"

其中 model_type 为架构。当前有效值为 mistralgemmallama

7. 将微调上传到 Cloudflare 账户

现在有了文件,可以将它们添加到账户。

你可以使用 REST API 或 Wrangler

8. 在生成中使用微调

新微调设置完成后,即可在推理请求中使用它

这篇文档对您有帮助吗?