跳至主要内容

Zephyr-7B 全面指南:特性、用法与微调

全面了解 Zephyr-7B,包括其训练方式、如何访问,以及如何使用免费的 Kaggle GPU 在自定义数据库上进行微调。
· 12分钟 阅读

使用 AI 探索

大家都在关注OpenAI LLM 排行榜以及那些力图达到 GPT-4 水平的新开源模型。最近备受瞩目的模型之一就是 Zephyr-7B。

在本教程中,我们将了解一款名为 Zephyr-7B 的新语言模型。我们将使用 Transformers 的 pipeline 来访问它,并在 Agent-Instruct 数据集上对模型进行微调。

如果您是人工智能新手,欢迎查看AI 基础技能路径。它将为您打好基础,引领您走上成为未来 AI 工程师的道路。

了解 Zephyr-7B

Zephyr-7B 是由 WebPilot.AI 开发的前沿语言模型。它隶属于 Zephyr 系列语言模型,这些模型经过训练,可充当有用的助手。Zephyr-7B 旨在在多种基于语言的任务中表现出色,例如生成连贯文本、进行跨语言翻译、概括关键信息、情感分析,以及基于上下文回答问题。

Zephyr-7B-β

Zephyr-7B-β 是该系列的第二个模型。它是在 Mistral-7B 模型基础上微调而来,使用了公共与合成数据集的组合,并采用直接偏好优化(DPO)进行训练。因此,Zephyr-7B-β 展现出从解读复杂问题到概括长文本段落的多样能力。

在发布时,Zephyr-7B-β 在 MT-Bench 和 AlpacaEval 基准中位列 7B 聊天模型之首。它借助自然语言处理的最新进展,在理解与生成类人文本方面达到了新的高度。

您可以通过在 Zephyr Chat 上试用免费演示来体验其性能提升。

image3.png

图片来源:Zephyr Chat

访问 Zephyr-7B

与Mistral 7B 教程类似,我们将使用 Hugging Face 的 transformers 来加载并使用 Zephyr-7B-beta。过程非常直接。

注意:如果您在加载模型时遇到问题,请查看推理 Kaggle 笔记本。

首先,安装所有必要的库。请确保您运行的是最新版本,否则无法正常工作。

!pip install -q -U transformers
!pip install -q -U accelerate
!pip install -q -U bitsandbytes

接着,从 transformers 中加载 Pytorch 库和 pipeline 模块。

import torch
from transformers import pipeline

我们将通过提供模型名称、torch_dtype 和 device_map 参数来构建文本生成的 pipeline。

device_map 中的“auto”表示可以使用多块 GPU 来更快地生成回答。

torch.bfloat16(brain float)是一种 16 位浮点数据类型,其指数位大小与 torch.float32 相同,但尾数位更少。这有助于加快计算速度并降低内存占用,但也会降低精度与准确性。

model_name = "HuggingFaceH4/zephyr-7b-beta"

pipe = pipeline(
    "text-generation",
    model=model_name,
    torch_dtype=torch.bfloat16,
    device_map="auto",
)

我们需要向 pipeline 对象提供提示词以及其他必要参数,并打印返回结果。

prompt = "Write a Python function that can clean the HTML tags from the file:"

outputs = pipe(
    prompt,
    max_new_tokens=300,
    do_sample=True,
    temperature=0.7,
    top_k=50,
    top_p=0.95,
)
print(outputs[0]["generated_text"])

结果非常出色。它给出了带注释的 Python 代码。

image11.png

我们甚至可以通过以 Zephyr-7B 风格提供系统提示词,来自定义模型输出。

我们将使用函数 pipe.tokenizer.apply_chat_template,通过字典列表来创建提示词。字典包含关于聊天助手的角色与行为,以及用户提示的信息。

messages = [
    {
        "role": "system",
        "content": "You are a skilled software engineer who consistently produces high-quality Python code.",
    },
    {
        "role": "user",
        "content": "Write a Python code to display text in a star pattern.",
    },
]

prompt = pipe.tokenizer.apply_chat_template(
    messages, tokenize=False, add_generation_prompt=True
)

最后,我们将把提示词和附加参数传入 pipeline 对象以生成回答。

outputs = pipe(
    prompt,
    max_new_tokens=300,
    do_sample=True,
    temperature=0.7,
    top_k=50,
    top_p=0.95,
)
print(outputs[0]["generated_text"])

Zephyr-7B 给出了最优方案,并附带了解释与函数输出。效果很棒。大家不妨用它来生成 Python 代码。

image6.png

微调 Zephyr-7B

