Hugging Face文字生成推理服務已在AWS Inferentia2上推出
我們很高興地宣佈,Hugging Face文字生成推理(TGI)已在AWS Inferentia2和Amazon SageMaker上全面推出。
文字生成推理(TGI)是一個專門為大規模生產工作負載部署和提供大型語言模型(LLM)的解決方案。TGI利用張量並行和連續批處理,為最流行的開放LLM(包括Llama、Mistral等)實現高效能文字生成。Text Generation Inference已在Grammarly、Uber、Deutsche Telekom等公司投入生產使用。
TGI與Amazon SageMaker的整合,結合AWS Inferentia2,提供了一個強大的解決方案,是構建生產LLM應用程式的GPU的有效替代方案。這種無縫整合確保了模型的輕鬆部署和維護,使LLM在各種生產用例中更易於訪問和擴充套件。
藉助Amazon SageMaker上新的適用於AWS Inferentia2的TGI,AWS客戶可以從與HuggingChat、OpenAssistant和Hugging Face Hub上LLM的無伺服器端點相同技術中受益,這些技術支援高併發、低延遲的LLM體驗。
在AWS Inferentia2上使用Amazon SageMaker部署Zephyr 7B
本教程展示了在AWS Inferentia2上使用Amazon SageMaker部署最先進的LLM(如Zephyr 7B)是多麼容易。Zephyr是mistralai/Mistral-7B-v0.1的一個7B微調版本,它使用直接偏好最佳化(DPO)在公開可用和合成資料集的混合上進行訓練,詳細描述見技術報告。該模型根據Apache 2.0許可釋出,確保了廣泛的可訪問性和使用。
我們將向您展示如何:
- 設定開發環境
- 獲取TGI Neuronx映象
- 將Zephyr 7B部署到Amazon SageMaker
- 執行推理並與模型聊天
讓我們開始吧。
1. 設定開發環境
我們將使用sagemaker
python SDK將Zephyr部署到Amazon SageMaker。我們需要確保已配置AWS賬戶並安裝了sagemaker
python SDK。
!pip install transformers "sagemaker>=2.206.0" --upgrade --quiet
如果您要在本地環境中使用SageMaker。您需要訪問一個具有SageMaker所需許可權的IAM角色。您可以在此處瞭解更多資訊。
import sagemaker
import boto3
sess = sagemaker.Session()
# sagemaker session bucket -> used for uploading data, models and logs
# sagemaker will automatically create this bucket if it doesn't exist
sagemaker_session_bucket=None
if sagemaker_session_bucket is None and sess is not None:
# set to default bucket if a bucket name is not given
sagemaker_session_bucket = sess.default_bucket()
try:
role = sagemaker.get_execution_role()
except ValueError:
iam = boto3.client('iam')
role = iam.get_role(RoleName='sagemaker_execution_role')['Role']['Arn']
sess = sagemaker.Session(default_bucket=sagemaker_session_bucket)
print(f"sagemaker role arn: {role}")
print(f"sagemaker session region: {sess.boto_region_name}")
2. 獲取TGI Neuronx映象
新的Hugging Face TGI Neuronx DLC可用於在AWS Inferentia2上執行推理。您可以使用sagemaker
SDK的get_huggingface_llm_image_uri
方法,根據您期望的backend
、session
、region
和version
檢索相應的Hugging Face TGI Neuronx DLC URI。您可以在此處找到所有可用版本。
注意:在撰寫此部落格文章時,Hugging Face LLM DLC的最新版本尚無法透過get_huggingface_llm_image_uri
方法獲得。我們將轉而使用原始容器URI。
from sagemaker.huggingface import get_huggingface_llm_image_uri
# retrieve the llm image uri
llm_image = get_huggingface_llm_image_uri(
"huggingface-neuronx",
version="0.0.20"
)
# print ecr image uri
print(f"llm image uri: {llm_image}")
4. 將Zephyr 7B部署到Amazon SageMaker
Inferentia2上的文字生成推理(TGI)支援流行的開放LLM,包括Llama、Mistral等。您可以在此處檢視支援的模型(文字生成)的完整列表。
編譯用於Inferentia2的LLM
在撰寫本文時,AWS Inferentia2 不支援推理的動態形狀,這意味著我們需要提前指定序列長度和批次大小。為了方便客戶充分利用 Inferentia2 的強大功能,我們建立了一個神經元模型快取,其中包含最流行 LLM 的預編譯配置。快取配置透過模型架構(Mistral)、模型大小(7B)、神經元版本(2.16)、Inferentia 核心數(2)、批次大小(2)和序列長度(2048)來定義。
這意味著我們不需要自己編譯模型,而是可以使用快取中的預編譯模型。例如,mistralai/Mistral-7B-v0.1和HuggingFaceH4/zephyr-7b-beta。您可以在Hugging Face Hub上找到已編譯/快取的配置。如果您的所需配置尚未快取,您可以使用Optimum CLI自行編譯,或在快取倉庫中提交請求。
對於本文,我們使用以下命令和引數在`inf2.8xlarge`例項上重新編譯了`HuggingFaceH4/zephyr-7b-beta`,並將其推送到Hub,位於aws-neuron/zephyr-7b-seqlen-2048-bs-4-cores-2。
# compile model with optimum for batch size 4 and sequence length 2048
optimum-cli export neuron -m HuggingFaceH4/zephyr-7b-beta --batch_size 4 --sequence_length 2048 --num_cores 2 --auto_cast_type bf16 ./zephyr-7b-beta-neuron
# push model to hub [repo_id] [local_path] [path_in_repo]
huggingface-cli upload aws-neuron/zephyr-7b-seqlen-2048-bs-4 ./zephyr-7b-beta-neuron ./ --exclude "checkpoint/**"
# Move tokenizer to neuron model repository
python -c "from transformers import AutoTokenizer; AutoTokenizer.from_pretrained('HuggingFaceH4/zephyr-7b-beta').push_to_hub('aws-neuron/zephyr-7b-seqlen-2048-bs-4')"
如果您正在嘗試編譯尚未快取配置的LLM,這可能需要長達45分鐘。
部署TGI Neuronx 端點
在將模型部署到Amazon SageMaker之前,我們必須定義TGI Neuronx端點配置。我們需要確保定義以下附加引數:
HF_NUM_CORES
:用於編譯的Neuron核心數量。HF_BATCH_SIZE
:用於編譯模型的批處理大小。HF_SEQUENCE_LENGTH
:用於編譯模型的序列長度。HF_AUTO_CAST_TYPE
:用於編譯模型的自動轉換型別。
我們仍然需要定義傳統的TGI引數:
HF_MODEL_ID
:Hugging Face模型ID。HF_TOKEN
:用於訪問受限模型的Hugging Face API令牌。MAX_BATCH_SIZE
:模型可以處理的最大批處理大小,等於用於編譯的批處理大小。MAX_INPUT_LENGTH
:模型可以處理的最大輸入長度。MAX_TOTAL_TOKENS
:模型可以生成的最大總token數,等於用於編譯的序列長度。
import json
from sagemaker.huggingface import HuggingFaceModel
# sagemaker config & model config
instance_type = "ml.inf2.8xlarge"
health_check_timeout = 1800
# Define Model and Endpoint configuration parameter
config = {
"HF_MODEL_ID": "HuggingFaceH4/zephyr-7b-beta",
"HF_NUM_CORES": "2",
"HF_BATCH_SIZE": "4",
"HF_SEQUENCE_LENGTH": "2048",
"HF_AUTO_CAST_TYPE": "bf16",
"MAX_BATCH_SIZE": "4",
"MAX_INPUT_LENGTH": "1512",
"MAX_TOTAL_TOKENS": "2048",
}
# create HuggingFaceModel with the image uri
llm_model = HuggingFaceModel(
role=role,
image_uri=llm_image,
env=config
)
建立`HuggingFaceModel`後,我們可以使用`deploy`方法將其部署到Amazon SageMaker。我們將使用`ml.inf2.8xlarge`例項型別部署模型。
# Deploy model to an endpoint
llm = llm_model.deploy(
initial_instance_count=1,
instance_type=instance_type,
container_startup_health_check_timeout=health_check_timeout,
)
SageMaker將建立我們的端點並將模型部署到其中。這可能需要10-15分鐘。
5. 執行推理並與模型聊天
部署完端點後,我們可以使用`predictor`的`predict`方法在其上執行推理。我們可以提供不同的引數來影響生成,將它們新增到有效載荷的`parameters`屬性中。您可以在此處或TGI的OpenAPI規範中的swagger文件中找到支援的引數。
`HuggingFaceH4/zephyr-7b-beta`是一個對話式聊天模型,這意味著我們可以使用以下提示結構與它聊天:
<|system|>\nYou are a friendly.</s>\n<|user|>\nInstruction</s>\n<|assistant|>\n
手動準備提示容易出錯,因此我們可以使用分詞器的`apply_chat_template`方法來幫助解決這個問題。它期望一個採用眾所周知的OpenAI格式的`messages`字典,並將其轉換為模型所需的正確格式。讓我們看看Zephyr是否知道一些關於AWS的事實。
from transformers import AutoTokenizer
# load the tokenizer
tokenizer = AutoTokenizer.from_pretrained("aws-neuron/zephyr-7b-seqlen-2048-bs-4-cores-2")
# Prompt to generate
messages = [
{"role": "system", "content": "You are the AWS expert"},
{"role": "user", "content": "Can you tell me an interesting fact about AWS?"},
]
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
# Generation arguments
payload = {
"do_sample": True,
"top_p": 0.6,
"temperature": 0.9,
"top_k": 50,
"max_new_tokens": 256,
"repetition_penalty": 1.03,
"return_full_text": False,
"stop": ["</s>"]
}
chat = llm.predict({"inputs":prompt, "parameters":payload})
print(chat[0]["generated_text"][len(prompt):])
# Sure, here's an interesting fact about AWS: As of 2021, AWS has more than 200 services in its portfolio, ranging from compute power and storage to databases,
太棒了,我們已成功將Zephyr部署到Amazon SageMaker的Inferentia2上,並與它進行了聊天。
6. 清理
為了清理,我們可以刪除模型和端點。
llm.delete_model()
llm.delete_endpoint()
結論
Hugging Face文字生成推理(TGI)與AWS Inferentia2和Amazon SageMaker的整合,為部署大型語言模型(LLM)提供了一種經濟高效的替代解決方案。
我們正在積極努力支援更多模型,簡化編譯過程,並完善快取系統。