柏拉图数据智能。
垂直搜索和人工智能。

使用 @remote 装饰器在 Amazon SageMaker 上微调 Falcon 7B 和其他 LLM | 亚马逊网络服务

日期:

如今,生成式人工智能模型涵盖了从文本摘要、问答以及图像和视频生成等各种任务。 为了提高输出质量,可以采用 n-short 学习、即时工程、 检索增强生成 (RAG) 并使用微调。 通过微调,您可以调整这些生成式 AI 模型,以提高特定领域任务的性能。

亚马逊SageMaker,现在您只需使用以下命令注释您的 Python 代码即可运行 SageMaker 训练作业 @远程装饰器。 该 SageMaker Python 开发工具包 自动将您现有的工作区环境以及任何关联的数据处理代码和数据集转换为在训练平台上运行的 SageMaker 训练作业。 这样做的优点是能够以更自然、面向对象的方式编写代码,并且仍然使用 SageMaker 功能在远程集群上运行训练作业,只需进行最少的更改。

在这篇文章中,我们展示了如何微调 猎鹰7B 使用 SageMaker Python SDK 中的 @remote 装饰器的基础模型 (FM)。 它还使用 Hugging Face 的参数高效微调 (PEFT)库和量化技术通过 位和字节 以支持微调。 本博客中提供的代码也可用于微调其他 FM,例如 骆驼-2 13b.

该模型的完整精度表示可能难以适应单个甚至多个内存 图形处理单元 (GPU) ——或者甚至可能需要一个更大的实例。 因此,为了在不增加成本的情况下微调该模型,我们使用称为 具有低阶适配器的量化 LLM (QLoRA)。 QLoRA 是一种高效的微调方法,可以减少 LLM 的内存使用量,同时保持非常好的性能。

使用@remote装饰器的优点

在进一步讨论之前,我们先了解一下远程装饰器在使用 SageMaker 时如何提高开发人员的工作效率:

  • @remote 装饰器直接使用本机 python 代码触发训练作业,无需显式调用 SageMaker Estimators 和 SageMaker 输入通道
  • 开发人员在 SageMaker 上训练模型的进入门槛较低。
  • 无需切换 集成开发环境 (IDE)。 继续在您选择的 IDE 中编写代码并调用 SageMaker 训练作业。
  • 无需了解容器。 继续在 a 中提供依赖项 requirements.txt 并将其提供给远程装饰器。

先决条件

需要一个 AWS 账户 AWS身份和访问管理 (AWS IAM) 角色 有权管理作为解决方案的一部分创建的资源。 详情请参阅 创建 AWS 账户.

在这篇文章中,我们使用 亚马逊SageMaker StudioData Science 3.0 图像和一个 ml.t3.medium 快速启动实例。 但是,您可以使用您选择的任何集成开发环境 (IDE)。 你只需要设置你的 AWS命令行界面 (AWS CLI) 凭证正确。 欲了解更多信息,请参阅 配置 AWS CLI.

为了进行微调,Falcon-7B ml.g5.12xlarge 这篇文章中使用了实例。 请确保AWS账户中有足够的容量用于该实例。

你需要克隆这个 Github存储库 用于复制本文中演示的解决方案。

解决方案概述

  1. 安装微调 Falcon-7B 模型的先决条件
  2. 设置远程装饰器配置
  3. 预处理包含 AWS 服务常见问题解答的数据集
  4. 在 AWS 服务上微调 Falcon-7B 常见问题解答
  5. 针对与 AWS 服务相关的示例问题测试微调模型

1. 安装微调 Falcon-7B 模型的先决条件

启动笔记本 falcon-7b-qlora-remote-decorator_qa.ipynb 在 SageMaker Studio 中选择 I法师 as Data Science核心 as Python 3。 安装中提到的所有必需的库 requirements.txt。 很少有库需要安装在笔记本实例本身上。 执行数据集处理和触发 SageMaker 训练作业所需的其他操作。

%pip install -r requirements.txt %pip install -q -U transformers==4.31.0
%pip install -q -U datasets==2.13.1
%pip install -q -U peft==0.4.0
%pip install -q -U accelerate==0.21.0
%pip install -q -U bitsandbytes==0.40.2
%pip install -q -U boto3
%pip install -q -U sagemaker==2.154.0
%pip install -q -U scikit-learn