本节我们将学习如何使用 Kaggle 免费 GPU 在自定义数据集上微调 Zephyr-7B-beta 模型。按照说明操作,您仅需两小时即可让模型做好部署准备。

注意:如果您在训练模型时遇到问题,请查看微调 Kaggle 笔记本。

环境准备

首先,安装加载数据集与模型并进行微调所需的 Python 库。

%%capture
%pip install -U bitsandbytes
%pip install -U transformers
%pip install -U peft
%pip install -U accelerate
%pip install -U trl

接着,我们将加载必要的模块,以便在内存有限的情况下更轻松地训练模型。

from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    BitsAndBytesConfig,
    HfArgumentParser,
    TrainingArguments,
    pipeline,
    logging,
)
from peft import (
    LoraConfig,
    PeftModel,
    prepare_model_for_kbit_training,
    get_peft_model,
)
import os, torch, wandb
from datasets import load_dataset
from trl import SFTTrainer

本节针对 Kaggle 笔记本。我们已将 Hugging Face 和 Weights & Biases(wandb)的 API 密钥添加到 Kaggle secrets 中。我们将安全地使用它们,将模型上传至 Hugging Face Hub,并在 Weights and Biases 服务器上实时监控训练过程。

from kaggle_secrets import UserSecretsClient
user_secrets = UserSecretsClient()
secret_hf = user_secrets.get_secret("HUGGINGFACE_TOKEN")
secret_wandb = user_secrets.get_secret("wandb")

使用 CLI 与 API 密钥登录 Hugging Face。

!huggingface-cli login --token $secret_hf

同样地,登录 wandb 并初始化项目。

# Monitoring the LLM
wandb.login(key = secret_wandb)
run = wandb.init(
    project='Fine tuning Zephyr 7B', 
    job_type="training", 
    anonymous="allow"
)

image2.png

提供用于微调、保存并推送到 Hugging Face Hub 的基础模型名、数据集名与新模型名。

base_model = "HuggingFaceH4/zephyr-7b-beta"
dataset_name = "THUDM/AgentInstruct"
new_model = "zephyr-7b-beta-Agent-Instruct"

AgentInstruct 数据集

我们将先加载数据集,然后使用 format_prompt 函数将其转换为 Zephyr-7B 的提示词风格。该函数从数据集中提取角色与内容,并将其转换为长字符串,这些字符串以系统提示开头,以默认指令结尾。

#Importing the dataset
dataset = load_dataset("THUDM/AgentInstruct", split="train")
def format_prompt(sample):
    intro = "Below is a conversation between a user and you."
    end = "Instruction: Write a response appropriate to the conversation."

    try:
        formatted_conversations = "\n".join(
            f"<{resp['from']}>: {resp['value']}"
            for resp in sample["conversations"]
        )

        sample["text"] = f"{intro}\n\n{formatted_conversations}\n\n{end}"
    except (TypeError, KeyError):
        raise ValueError("Invalid format of the input sample.")
    return sample


dataset = dataset.map(
    format_prompt,
    remove_columns=["conversations"]
)
dataset["text"][100]

image1.png

加载模型与分词器

我们将从 Hugging Face 下载并加载 4 比特精度的模型,以加快训练速度。这对于显存有限的 GPU 微调是必要的。之后我们会加载分词器,并对其进行配置,以修复与 fp16 相关的问题。

bnb_config = BitsAndBytesConfig(  
    load_in_4bit= True,
    bnb_4bit_quant_type= "nf4",
    bnb_4bit_compute_dtype= torch.bfloat16,
    bnb_4bit_use_double_quant= False,
)
model = AutoModelForCausalLM.from_pretrained(
        base_model,
        load_in_4bit=True,
        quantization_config=bnb_config,
        torch_dtype=torch.bfloat16,
        device_map="auto",
        trust_remote_code=True,
)
model.config.use_cache = False
model.config.pretraining_tp = 1
model.gradient_checkpointing_enable()

# Load tokenizer
tokenizer = AutoTokenizer.from_pretrained(base_model, trust_remote_code=True)
tokenizer.padding_side = 'right'
tokenizer.pad_token = tokenizer.eos_token
tokenizer.add_eos_token = True
tokenizer.add_bos_token, tokenizer.add_eos_token

构建模型

现在我们将为模型添加一个适配器层,使其能够更高效地微调。我们不会微调整个模型,而是仅更新适配器层中的参数,以加快训练。

