当前位置:   article > 正文

收下实操教程!立即使用 Amazon SageMaker 部署 Baichuan-2 模型!

收下实操教程!立即使用 Amazon SageMaker 部署 Baichuan-2 模型!

80eb4318b8f9b56c4f6129496fd1d6dd.gif

前言

随着各类生成式 AI 技术与服务的发展,国内外各种大语言模型竞相出炉,在其基础上衍生出种类繁多的应用场景。模型的部署推理在整个模型的应用中占据极其重要的地位,易用、稳定、可扩展、可维护等诸多要素使得部署模型的推理服务变得极具挑战性。

Amazon SageMaker 是亚马逊云科技一项完全托管的服务,旨在简化机器学习的开发、训练和部署过程,提供了端到端的机器学习解决方案,包括数据准备、模型训练、模型调优、部署和推理等。同时可以根据需要自动扩展计算资源,使其能够处理大规模的训练任务。这种弹性使得用户能够高效地利用云计算的强大计算能力,而无需担心基础架构的管理和维护。

本文将通过具体模型在 Amazon SageMaker 上的部署示例来讲解如何快速高效地基于其部署开源大语言模型。

Baichuan-2 总体介绍

Baichuan-2 是百川智能推出的新一代开源大语言模型,采用 2.6 万亿 Tokens 的高质量语料训练,新系列发布包含有 7B、13B 的 Base 和 Chat 版本,不仅继承了上一代良好的生成与创作能力,流畅的多轮对话能力以及部署门槛较低等众多特性,而且在数学、代码、安全、逻辑推理、语义理解等能力有显著提升。

Baichuan-2 部署介绍

SageMaker 维护了一整套 deep learning containers(DLCs)用于在亚马逊云科技基础设施上部署开源模型,包括 Llama、Baichuan在内。在 DLCs 之上,SageMaker 集成了一系列开源的第三方框架,包括 DeepSpeed、Accelerate 和 FasterTransformer,形成了 Large Model Inference(LMI)用于大语言模型的加速推理。

在使用 LMI 部署大语言模型的时候需要指定 tarball 的格式,如下所示:

code
├────
│   └── model.py
│   └── requirements.txt
│   └── serving.properties

  • model.py 核心文件,指示如何加载模型及处理接收请求。

  • requirements.txt 指示模型加载和推理的依赖包。

  • serving.properties 指示模型的环境变量,包括推理引擎、文件位置、模型并发度等。

Baichuan-2 环境设置

1.升级 Python SDK

pip install -U sagemaker

2.获取运行时资源,包括区域、角色、账号、Amazon S3 桶等

  1. import boto3
  2. import sagemaker
  3. from sagemaker import get_execution_role
  4. sess                     = sagemaker.Session()
  5. role                     = get_execution_role()
  6. sagemaker_default_bucket = sess.default_bucket()
  7. account                  = sess.boto_session.client("sts").get_caller_identity()["Account"]
  8. region                   = sess.boto_session.region_name

左右滑动查看完整示意

0af668c2ad0f6e0425c97b64c1b03883.png

扫码进入代码仓库

获取示例代码

Baichuan-2 部署推理

部署准备

安装依赖包

pip install huggingface_hub

左右滑动查看完整示意

下载 Baichuan-2 原始模型

为便于后续的复现性和持续迭代,下载原始模型时应指定 commit-id,不同的 commit-id 对应不同的模型处理和参数。

  1. from huggingface_hub import snapshot_download
  2. from pathlib import Path
  3. local_cache_path = Path("./model")
  4. local_cache_path.mkdir(exist_ok=True)
  5. model_name = "baichuan-inc/Baichuan2-7B-Chat"
  6. # Only download pytorch checkpoint files
  7. allow_patterns = ["*.json", "*.pt", "*.bin", "*.model", "*.py", "*.txt"]
  8. # Version is from 2023-09-18
  9. model_download_path = snapshot_download(
  10.    repo_id=model_name,
  11.    cache_dir=local_cache_path,
  12.    allow_patterns=allow_patterns,
  13.    revision='229e4eb1fab7f6aef90a2344c07085b680487597'
  14. )

左右滑动查看完整示意

拷贝模型和数据到 S3

  1. # Get the model files path
  2. import os
  3. from glob import glob
  4. local_model_path = None
  5. paths = os.walk(r'./model')
  6. for root, dirs, files in paths:
  7.    for file in files:
  8.        if file == 'config.json':
  9.            print(os.path.join(root,file))
  10.            local_model_path = str(os.path.join(root,file))[0:-11]
  11.            print(local_model_path)
  12. if local_model_path == None:
  13.    print("Model download may failed, please check prior step!")
  14.    
  15. %%script env sagemaker_default_bucket=$sagemaker_default_bucket local_model_path=$local_model_path bash
  16. chmod +x ./s5cmd
  17. ./s5cmd sync ${local_model_path} s3://${sagemaker_default_bucket}/llm/models/baichuan2/baichuan-inc/Baichuan2-7B-Chat/
  18. rm -rf model

左右滑动查看完整示意

模型部署

  • 模型的微调使用全参数模型,以实现微调后模型的稳定性。

  • 模型的微调使用开源框架 DeepSpeed 进行加速。

准备 serving.properties

  • 引擎选择 DeepSpeed。

  • 张量并行度选择 1。模型 GPU 显卡内存占用与其尺寸成正比,以常见的半精度模型为例,计算公式:显存占用量(单位/GB) ~= 2 * 每 10 亿参数;如果是 Baichuan2-7B 模型,大致的 GPU 显存需求 = 7 * 2 = 14GB。以 Nvidia A10 为例,单卡的显存为 24GB,模型可以部署在单张显卡内,因此并行度选择 1。

  • 指定模型存储的 S3 桶。

  1. %%writefile ./src/serving.properties
  2. engine=DeepSpeed
  3. option.tensor_parallel_degree=1
  4. option.s3url=${option.s3url}

