使用 Amazon SageMaker 异步终端节点优化 Amazon SageMaker JumpStart 基础模型的部署成本 | 亚马逊网络服务

使用 Amazon SageMaker 异步终端节点优化 Amazon SageMaker JumpStart 基础模型的部署成本 | 亚马逊网络服务

生成式人工智能应用在各行各业的成功吸引了世界各地公司的关注和兴趣,这些公司希望复制和超越竞争对手的成就或解决新的、令人兴奋的用例。 这些客户正在研究基础模型,例如 TII Falcon、Stable Diffusion XL 或 OpenAI 的 GPT-3.5,作为推动生成式 AI 创新的引擎。

基础模型是一类生成式人工智能模型,由于接受过大量非结构化数据的训练,它们能够理解和生成类似人类的内容。 这些模型彻底改变了各种计算机视觉 (CV) 和自然语言处理 (NLP) 任务,包括图像生成、翻译和问答。 它们是许多人工智能应用的构建模块,并已成为先进智能系统开发的关键组成部分。

然而,基础模型的部署可能会带来重大挑战,特别是在成本和资源需求方面。 这些模型以其规模而闻名,参数范围通常从数亿到数十亿不等。 它们的大尺寸需要大量的计算资源,包括强大的硬件和大量的内存容量。 事实上,部署基础模型通常需要至少一个(通常更多)GPU 来有效处理计算负载。 例如,TII Falcon-40B Instruct 模型至少需要一个 ml.g5.12xlarge 实例才能成功加载到内存中,但在较大的实例上性能最佳。 因此,部署和维护这些模型的投资回报 (ROI) 可能太低,无法证明业务价值,尤其是在开发周期或高峰工作负载期间。 这是由于长时间会话(可能是 24/7)使用 GPU 驱动的实例的运行成本。

今年早些时候,我们宣布 亚马逊基岩,一个无服务器 API,用于访问 Amazon 和我们的生成 AI 合作伙伴的基础模型。 尽管它目前处于私人预览版,但其无服务器 API 允许您使用 Amazon、Anthropic、Stability AI 和 AI21 的基础模型,而无需自行部署任何端点。 然而,来自 Hugging Face 等社区的开源模型一直在大量增长,但并非每一个模型都可以通过 Amazon Bedrock 提供。

在这篇文章中,我们针对这些情况,通过部署大型基础模型来解决高成本风险的问题 亚马逊SageMaker 异步端点亚马逊SageMaker JumpStart。 这有助于降低架构成本,允许端点仅在请求在队列中且生存时间较短时运行,同时在没有请求等待服务时缩减至零。 这对于很多用例来说听起来都很棒; 但是,缩小到零的端点将在能够提供推理之前引入冷启动时间。

解决方案概述

下图说明了我们的解决方案体系结构。

使用 Amazon SageMaker 异步终端节点优化 Amazon SageMaker JumpStart 基础模型的部署成本 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。

我们部署的架构非常简单:

  • 用户界面是一个笔记本,可以替换为基于 Streamlit 或类似技术构建的 Web UI。 在我们的例子中,笔记本是 亚马逊SageMaker Studio 笔记本,在具有 PyTorch 5 Python 2.0 CPU 内核的 ml.m3.10.large 实例上运行。
  • 笔记本通过三种方式查询终端节点:SageMaker Python SDK、AWS SDK for Python (Boto3) 和 LangChain。
  • 端点在 SageMaker 上异步运行,在端点上,我们部署 Falcon-40B Instruct 模型。 它是目前最先进的指令模型,可在 SageMaker JumpStart 中使用。 单个 API 调用允许我们在端点上部署模型。

什么是 SageMaker 异步推理

SageMaker 异步推理是 SageMaker 中的四个部署选项之一,其他选项还有实时端点、批量推理和无服务器推理。 要了解有关不同部署选项的更多信息,请参阅 部署推理模型.

SageMaker 异步推理对传入请求进行排队并异步处理它们,因此此选项非常适合负载大小高达 1 GB、处理时间长和近实时延迟要求的请求。 然而,在处理大型基础模型时,尤其是在概念验证 (POC) 或开发过程中,它提供的主要优势是能够配置异步推理,以便在没有请求时将实例计数缩小到零。程,从而节省成本。 有关 SageMaker 异步推理的更多信息,请参阅 异步推理. 下图说明了此体系结构。