2. 设置远程装饰器配置

创建一个配置文件,其中指定与 Amazon SageMaker 训练作业相关的所有配置。 该文件由 @remote 装饰器在运行训练作业时读取。 该文件包含依赖项、训练映像、实例以及用于训练作业的执行角色等设置。 有关配置文件支持的所有设置的详细参考,请查看 使用 SageMaker Python 开发工具包配置和使用默认值.

SchemaVersion: '1.0'
SageMaker: PythonSDK: Modules: RemoteFunction: Dependencies: ./requirements.txt ImageUri: '{aws_account_id}.dkr.ecr.{region}.amazonaws.com/huggingface-pytorch-training:2.0.0-transformers4.28.1-gpu-py310-cu118-ubuntu20.04' InstanceType: ml.g5.12xlarge RoleArn: arn:aws:iam::111122223333:role/ExampleSageMakerRole

不强制要求使用 config.yaml 文件以便与 @remote 装饰器一起使用。 这只是向 @remote 装饰器提供所有配置的更简洁的方式。 这将 SageMaker 和 AWS 相关参数保留在代码之外,只需一次性设置团队成员使用的配置文件即可。 所有配置也可以直接在装饰器参数中提供,但从长远来看,这会降低更改的可读性和可维护性。 此外,配置文件可以由管理员创建并与环境中的所有用户共享。

预处理包含 AWS 服务常见问题解答的数据集

下一步是加载和预处理数据集,使其为训练工作做好准备。 首先,让我们看一下数据集:

它显示了一项 AWS 服务的常见问题解答。 除了 QLoRA 之外, bitsanbytes 用于转换为 4 位精度,以将冻结的 LLM 量化为 4 位并附加 劳拉 适配器就可以了。

创建提示模板以将每个常见问题解答示例转换为提示格式:

from random import randint # custom instruct prompt start
prompt_template = f"{{question}}n---nAnswer:n{{answer}}{{eos_token}}" # template dataset to add prompt to each sample
def template_dataset(sample): sample["text"] = prompt_template.format(question=sample["question"], answer=sample["answers"], eos_token=tokenizer.eos_token) return sample

下一步是将输入(文本)转换为令牌 ID。 这是由一个 拥抱脸变形金刚分词器.

from transformers import AutoTokenizer model_id = "tiiuae/falcon-7b" tokenizer = AutoTokenizer.from_pretrained(model_id)
# Set the Falcon tokenizer
tokenizer.pad_token = tokenizer.eos_token

现在只需使用 prompt_template 函数将所有常见问题解答转换为提示格式并设置训练和测试数据集。

4. 在 AWS 服务上微调 Falcon-7B 常见问题解答

现在您可以准备训练脚本并定义训练函数 train_fn 并将 @remote 装饰器放在该函数上。

训练函数执行以下操作:

  • 对数据集进行标记和分块
  • 设立 BitsAndBytesConfig,它指定模型应以 4 位加载,但计算应转换为 bfloat16.
  • 加载模型
  • 使用实用程序方法查找目标模块并更新必要的矩阵 find_all_linear_names
  • 创建 劳拉 指定更新矩阵排名的配置(s),比例因子(lora_alpha),应用 LoRA 更新矩阵的模块(target_modules), Lora 层的 dropout 概率(lora_dropout), task_type等等。
  • 开始培训和评估