左右滑动查看完整示意

准备 requirements.txt

requirements.txt 主要用于指定依赖包:

  • 对于 Baichuan 2-7B-Chat,需要选用 transformers==4.29.2 版本以实现更好的兼容性和稳定性。

  • 加入 xformers 和 peft 依赖包用于模型的加速和 PEFT 推理等。

  1. %%writefile ./src/requirements.txt
  2. transformers==4.29.2
  3. sagemaker
  4. nvgpu
  5. xformers
  6. peft

左右滑动查看完整示意

准备 model.py

model.py 文件较多,仅列出关键代码块,包括模型的加载和推理。

1.模型加载:一些需要注意的细节

  • 模型加载时,需加入”trust_remote_code=True”

  • Baichuan 2 的增加了额外配置文件,包括特定的 token,等需使用”GenerationConfig.from_pretrained(model_location)”读取

  1. model_location = "baichuan-inc/Baichuan2-7B-Chat"
  2. tokenizer = AutoTokenizer.from_pretrained(model_location, torch_dtype=torch.float16, use_fast=False, trust_remote_code=True)
  3. model = AutoModelForCausalLM.from_pretrained(model_location, device_map="auto", torch_dtype=torch.float16, trust_remote_code=True)
  4. model.generation_config = GenerationConfig.from_pretrained(model_location)

左右滑动查看完整示意

2.模型推理:Baichuan 2-Chat 推理过程中会引入“角色”,推理的提示词必须引入”role”: “user”、”role”: “assistant”格式来指定是用户询问还是模型的作答

  1. messages = []
  2. messages.append({"role": "user", "content": input_data})
  3. response = model.chat(tokenizer, messages)

左右滑动查看完整示意

指定推理镜像

  1. #Note that: you can modify the image url according to your specific region.
  2. inference_image_uri = "763104351884.dkr.ecr.us-west-2.amazonaws.com/djl-inference:0.23.0-deepspeed0.9.5-cu118"

左右滑动查看完整示意

创建模型

  1. from sagemaker.utils import name_from_base
  2. model_name = name_from_base(f"baichuan2-7b-chat-origin")
  3. print(model_name)
  4. role = sagemaker.get_execution_role()
  5. create_model_response = sm_client.create_model(
  6.    ModelName=model_name,
  7.    ExecutionRoleArn=role,
  8.    PrimaryContainer={
  9.        "Image": inference_image_uri,
  10.        "ModelDataUrl": s3_code_artifact,
  11.    },
  12. )
  13. model_arn = create_model_response["ModelArn"]

左右滑动查看完整示意

创建终端配置

  1. endpoint_config_name = f"{model_name}-config"
  2. endpoint_name = f"{model_name}-endpoint"
  3. endpoint_config_response = sm_client.create_endpoint_config(
  4.    EndpointConfigName=endpoint_config_name,
  5.    ProductionVariants=[
  6.        {
  7.            "VariantName": "variant1",
  8.            "ModelName": model_name,
  9.            "InstanceType": "ml.g5.2xlarge",
  10.            "InitialInstanceCount": 1,
  11.            "ContainerStartupHealthCheckTimeoutInSeconds": 15*60,
  12.        },
  13.    ],
  14. )

左右滑动查看完整示意

创建终端节点

  1. endpoint_name            = f"{model_name}-endpoint"
  2. create_endpoint_response = sm_client.create_endpoint(
  3.    EndpointName=f"{endpoint_name}",
  4.    EndpointConfigName=endpoint_config_name
  5. )

左右滑动查看完整示意

部署测试

  1. "top_k": 5,
  2.    "top_p": 0.85,
  3.    "repetition_penalty": 1.05
  4. }
  5. prompt = "解释一下“学而时习之”"
  6. response_model = smr_client.invoke_endpoint(
  7.            EndpointName=endpoint_name,
  8.            Body=json.dumps(
  9.            {
  10.                "inputs"    : prompt,
  11.                "parameters": parameters
  12.            }
  13.            ),
  14.            ContentType="application/json",
  15.        )
  16. response_model['Body'].read().decode('utf8')

左右滑动查看完整示意

总结

大语言模型方兴未艾,正在以各种方式改变和影响着整个世界。客户拥抱大语言模型,亚马逊云科技团队同样在深耕客户需求和大语言模型技术,在未来更好的协助客户实现需求、提升业务价值。

立即体验

即刻使用 Amazon SageMaker JumpStart 体验全球领先基础模型,扫描下方二维码,从 PC 端开始实验!

8746c9de1a87633363a8037e83dc4b19.png

本篇作者

c5ec5fd10f929daba6a433e764b2a01b.png

高郁

亚马逊云科技解决方案架构师,主要负责企业客户上云,帮助客户进行云架构设计和技术咨询,专注于智能湖仓、人工智能与机器学习等技术方向。

3f9e8e3a843b45b69bc4a86d24a78013.png

fc39ceeb355671940b8f9d4d8ee3b6d5.gif

星标不迷路,开发更极速!

关注后记得星标「亚马逊云开发者」

听说,点完下面4个按钮

就不会碰到bug了!

294ff79e5eda4400674c7662d445fc0b.gif

点击阅读原文查看博客,获得更详细内容

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/917536
推荐阅读
相关标签
  

闽ICP备14008679号