使用 Amazon SageMaker 异步终端节点优化 Amazon SageMaker JumpStart 基础模型的部署成本 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。

要部署异步推理端点,您需要创建一个 AsyncInferenceConfig 目的。 如果你创建 AsyncInferenceConfig 不指定其参数,默认 S3OutputPaths3://sagemaker-{REGION}-{ACCOUNTID}/async-endpoint-outputs/{UNIQUE-JOB-NAME}S3FailurePaths3://sagemaker-{REGION}-{ACCOUNTID}/async-endpoint-failures/{UNIQUE-JOB-NAME}.

什么是 SageMaker JumpStart

我们的模型来自 SageMaker JumpStart,这是 SageMaker 的一项功能,可通过提供预先训练的模型、解决方案模板和示例笔记本来加速机器学习 (ML) 之旅。 它提供针对不同问题类型的各种预训练模型的访问权限,让您能够以坚实的基础开始 ML 任务。 SageMaker JumpStart 还提供常见用例的解决方案模板和学习示例笔记本。 借助 SageMaker JumpStart,您可以通过一键式解决方案启动和实用 ML 体验的综合资源来减少启动 ML 项目所需的时间和精力。

以下屏幕截图显示了 SageMaker JumpStart UI 上可用的部分模型的示例。

使用 Amazon SageMaker 异步终端节点优化 Amazon SageMaker JumpStart 基础模型的部署成本 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。

部署模型

我们的第一步是将模型部署到 SageMaker。 为此,我们可以使用 SageMaker JumpStart 的 UI 或 SageMaker Python SDK,它提供了一个 API,可用于将模型部署到异步端点:

%%time
from sagemaker.jumpstart.model import JumpStartModel, AsyncInferenceConfig
from sagemaker.serializers import JSONSerializer
from sagemaker.deserializers import JSONDeserializer model_id, model_version = "huggingface-llm-falcon-40b-instruct-bf16", "*"
my_model = JumpStartModel(model_id=model_id)
predictor = my_model.deploy( initial_instance_count=0, instance_type="ml.g5.12xlarge", async_inference_config=AsyncInferenceConfig()
)

此呼叫大约需要 10 分钟才能完成。 在此期间,端点启动,容器与模型工件一起下载到端点,从 SageMaker JumpStart 加载模型配置,然后通过 DNS 端点公开异步端点。 为了确保我们的端点可以缩小到零,我们需要使用 Application Auto Scaling 在异步端点上配置自动缩放。 您需要首先向 Application Auto Scaling 注册端点变体,定义扩展策略,然后应用扩展策略。 在此配置中,我们使用自定义指标 CustomizedMetricSpecification,被称为 ApproximateBacklogSizePerInstance,如下面的代码所示。 如需详细列表 亚马逊CloudWatch 异步推理端点可用的指标,请参阅 使用 CloudWatch 进行监控.

import boto3 client = boto3.client("application-autoscaling")
resource_id = "endpoint/" + my_model.endpoint_name + "/variant/" + "AllTraffic" # Configure Autoscaling on asynchronous endpoint down to zero instances
response = client.register_scalable_target( ServiceNamespace="sagemaker", ResourceId=resource_id, ScalableDimension="sagemaker:variant:DesiredInstanceCount", MinCapacity=0, # Miminum number of instances we want to scale down to - scale down to 0 to stop incurring in costs MaxCapacity=1, # Maximum number of instances we want to scale up to - scale up to 1 max is good enough for dev
) response = client.put_scaling_policy( PolicyName="Invocations-ScalingPolicy", ServiceNamespace="sagemaker", # The namespace of the AWS service that provides the resource. ResourceId=resource_id, # Endpoint name ScalableDimension="sagemaker:variant:DesiredInstanceCount", # SageMaker supports only Instance Count PolicyType="TargetTrackingScaling", # 'StepScaling'|'TargetTrackingScaling' TargetTrackingScalingPolicyConfiguration={ "TargetValue": 5.0, # The target value for the metric. - here the metric is - SageMakerVariantInvocationsPerInstance "CustomizedMetricSpecification": { "MetricName": "ApproximateBacklogSizePerInstance", "Namespace": "AWS/SageMaker", "Dimensions": [{"Name": "EndpointName", "Value": my_model.endpoint_name}], "Statistic": "Average", }, "ScaleInCooldown": 600, # The amount of time, in seconds, after a scale in activity completes before another scale in activity can start. "ScaleOutCooldown": 300, # ScaleOutCooldown - The amount of time, in seconds, after a scale out activity completes before another scale out activity can start. # 'DisableScaleIn': True|False - indicates whether scale in by the target tracking policy is disabled. # If the value is true, scale in is disabled and the target tracking policy won't remove capacity from the scalable resource. },
)