import bitsandbytes as bnb def find_all_linear_names(hf_model): lora_module_names = set() for name, module in hf_model.named_modules(): if isinstance(module, bnb.nn.Linear4bit): names = name.split(".") lora_module_names.add(names[0] if len(names) == 1 else names[-1]) if "lm_head" in lora_module_names: lora_module_names.remove("lm_head") return list(lora_module_names)
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from sagemaker.remote_function import remote
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
import transformers # Start training
@remote(volume_size=50)
def train_fn( model_name, train_ds, test_ds, lora_r=8, lora_alpha=32, lora_dropout=0.05, per_device_train_batch_size=8, per_device_eval_batch_size=8, learning_rate=2e-4, num_train_epochs=1
): # tokenize and chunk dataset lm_train_dataset = train_ds.map( lambda sample: tokenizer(sample["text"]), batched=True, batch_size=24, remove_columns=list(train_dataset.features) ) lm_test_dataset = test_ds.map( lambda sample: tokenizer(sample["text"]), batched=True, remove_columns=list(test_dataset.features) ) # Print total number of samples print(f"Total number of train samples: {len(lm_train_dataset)}") bnb_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16 ) # Falcon requires you to allow remote code execution. This is because the model uses a new architecture that is not part of transformers yet. # The code is provided by the model authors in the repo. model = AutoModelForCausalLM.from_pretrained( model_name, trust_remote_code=True, quantization_config=bnb_config, device_map="auto") model.gradient_checkpointing_enable() model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=True) # get lora target modules modules = find_all_linear_names(model) print(f"Found {len(modules)} modules to quantize: {modules}") config = LoraConfig( r=lora_r, lora_alpha=lora_alpha, target_modules=modules, lora_dropout=lora_dropout, bias="none", task_type="CAUSAL_LM" ) model = get_peft_model(model, config) print_trainable_parameters(model) trainer = transformers.Trainer( model=model, train_dataset=lm_train_dataset, eval_dataset=lm_test_dataset, args=transformers.TrainingArguments( per_device_train_batch_size=per_device_train_batch_size, per_device_eval_batch_size=per_device_eval_batch_size, logging_steps=2, num_train_epochs=num_train_epochs, learning_rate=learning_rate, bf16=True, save_strategy="no", output_dir="outputs" ), data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False), ) model.config.use_cache = False trainer.train() trainer.evaluate() model.save_pretrained("/opt/ml/model")

并调用 train_fn()

train_fn(model_id, train_dataset, test_dataset)

调优作业将在 Amazon SageMaker 训练集群上运行。 等待调整工作完成。

5. 在与 AWS 服务相关的示例问题上测试微调模型

现在,是时候对模型进行一些测试了。 首先,让我们加载模型:

from peft import PeftModel, PeftConfig
import torch
from transformers import AutoModelForCausalLM device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu' config = PeftConfig.from_pretrained("./model")
model = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path, trust_remote_code=True)
model = PeftModel.from_pretrained(model, "./model")
model.to(device)

现在从训练数据集中加载一个示例问题以查看原始答案,然后从调整后的模型中询问相同的问题以查看比较的答案。

这是训练集中的问题示例和原始答案:

现在,同样的问题被问到调整 Falcon-7B 模型:

使用 Amazon SageMaker Python SDK 中的 @remote 装饰器在 AWS 服务常见问题解答数据集上微调 Falcon-7B 的实施到此结束。

打扫干净

完成以下步骤以清理您的资源:

  • 关闭 Amazon SageMaker Studio 实例以避免产生额外费用。
  • 清理您的 Amazon Elastic 文件系统 (亚马逊 EFS) 目录,通过清除 Hugging Face 缓存目录:
    rm -R ~/.cache/huggingface/hub

结论

在这篇文章中,我们向您展示了如何有效地使用 @remote 装饰器的功能,使用 QLoRA、Hugging Face PEFT 和 bitsandbtyes 无需在训练笔记本中进行重大更改,并使用 Amazon SageMaker 功能在远程集群上运行训练作业。

本文中显示的用于微调 Falcon-7B 的所有代码均可在 GitHub存储库。 该存储库还包含显示如何微调 Llama-13B 的笔记本。

下一步,我们鼓励您查看 @remote装饰器功能Python SDK API 并在您选择的环境和 IDE 中使用它。 其他示例可在 amazon-sagemaker 示例 存储库可帮助您快速入门。 您还可以查看以下帖子:


作者简介

布鲁诺·皮斯通 是一位位于米兰的 AWS 人工智能/机器学习专家解决方案架构师。 他与大客户合作,帮助他们深入了解自己的技术需求,并设计充分利用 AWS 云和 Amazon 机器学习堆栈的 AI 和机器学习解决方案。 他的专业知识包括:端到端机器学习、机器学习工业化和生成人工智能。 他喜欢与朋友共度时光,探索新的地方,以及去新的目的地旅行。

维克什·潘迪 是 AWS 的机器学习专家解决方案架构师,帮助金融行业的客户设计和构建基于生成式 AI 和 ML 的解决方案。 工作之余,Vikesh 喜欢尝试不同的美食和进行户外运动。

现货图片

最新情报

现货图片

在线答疑

你好呀! 我怎么帮你?