如何在 Cloud Run GPU 上執行 Transformers.js

1. 簡介

總覽

Cloud Run 最近新增了 GPU 支援。這項功能目前開放等候名單中的公開測試計畫參與者使用。如有意試用這項功能,請填寫這份表單,加入候補名單。Cloud Run 是 Google Cloud 上的容器平台,可讓您輕鬆在容器中執行程式碼,不必管理叢集。

我們目前提供的 GPU 是搭載 24 GB vRAM 的 Nvidia L4 GPU。每個 Cloud Run 執行個體都有一個 GPU,Cloud Run 自動調整資源配置功能仍會套用。包括向外擴充 5 個執行個體 (可增加配額),以及在沒有任何要求時將執行個體縮減至零。

Transformers.js 的功能與 Hugging Face 的轉換器 Python 程式庫相同,因此您可以使用非常相似的 API 執行相同的預先訓練模型。詳情請參閱 Transformers.js 網站

在本程式碼研究室中,您將建立使用 Transformers.js 和 GPU 的應用程式,並部署至 Cloud Run。

課程內容

  • 如何在 Cloud Run 中使用 Transformers.js 執行應用程式

2. 啟用 API 並設定環境變數

開始使用本程式碼研究室之前,您必須先啟用幾個 API。本程式碼研究室需要使用下列 API。您可以執行下列指令來啟用這些 API:

gcloud services enable run.googleapis.com \
    storage.googleapis.com \
    cloudbuild.googleapis.com \

接著,您可以設定在本程式碼研究室中使用的環境變數。

PROJECT_ID=<YOUR_PROJECT_ID>

AR_REPO_NAME=repo
REGION=us-central1

3. 建立 Transformers.js 應用程式

首先,請建立原始碼目錄,然後切換至該目錄。

mkdir transformers-js-codelab && cd $_

建立 package.json 檔案。

{
    "name": "huggingface",
    "version": "1.0.0",
    "main": "index.js",
    "type": "module",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "description": "",
    "dependencies": {
      "@huggingface/transformers": "^3.0.0-alpha.8",
      "@xenova/transformers": "^2.17.2",
      "express": "^4.17.1"
    }
  }

建立名為 index.js 的檔案

import { pipeline } from "@xenova/transformers";

import express from 'express';

// make sure the text-generation pipeline is created first
// before anyone can access the routes
const generator = await pipeline('text-generation', 'Xenova/llama2.c-stories15M', {
    device: 'cuda',
    dtype: 'fp32',
});

// now create the app and routes
const app = express();

app.get('/', async (req, res) => {
  const text = 'A long time ago in a galaxy far far away,';
  const output = await generator(text, { max_new_tokens: 50 });
  res.send(output);
});

const port = parseInt(process.env.PORT) || 8080;
app.listen(port, () => {
  console.log(`transformers-js app: listening on port ${port}`);
});

建立 Dockerfile。Dockerfile 會安裝 Transformers.js 所需的額外 NVIDIA 驅動程式

FROM node:20
WORKDIR /usr/src/app

RUN apt-get update && \
 apt-get install software-properties-common -y && \
 wget https://developer.download.nvidia.com/compute/cuda/repos/debian12/x86_64/cuda-keyring_1.1-1_all.deb && \
 dpkg -i cuda-keyring_1.1-1_all.deb && \
 add-apt-repository contrib && \
 apt-get update && \
 apt-get -y install cuda-toolkit-12-6 && \
 apt-get -y install cudnn-cuda-12

EXPOSE 8080
COPY package.json .

RUN npm install

COPY index.js .
ENTRYPOINT ["node", "index.js"]

4. 建構及部署 Cloud Run 服務

在 Artifact Registry 中建立存放區。

gcloud artifacts repositories create $AR_REPO_NAME \
  --repository-format docker \
  --location us-central1

將程式碼提交至 Cloud Build。

IMAGE=us-central1-docker.pkg.dev/$PROJECT_ID/$AR_REPO_NAME/gpu-transformers-js
gcloud builds submit --tag $IMAGE

接著,部署至 Cloud Run

gcloud beta run deploy transformers-js-codelab \
 --image=$IMAGE \
 --cpu 8 --memory 32Gi \
 --gpu=1 --no-cpu-throttling --gpu-type nvidia-l4 \
 --allow-unauthenticated \
 --region us-central1 \
 --project=$PROJECT_ID \
 --max-instances 1

5. 測試服務

您可以執行下列指令來測試服務:

SERVICE_URL=$(gcloud run services describe transformers-js-codelab --region $REGION --format 'value(status.url)')

curl $SERVICE_URL

就會看到類似下方的內容:

[{"generated_text":"A long time ago in a galaxy far far away, there was a beautiful garden. Every day, the little girl would go to the garden and look at the flowers. She loved the garden so much that she would come back every day to visit it.\nOne day, the little girl was walking through"}]

6. 恭喜!

恭喜您完成本程式碼研究室!

建議您詳閱 Cloud Run GPU 的說明文件。

涵蓋內容

  • 如何在 Cloud Run 中使用 Transformers.js 執行應用程式

7. 清除所用資源

為避免產生意外費用 (例如,如果 Cloud Run 服務在免費方案中意外呼叫的次數超過每月配額),您可以刪除 Cloud Run,或是刪除在步驟 2 中建立的專案。

如要刪除 Cloud Run 服務,請前往 Cloud Run 控制台 (https://console.cloud.google.com/run),然後刪除 transformers-js-codelab 服務。

如果選擇刪除整個專案,您可以前往 https://console.cloud.google.com/cloud-resource-manager,選取您在步驟 2 建立的專案,然後選擇「刪除」。如果您刪除專案,就必須在 Cloud SDK 中變更專案。您可以執行 gcloud projects list 來查看可用專案的清單。