model = prepare_model_for_kbit_training(model)
peft_config = LoraConfig(
    lora_alpha=16,
    lora_dropout=0.1,
    r=64,
    bias="none",
    task_type="CAUSAL_LM",
    target_modules=['up_proj', 'base_layer', 'down_proj']
)
model = get_peft_model(model, peft_config)

训练模型

在训练参数中设置合适的超参数非常重要。您可以通过阅读微调 LLaMA 2教程来了解每个参数。

然后,我们将使用 HuggingFace 的 TRL 库构建 SFT Trainer,传入模型、数据集、Lora 配置、分词器和训练参数等必要组件。

最后,开始训练。

#Hyperparamter
training_arguments = TrainingArguments(
    output_dir="./results",
    num_train_epochs=1,
    per_device_train_batch_size=4,
    gradient_accumulation_steps=1,
    optim="paged_adamw_32bit",
    save_steps=25,
    logging_steps=25,
    learning_rate=2e-4,
    weight_decay=0.001,
    fp16=False,
    bf16=False,
    max_grad_norm=0.3,
    max_steps=-1,
    warmup_ratio=0.03,
    group_by_length=True,
    lr_scheduler_type="constant",
    report_to="wandb"
)


# Setting sft parameters
trainer = SFTTrainer(
    model=model,
    train_dataset=dataset,
    peft_config=peft_config,
    max_seq_length= 512,
    dataset_text_field="text",
    tokenizer=tokenizer,
    args=training_arguments,
    packing= False,
)


trainer.train()

经过将近 1 小时 40 分钟,训练结束,我们观察到训练损失稳步下降。

image10.png

以下是来自 Weights & Biases 的更详细的模型评估。

image8.png

现在我们将保存模型、结束 wandb 实例,并将模型推送到 Hugging Face Hub。这将创建一个包含已保存适配器文件的模型仓库。

# Save the fine-tuned model
trainer.model.save_pretrained(new_model)
wandb.finish()

trainer.model.push_to_hub(new_model, use_temp_dir=False)

image9.png

这是微调后的模型仓库,您可以通过以下地址访问:hf.co/kingabzpro/zephyr-7b-beta-Agent-Instruct

image7.png

现在是时候在各种提示词上测试我们的微调模型了。

我们请模型介绍如何在 DataCamp 上在线使用 Python。

logging.set_verbosity(logging.CRITICAL)

prompt = "How to use Python online with DataCamp?"
pipe = pipeline(task="text-generation", model=model, tokenizer=tokenizer, max_length=200)
result = pipe(prompt)
print(result[0]['generated_text'])

我们可以看到,其回答与AgentGPT 相似。AgentGPT 是一种自动化 AI 代理,能借助多种扩展执行多个任务,并取得与先进 AI 系统一样的效果。这些系统可以执行类似人类的任务,例如网页搜索、更新代码与测试。

image5.png

我们不再请求步骤列表,而是就 DataCamp 的职业路径向模型提出一个简单问题。

prompt = "What is Datacamp Career track?"
result = pipe(prompt)
print(result[0]['generated_text'])

我们收到了答案,但它引出了更多的问答(并非全部准确),这很有意思。

image4.png

接下来,您可以用这个模型来构建 AI 应用。为此,您需要能让工作更轻松的工具。这里有一份7 款生成式 AI 必备工具清单,可助您打造出色的 AI 应用。

结语

Zephyr-7B-beta 大语言模型在理解与给出准确回答方面展现了惊人的能力。在本教程中,我们学习了 Zephyr-7B,并了解了如何使用 Transformers pipeline 访问它。我们还学习了如何在自定义 Agent 数据集上对其进行微调,使其具备更强的推理能力,并能给出类似 AgentGPT 的指令式回答。

本指南是面向各个层次机器学习爱好者的综合资源,适合在显存有限的 GPU 上试验与微调大语言模型。

报名参加掌握大语言模型(LLMs)概念课程,学习与 Zephyr-7B 类似的 LLM 组件、训练方法与技术。

Abid Ali Awan

作者

Abid Ali Awan

作为一名持证的数据科学家,我热衷于利用前沿技术打造创新的机器学习应用。凭借在语音识别、数据分析与报告、MLOps、对话式人工智能以及自然语言处理方面的扎实背景,我不断打磨构建智能系统的能力,力求带来切实影响。除技术专长外,我也擅长沟通,能够将复杂概念提炼为清晰、简明的表述。因此,我成为数据科学领域备受关注的博主,与不断壮大的数据专业人士社区分享洞见与实践经验。目前,我专注于内容创作与编辑,借助大语言模型打造有力且吸引人的内容,帮助企业与个人更好地发挥数据价值。

主题