您可以通过导航到 SageMaker 控制台并选择来验证此策略是否已成功设置 端点推理 在导航窗格中,查找我们刚刚部署的端点。

使用 Amazon SageMaker 异步终端节点优化 Amazon SageMaker JumpStart 基础模型的部署成本 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。

调用异步端点

要调用端点,您需要将请求负载放入 亚马逊简单存储服务 (Amazon S3) 并提供指向此有效负载的指针作为 InvokeEndpointAsync 要求。 调用后,SageMaker 将请求排队进行处理,并返回标识符和输出位置作为响应。 处理后,SageMaker 将结果放置在 Amazon S3 位置。 您可以选择接收成功或错误通知 亚马逊简单通知服务 (亚马逊 SNS)。

SageMaker Python 开发工具包

部署完成后,会返回一个 AsyncPredictor 目的。 要进行异步推理,您需要将数据上传到Amazon S3并使用 predict_async() 使用 S3 URI 作为输入的方法。 它将返回一个 AsyncInferenceResponse 对象,您可以使用以下命令检查结果 get_response() 方法。

或者,如果您想定期检查结果并在生成时返回它,请使用 predict() 方法。 我们在以下代码中使用第二种方法:

import time # Invoking the asynchronous endpoint with the SageMaker Python SDK
def query_endpoint(payload): """Query endpoint and print the response""" response = predictor.predict_async( data=payload, input_path="s3://{}/{}".format(bucket, prefix), ) while True: try: response = response.get_result() break except: print("Inference is not ready ...") time.sleep(5) print(f"33[1m Input:33[0m {payload['inputs']}") print(f"33[1m Output:33[0m {response[0]['generated_text']}") query_endpoint(payload)

博托3

现在让我们探索一下 invoke_endpoint_async Boto3 的方法 sagemaker-runtime 客户。 它使开发人员能够异步调用 SageMaker 端点,提供用于稍后跟踪进度和检索响应的令牌。 Boto3 没有提供像 SageMaker Python SDK 那样等待异步推理完成的方法 get_result() 手术。 因此,我们利用 Boto3 将推理输出存储在 Amazon S3 中的事实 response["OutputLocation"]。 我们可以使用以下函数等待推理文件写入 Amazon S3:

import json
import time
import boto3
from botocore.exceptions import ClientError s3_client = boto3.client("s3") # Wait until the prediction is generated
def wait_inference_file(bucket, prefix): while True: try: response = s3_client.get_object(Bucket=bucket, Key=prefix) break except ClientError as ex: if ex.response['Error']['Code'] == 'NoSuchKey': print("Waiting for file to be generated...") time.sleep(5) next else: raise except Exception as e: print(e.__dict__) raise return response

通过这个函数,我们现在可以查询端点:

# Invoking the asynchronous endpoint with the Boto3 SDK
import boto3 sagemaker_client = boto3.client("sagemaker-runtime") # Query the endpoint function
def query_endpoint_boto3(payload): """Query endpoint and print the response""" response = sagemaker_client.invoke_endpoint_async( EndpointName=my_model.endpoint_name, InputLocation="s3://{}/{}".format(bucket, prefix), ContentType="application/json", Accept="application/json" ) output_url = response["OutputLocation"] output_prefix = "/".join(output_url.split("/")[3:]) # Read the bytes of the file from S3 in output_url with Boto3 output = wait_inference_file(bucket, output_prefix) output = json.loads(output['Body'].read())[0]['generated_text'] # Emit output print(f"33[1m Input:33[0m {payload['inputs']}") print(f"33[1m Output:33[0m {output}") query_endpoint_boto3(payload)

