AWS 上的生成式 AI - EC2



Amazon EC2(彈性計算雲)是一種多用途計算服務,提供虛擬機器來執行各種型別的負載。AWS EC2 是訓練、部署和執行這些模型(特別是需要高效能計算 (HPC) 資源的生成式 AI 模型)的重要組成部分。

AWS EC2 提供高計算能力、可擴充套件性、靈活性以及成本效益。這些強大的功能可用於訓練和部署生成式 AI

使用 AWS Elastic Inference 和 EC2 例項

AWS Elastic Inference 可用於生成式 AI 模型,以便在無需處理專用 GPU 伺服器和其他例項的情況下擴充套件 GPU 推理。

AWS Elastic Inference 允許我們將所需的 GPU 能力附加到 EC2、AWS SageMaker 或 EC2 例項。

實現示例

在以下示例中,我們將使用 AWS Elastic Inference 與 EC2 例項和預訓練的生成式 AI 模型(如 GPT 或 GAN)一起使用。

實現此示例的先決條件如下:

  • 一個彈性推理加速器(可附加到 EC2)。
  • 一個您要用於推理的預訓練生成式 AI 模型(例如,GAN、GPT)。
  • AWS CLI 和支援 Elastic Inference 的 EC2 例項深度學習 AMI。

現在,請按照以下步驟操作:

步驟 1:使用 EC2 設定彈性推理

當您為推理任務啟動 EC2 例項時,您需要附加一個彈性推理加速器。讓我們看看如何做到這一點:

要使用彈性推理啟動 EC2 例項,請執行以下操作:

  • 首先,轉到 EC2 控制檯並點選“啟動例項”。
  • 選擇支援 Elastic Inference 的 AMI。例如,深度學習 AMI。
  • 接下來,選擇例項型別(例如,t2.medium)。但請記住,不要選擇 GPU 例項,因為您將附加彈性推理加速器。
  • 最後,在“彈性推理加速器”下,選擇合適的加速器(例如,eia2.medium,它提供適度的 GPU 能力)。

啟動 EC2 例項後,在啟動 EC2 例項時附加彈性推理加速器,以提供推理所需的 GPU 能力。

步驟 2:安裝必要的庫

將支援 Elastic Inference 的 EC2 例項附加並執行後,安裝以下 Python 庫:

# Update and install pip
sudo apt-get update
sudo apt-get install -y python3-pip

# Install torch, torchvision, and the AWS Elastic Inference Client
pip3 install torch torchvision
pip3 install awscli --upgrade
pip3 install elastic-inference

步驟 3:載入預訓練的生成式 AI 模型(例如,GPT)

在此示例中,我們將使用來自 Hugging Face 的預訓練 GPT-2 模型(生成式預訓練 Transformer)。

import torch
from transformers import GPT2Tokenizer, GPT2LMHeadModel

# Load pre-trained GPT-2 model and tokenizer from Hugging Face
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
model = GPT2LMHeadModel.from_pretrained("gpt2")

# Move the model to the Elastic Inference accelerator (if available)
if torch.cuda.is_available():
    model.to('cuda')

# Set the model to evaluation mode for inference
model.eval()

模型現已載入並準備使用 Elastic Inference 執行推理。

步驟 4:定義一個函式以執行即時推理

我們定義一個函式來使用 GPT-2 模型生成文字。

def generate_text(prompt, max_length=50):
    # Tokenize the input prompt
    inputs = tokenizer.encode(prompt, return_tensors="pt")

    # Move input to GPU if Elastic Inference is available
    if torch.cuda.is_available():
        inputs = inputs.to('cuda')

    # Generate text using GPT-2
    with torch.no_grad():
        outputs = model.generate(inputs, max_length = max_length, num_return_sequences = 1)

    # Decode and return the generated text
    generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
    return generated_text

步驟 5:測試模型

讓我們透過執行推理來測試模型。此函式將根據提示生成文字並返回生成的文字。

prompt = "In the future, artificial intelligence will"
generated_text = generate_text(prompt)
print("Generated Text:\n", generated_text)
廣告

© . All rights reserved.