Amazon SageMaker 实现 Llama 2 模型实时流式推理
通过响应流式传输降低生成式 AI 应用感知延迟
本文作者:Pavan Kumar Rao Navule,亚马逊云科技解决方案架构师;Sudhanshu Hate,亚马逊云科技首席人工智能与机器学习专家[k]
随着生成式 AI 应用的快速普及,降低推理延迟、提升响应吞吐量成为关键需求。基础模型(FM)尤其是大型语言模型(LLM)通常参数规模庞大,推理过程易受响应长度和硬件类型影响,导致延迟不一致[k]
采用响应流式传输技术可有效缓解该问题,即在生成内容的同时立即传输部分结果,而非等待完整响应。这种模式显著改善用户体验,适用于聊天机器人、虚拟助手等交互式场景[k]
Amazon SageMaker 实时推理现已支持响应流式传输,允许持续将推理结果流式返回客户端。结合 Amazon SageMaker 全托管的机器学习服务(涵盖数据准备、模型训练与部署),开发者可高效构建高性能生成式 AI 应用[k]
本文以 Llama-2-13b-chat-hf 模型为例,展示如何在 Amazon SageMaker 上部署支持流式输出的实时推理服务,重点优化首字节时间(TTFB)并减少整体感知延迟。该方案适用于任意大型语言模型[k]
Llama 2 是由 Meta 发布的开源生成式文本模型系列,参数范围从70亿至700亿,采用仅解码器的自回归架构,广泛应用于文本生成、翻译、摘要、问答等任务[k]
在 Amazon SageMaker 上部署 Llama 2 模型,可通过深度学习容器(DLC)或 Hugging Face 文本生成推理(TGI)容器实现。本文选用 Amazon DLC 在 G5 实例上部署 13B 版本模型,G5 为高性能 GPU 实例,适用于图形与机器学习推理负载。亦可选用 p4d、p3、g4dn 等受支持实例类型[k]
部署前需准备:有效的亚马逊云科技账户及 IAM 权限;Amazon SageMaker Domain;Hugging Face 账户及读取访问令牌;访问 Llama 模型的权限(需同意 Meta 许可协议)[k]
方法:使用 Hugging Face TGI 部署
通过 Hugging Face TGI 支持的 Amazon SageMaker DLC 镜像,可便捷部署 meta-llama/Llama-2-13b-chat-hf 模型。部署流程包括:获取镜像、配置环境参数、构建模型实例并部署至指定 ML 实例[k]
关键配置参数如下:
- 实例类型:ml.g5.12xlarge
- GPU 数量:4
- HF_MODEL_ID:meta-llama/Llama-2-13b-chat-hf
- MAX_INPUT_LENGTH:2048
- MAX_TOTAL_TOKENS:4096
- MAX_BATCH_TOTAL_TOKENS:8192
- HUGGING_FACE_HUB_TOKEN:用户 Hugging Face 访问令牌
通过 Boto3 调用 invoke_endpoint_with_response_stream API 或使用 SageMaker Python SDK 的 InvokeEndpointWithResponseStream,即可实现流式响应。该 API 支持实时传输生成结果,显著降低用户感知延迟,提升交互体验[k]
调用时需设置 CustomAttributes='accept_eula=true' 以合规使用 Llama 2 模型。成功调用后将返回字节流形式的响应流,实现逐块输出生成内容[k]
使用 DJL Serving 和 LMI 部署 Llama 2 模型实现流式响应
详解基于 Amazon SageMaker 的大模型部署流程与参数优化
为实现对大型语言模型(LLM)的高效推理,本文介绍如何使用 DJL Serving 的 LMI 将 meta-llama/Llama-2-13b-chat-hf 模型部署到支持响应流式传输的 Amazon SageMaker 实时端点[k]。
首先需准备提示模板以供模型推理使用。Llama 2 的标准提示格式如下:
<s>[INST] <<SYS>>{{ system_prompt }}<</SYS>>{{ user_message }} [/INST]
该模板通过 build_llama2_prompt 方法程序化构建,并结合具体任务指令生成最终提示。例如,针对营销活动生成邮件的任务,构造如下用户请求:
user_ask_1 = f'''AnyCompany recently announced new service launch named AnyCloud Internet Service.Write a short email about the product launch with Call to action to Alice Smith, whose email is alice.smith@example.comMention the Coupon Code: EARLYB1RD to get 20% for 1st 3 months.'''instructions = get_instructions(user_ask_1)prompt = build_llama2_prompt(instructions)
推理参数与提示共同组成请求负载,启用流式传输功能:
inference_params = {"do_sample": True,"top_p": 0.6,"temperature": 0.9,"top_k": 50,"max_new_tokens": 512,"repetition_penalty": 1.03,"stop": ["</s>"],"return_full_text": False}payload = {"inputs": prompt,"parameters": inference_params,"stream": True}
将负载发送至流式接口,实现生成文本的实时输出[k]。
部署流程包括:从 Hugging Face 下载模型快照并上传至 Amazon S3 存储桶,随后基于 DJL Serving 构建模型服务镜像。核心配置文件 serving.properties 如下:
%%writefile chat_llama2_13b_hf/serving.propertiesengine = MPIoption.entryPoint=djl_python.huggingfaceoption.tensor_parallel_degree=4option.low_cpu_mem_usage=TRUEoption.rolling_batch=lmi-distoption.max_rolling_batch_size=64option.model_loading_timeout=900option.model_id={{model_id}}option.paged_attention=true
关键参数说明:
- engine:设置为 MPI,支持跨 GPU 设备的模型并行加速[k];
- entryPoint:使用
djl_python.huggingface支持 Hugging Face Accelerate[k]; - tensor_parallel_degree:设置为 4,对应 4 卡 GPU 分区,提升推理效率[k];
- rolling_batch:启用
lmi-dist实现连续批处理,提升吞吐量[k]; - model_id:需替换为 Hugging Face 模型 ID 或 S3 路径[k]。
模型工件需打包为 model.tar.gz 并上传至 S3:
s3_code_prefix = f"{s3_prefix}/code"s3_code_artifact = sess.upload_data("model.tar.gz", bucket, s3_code_prefix)
通过 Amazon SageMaker 获取 DJL Serving 的 LMI 容器镜像 URI:
from sagemaker import image_urisinference_image_uri = image_uris.retrieve(framework="djl-deepspeed", region=region, version="0.25.0")
最后创建模型并部署至 ml.g5.12xlarge 实例,用于实现实时推理服务[k]:
from sagemaker.utils import name_from_basemodel_name = name_from_base(f"Llama-2-13b-chat-lmi-streaming")create_model_response = sm_client.create_model(ModelName=model_name,ExecutionRoleArn=role,PrimaryContainer={"Image": inference_image_uri,"ModelDataUrl": s3_code_artifact,"Environment": {"MODEL_LOADING_TIMEOUT": "3600"},},)
完整源码可在相关笔记本中获取,部署成功后即可支持高并发、低延迟的流式生成服务[k]。
使用 Amazon SageMaker 部署 Llama 2 模型并实现响应流式传输
掌握流式推理技术,提升大模型用户体验
通过 Amazon SageMaker 可以为 Llama 2 Chat 模型配置端点并实现高效推理。首先,需为模型创建包含详细参数的模型配置。
endpoint_config_name = f"{model_name}-config"endpoint_name = name_from_base(model_name)endpoint_config_response = sm_client.create_endpoint_config(EndpointConfigName=endpoint_config_name,ProductionVariants=[{"VariantName": "variant1","ModelName": model_name,"InstanceType": "ml.g5.12xlarge","InitialInstanceCount": 1,"ModelDataDownloadTimeoutInSeconds": 3600,"ContainerStartupHealthCheckTimeoutInSeconds": 3600,},],)
该配置指定了 ML 实例类型为 ml.g5.12xlarge,并通过共享 ModelName 与模型建立关联。完成模型与配置定义后,即可创建 SageMaker 端点。
create_endpoint_response = sm_client.create_endpoint(EndpointName=f"{endpoint_name}", EndpointConfigName=endpoint_config_name)
部署进度可通过以下代码监控:
resp = sm_client.describe_endpoint(EndpointName=endpoint_name)status = resp["EndpointStatus"]
当端点状态变为 InService 时,即可进行实时推理与响应流式传输。使用 get_realtime_response_stream 方法可从 SageMaker 端点获取流式响应,相关代码位于 llama-2-lmi/llama-2-13b-chat/2-inference-llama-2-13b-chat-lmi-response-streaming.ipynb。LineIterator 实现位于 utils/LineIterator.py,专用于解析 djl-deepspeed v0.25.0 推理输出的字节流。
辅助函数 print_response_stream 用于处理 invoke_endpoint_with_response_stream API 返回的数据流:
from utils.LineIterator import LineIteratordef print_response_stream(response_stream):event_stream = response_stream.get('Body')for line in LineIterator(event_stream):print(line, end='')
提示和指令的准备方式在 Hugging Face TGI 与 LMI 方法中一致,使用 get_instructions 和 build_llama2_prompt 构建有效负载:
user_ask_2 = f'''AnyCompany recently announced new service launch named AnyCloud Streaming Service.Write a short email about the product launch with Call to action to Alice Smith, whose email is alice.smith@example.comMention the Coupon Code: STREAM2DREAM to get 15% for 1st 6 months.'''instructions = get_instructions(user_ask_2)prompt = build_llama2_prompt(instructions)
将推理参数与提示结合形成最终有效负载:
inference_params = {"do_sample": True,"top_p": 0.6,"temperature": 0.9,"top_k": 50,"max_new_tokens": 512,"return_full_text": False,}payload = {"inputs": prompt,"parameters": inference_params}
将有效负载发送至 get_realtime_response_stream 以调用流式端点:
resp = get_realtime_response_stream(sagemaker_runtime, endpoint_name, payload)print_response_stream(resp)
生成的文本将以流式方式输出,显著降低用户感知延迟。
资源清理
为避免产生额外费用,部署完成后应删除相关资源:
import boto3sm_client = boto3.client('sagemaker')endpoint_name="<SageMaker_Real-time_Endpoint_Name>"endpoint = sm_client.describe_endpoint(EndpointName=endpoint_name)endpoint_config_name = endpoint['EndpointConfigName']endpoint_config = sm_client.describe_endpoint_config(EndpointConfigName=endpoint_config_name)model_name = endpoint_config['ProductionVariants'][0]['ModelName']print(f"""About to delete the following sagemaker resources:Endpoint: {endpoint_name}Endpoint Config: {endpoint_config_name}Model: {model_name}""")# delete endpointsm_client.delete_endpoint(EndpointName=endpoint_name)# delete endpoint configsm_client.delete_endpoint_config(EndpointConfigName=endpoint_config_name)# delete modelsm_client.delete_model(ModelName=model_name)
若使用了 Amazon S3 存储模型和代码工件,可执行以下命令清理:
s3 = boto3.resource('s3')s3_bucket = s3.Bucket(bucket)s3_bucket.objects.filter(Prefix=s3_prefix).delete()
结语
本文介绍了通过 Amazon DLCs(LMI 和 Hugging Face TGI)部署 Llama 2 Chat 模型的两种方法,并重点阐述了响应流式传输技术的应用[k]。流式响应有效缓解了因输出长度变化或参数调整带来的延迟问题,显著改善用户体验[k]。掌握此项技术有助于提升大语言模型服务的交互流畅度与客户满意度[k]。更多 Llama 2 模型变体的部署方案可参考官方文档。
点击阅读原文查看博客,获取更详细内容[k]