浪链

LangChain 是 Harrison Chase 于 2022 年 XNUMX 月推出的开源框架。 它通过提供与各种系统和数据源的集成,简化了使用大型语言模型 (LLM) 的应用程序的开发。 LangChain 允许进行文档分析、摘要、聊天机器人创建、代码分析等。 它受到了数百名开发人员的贡献以及风险投资公司的大量资金的欢迎。 LangChain 支持法学硕士与外部资源的连接,从而可以创建动态的、数据响应的应用程序。 它提供库、API 和文档来简化开发过程。

LangChain 提供了在其框架中使用 SageMaker 端点的库和示例,从而可以更轻松地使用 SageMaker 上托管的 ML 模型作为链的“大脑”。 要了解有关 LangChain 如何与 SageMaker 集成的更多信息,请参阅 SageMaker 端点 在 LangChain 文档中。

LangChain 当前实现的限制之一是它本身不支持异步端点。 要使用 LangChain 的异步端点,我们必须定义一个新类, SagemakerAsyncEndpoint,这扩展了 SagemakerEndpoint LangChain 中已经提供了该类。 此外,我们还提供以下信息:

  • 异步推理将存储输入(和输出)的 S3 存储桶和前缀
  • 超时前等待的最大秒数
  • An updated _call() 查询端点的函数 invoke_endpoint_async() 而不是 invoke_endpoint()
  • 一种在冷启动时唤醒异步端点的方法(缩小到零)

来查看新创建的 SagemakerAsyncEndpoint,你可以检查出 sagemaker_async_endpoint.py 文件 在GitHub上可用.

from typing import Dict
from langchain import PromptTemplate
from langchain.llms.sagemaker_endpoint import LLMContentHandler
from langchain.chains import LLMChain
from sagemaker_async_endpoint import SagemakerAsyncEndpoint class ContentHandler(LLMContentHandler): content_type:str = "application/json" accepts:str = "application/json" len_prompt:int = 0 def transform_input(self, prompt: str, model_kwargs: Dict) -> bytes: self.len_prompt = len(prompt) input_str = json.dumps({"inputs": prompt, "parameters": {"max_new_tokens": 100, "do_sample": False, "repetition_penalty": 1.1}}) return input_str.encode('utf-8') def transform_output(self, output: bytes) -> str: response_json = output.read() res = json.loads(response_json) ans = res[0]['generated_text'] return ans chain = LLMChain( llm=SagemakerAsyncEndpoint( input_bucket=bucket, input_prefix=prefix, endpoint_name=my_model.endpoint_name, region_name=sagemaker.Session().boto_region_name, content_handler=ContentHandler(), ), prompt=PromptTemplate( input_variables=["query"], template="{query}", ),
) print(chain.run(payload['inputs']))

清理

当您完成从端点生成推理的测试后,请记住删除端点以避免产生额外费用:

predictor.delete_endpoint()

结论

在部署 TII Falcon 等大型基础模型时,优化成本至关重要。 这些模型需要强大的硬件和大量的内存容量,从而导致基础设施成本高昂。 SageMaker 异步推理是一种异步处理请求的部署选项,可在没有待处理请求时将实例计数缩减至零,从而减少开支。 在本文中,我们演示了如何将大型 SageMaker JumpStart 基础模型部署到 SageMaker 异步端点。 我们提供了使用 SageMaker Python SDK、Boto3 和 LangChain 的代码示例,以说明调用异步端点和检索结果的不同方法。 这些技术使开发人员和研究人员能够优化成本,同时使用高级语言理解系统的基础模型的功能。

要了解有关异步推理和 SageMaker JumpStart 的更多信息,请查看以下帖子:


关于作者

大卫德的图片戴维德·加利特利 是 EMEA 地区的 AI/ML 专家解决方案架构师。 他常驻布鲁塞尔,与比荷卢三国的客户密切合作。 他从小就是一名开发人员,7 岁开始编写代码。他从大学开始学习 AI/ML,从那时起就爱上了它。

时间戳记:

更多来自 AWS机器学习