วิธีเรียกใช้ TorchServe และ Stable Diffusion ใน GPU ของ Cloud Run

1. บทนำ

ภาพรวม

Cloud Run เพิ่งเพิ่มการรองรับ GPU โดยพร้อมให้ใช้งานเป็นเวอร์ชันตัวอย่างแบบสาธารณะแบบมีลําดับรอ หากสนใจลองใช้ฟีเจอร์นี้ โปรดกรอกแบบฟอร์มนี้เพื่อเข้าร่วมคิวรอ Cloud Run เป็นแพลตฟอร์มคอนเทนเนอร์บน Google Cloud ที่ช่วยให้คุณเรียกใช้โค้ดในคอนเทนเนอร์ได้อย่างง่ายดายโดยไม่ต้องจัดการคลัสเตอร์

ปัจจุบัน GPU ที่เราให้บริการคือ GPU Nvidia L4 ที่มี vRAM 24 GB โดยจะมี GPU 1 ตัวต่ออินสแตนซ์ Cloud Run และการปรับขนาดอัตโนมัติของ Cloud Run จะยังคงมีผลอยู่ ซึ่งรวมถึงการปรับขนาดขึ้นสูงสุด 5 อินสแตนซ์ (พร้อมให้เพิ่มโควต้า) รวมถึงการปรับขนาดลงเป็น 0 อินสแตนซ์เมื่อไม่มีคำขอ

ในโค้ดแล็บนี้ คุณจะได้สร้างและติดตั้งใช้งานแอป TorchServe ที่ใช้ stable diffusion XL เพื่อสร้างรูปภาพจากพรอมต์ข้อความ ระบบจะแสดงผลรูปภาพที่สร้างขึ้นต่อผู้เรียกใช้เป็นสตริงที่เข้ารหัสฐาน 64

ตัวอย่างนี้อิงตามการเรียกใช้โมเดลการแพร่กระจายแบบเสถียรโดยใช้ Diffuser ของ Huggingface ใน Torchserve Codelab นี้แสดงวิธีแก้ไขตัวอย่างนี้ให้ทำงานร่วมกับ Cloud Run ได้

สิ่งที่จะได้เรียนรู้

  • วิธีเรียกใช้โมเดล Stable Diffusion XL ใน Cloud Run โดยใช้ GPU

2. เปิดใช้ API และตั้งค่าตัวแปรสภาพแวดล้อม

คุณต้องเปิดใช้ API หลายรายการก่อนจึงจะเริ่มใช้ Codelab นี้ได้ โค้ดแล็บนี้ต้องใช้ API ต่อไปนี้ คุณเปิดใช้ API เหล่านั้นได้โดยเรียกใช้คําสั่งต่อไปนี้

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

จากนั้นคุณสามารถตั้งค่าตัวแปรสภาพแวดล้อมที่จะใช้ในโค้ดแล็บนี้

PROJECT_ID=<YOUR_PROJECT_ID>

REPOSITORY=repo
NETWORK_NAME=default
REGION=us-central1
IMAGE=us-central1-docker.pkg.dev/$PROJECT_ID/$REPOSITORY/gpu-torchserve

3. สร้างแอป Torchserve

ก่อนอื่น ให้สร้างไดเรกทอรีสำหรับซอร์สโค้ดและ cd ไปยังไดเรกทอรีนั้น

mkdir stable-diffusion-codelab && cd $_

สร้างไฟล์ config.properties นี่คือไฟล์การกําหนดค่าสําหรับ TorchServe

inference_address=http://0.0.0.0:8080
enable_envvars_config=true
min_workers=1
max_workers=1
default_workers_per_model=1
default_response_timeout=1000
load_models=all
max_response_size=655350000
# to enable authorization, see https://github.com/pytorch/serve/blob/master/docs/token_authorization_api.md#how-to-set-and-disable-token-authorization
disable_token_authorization=true

โปรดทราบว่าในตัวอย่างนี้ ระบบจะใช้ที่อยู่การฟัง http://0.0.0.0 เพื่อทํางานใน Cloud Run พอร์ตเริ่มต้นของ Cloud Run คือพอร์ต 8080

สร้างไฟล์ requirements.txt

python-dotenv
accelerate
transformers
diffusers
numpy
google-cloud-storage
nvgpu

สร้างไฟล์ชื่อ stable_diffusion_handler.py

from abc import ABC
import base64
import datetime
import io
import logging
import os

from diffusers import StableDiffusionXLImg2ImgPipeline
from diffusers import StableDiffusionXLPipeline
from google.cloud import storage
import numpy as np
from PIL import Image
import torch
from ts.torch_handler.base_handler import BaseHandler


logger = logging.getLogger(__name__)


def image_to_base64(image: Image.Image) -> str:
  """Convert a PIL image to a base64 string."""
  buffer = io.BytesIO()
  image.save(buffer, format="JPEG")
  image_str = base64.b64encode(buffer.getvalue()).decode("utf-8")
  return image_str


class DiffusersHandler(BaseHandler, ABC):
  """Diffusers handler class for text to image generation."""

  def __init__(self):
    self.initialized = False

  def initialize(self, ctx):
    """In this initialize function, the Stable Diffusion model is loaded and

       initialized here.
    Args:
        ctx (context): It is a JSON Object containing information pertaining to
          the model artifacts parameters.
    """
    logger.info("Initialize DiffusersHandler")
    self.manifest = ctx.manifest
    properties = ctx.system_properties
    model_dir = properties.get("model_dir")
    model_name = os.environ["MODEL_NAME"]
    model_refiner = os.environ["MODEL_REFINER"]

    self.bucket = None

    logger.info(
        "GPU device count: %s",
        torch.cuda.device_count(),
    )
    logger.info(
        "select the GPU device, cuda is available: %s",
        torch.cuda.is_available(),
    )
    self.device = torch.device(
        "cuda:" + str(properties.get("gpu_id"))
        if torch.cuda.is_available() and properties.get("gpu_id") is not None
        else "cpu"
    )
    logger.info("Device used: %s", self.device)

    # open the pipeline to the inferenece model 
    # this is generating the image
    logger.info("Donwloading model %s", model_name)
    self.pipeline = StableDiffusionXLPipeline.from_pretrained(
        model_name,
        variant="fp16",
        torch_dtype=torch.float16,
        use_safetensors=True,
    ).to(self.device)
    logger.info("done donwloading model %s", model_name)

    # open the pipeline to the refiner
    # refiner is used to remove artifacts from the image
    logger.info("Donwloading refiner %s", model_refiner)
    self.refiner = StableDiffusionXLImg2ImgPipeline.from_pretrained(
        model_refiner,
        variant="fp16",
        torch_dtype=torch.float16,
        use_safetensors=True,
    ).to(self.device)
    logger.info("done donwloading refiner %s", model_refiner)

    self.n_steps = 40
    self.high_noise_frac = 0.8
    self.initialized = True
    # Commonly used basic negative prompts.
    logger.info("using negative_prompt")
    self.negative_prompt = ("worst quality, normal quality, low quality, low res, blurry")

  # this handles the user request
  def preprocess(self, requests):
    """Basic text preprocessing, of the user's prompt.

    Args:
        requests (str): The Input data in the form of text is passed on to the
          preprocess function.

    Returns:
        list : The preprocess function returns a list of prompts.
    """
    logger.info("Process request started")
    inputs = []
    for _, data in enumerate(requests):
      input_text = data.get("data")
      if input_text is None:
        input_text = data.get("body")
      if isinstance(input_text, (bytes, bytearray)):
        input_text = input_text.decode("utf-8")
      logger.info("Received text: '%s'", input_text)
      inputs.append(input_text)
    return inputs

  def inference(self, inputs):
    """Generates the image relevant to the received text.

    Args:
        input_batch (list): List of Text from the pre-process function is passed
          here

    Returns:
        list : It returns a list of the generate images for the input text
    """
    logger.info("Inference request started")
    # Handling inference for sequence_classification.
    image = self.pipeline(
        prompt=inputs,
        negative_prompt=self.negative_prompt,
        num_inference_steps=self.n_steps,
        denoising_end=self.high_noise_frac,
        output_type="latent",
    ).images
    logger.info("Done model")

    image = self.refiner(
        prompt=inputs,
        negative_prompt=self.negative_prompt,
        num_inference_steps=self.n_steps,
        denoising_start=self.high_noise_frac,
        image=image,
    ).images
    logger.info("Done refiner")

    return image

  def postprocess(self, inference_output):
    """Post Process Function converts the generated image into Torchserve readable format.

    Args:
        inference_output (list): It contains the generated image of the input
          text.

    Returns:
        (list): Returns a list of the images.
    """
    logger.info("Post process request started")
    images = []
    response_size = 0
    for image in inference_output:
      # Save image to GCS
      if self.bucket:
        image.save("temp.jpg")

        # Create a blob object
        blob = self.bucket.blob(
            datetime.datetime.now().strftime("%Y%m%d_%H%M%S") + ".jpg"
        )

        # Upload the file
        blob.upload_from_filename("temp.jpg")

      # to see the image, encode to base64
      encoded = image_to_base64(image)
      response_size += len(encoded)
      images.append(encoded)

    logger.info("Images %d, response size: %d", len(images), response_size)
    return images

สร้างไฟล์ชื่อ start.sh ไฟล์นี้ใช้เป็นจุดแรกเข้าในคอนเทนเนอร์เพื่อเริ่ม TorchServe

#!/bin/bash

echo "starting the server"
# start the server. By default torchserve runs in backaround, and start.sh will immediately terminate when done
# so use --foreground to keep torchserve running in foreground while start.sh is running in a container  
torchserve --start --ts-config config.properties --models "stable_diffusion=${MAR_FILE_NAME}.mar" --model-store ${MAR_STORE_PATH} --foreground

จากนั้นเรียกใช้คำสั่งต่อไปนี้เพื่อทำให้ไฟล์เป็นไฟล์ที่ทำงานได้

chmod 755 start.sh

สร้าง dockerfile

# pick a version of torchserve to avoid any future breaking changes
# docker pull pytorch/torchserve:0.11.1-cpp-dev-gpu
FROM pytorch/torchserve:0.11.1-cpp-dev-gpu AS base

USER root

WORKDIR /home/model-server

COPY requirements.txt ./
RUN pip install --upgrade -r ./requirements.txt

# Stage 1 build the serving container.
FROM base AS serve-gcs

ENV MODEL_NAME='stabilityai/stable-diffusion-xl-base-1.0'
ENV MODEL_REFINER='stabilityai/stable-diffusion-xl-refiner-1.0'

ENV MAR_STORE_PATH='/home/model-server/model-store'
ENV MAR_FILE_NAME='model'
RUN mkdir -p $MAR_STORE_PATH

COPY config.properties ./
COPY stable_diffusion_handler.py ./
COPY start.sh ./

# creates the mar file used by torchserve
RUN torch-model-archiver --force --model-name ${MAR_FILE_NAME} --version 1.0 --handler stable_diffusion_handler.py -r requirements.txt --export-path ${MAR_STORE_PATH}

# entrypoint
CMD ["./start.sh"]

4. ตั้งค่า Cloud NAT

Cloud NAT ช่วยให้คุณมีแบนด์วิดท์ที่สูงขึ้นในการเข้าถึงอินเทอร์เน็ตและดาวน์โหลดโมเดลจาก HuggingFace ซึ่งจะเร่งเวลาในการทำให้ใช้งานได้อย่างมาก

หากต้องการใช้ Cloud NAT ให้เรียกใช้คําสั่งต่อไปนี้เพื่อเปิดใช้อินสแตนซ์ Cloud NAT

gcloud compute routers create nat-router --network $NETWORK_NAME --region us-central1
gcloud compute routers nats create vm-nat --router=nat-router --region=us-central1 --auto-allocate-nat-external-ips --nat-all-subnet-ip-ranges

5. บิลด์และทำให้บริการ Cloud Run ใช้งานได้

ส่งโค้ดไปยัง Cloud Build

gcloud builds submit --tag $IMAGE

ถัดไป ให้ทำให้ใช้งานได้กับ Cloud Run

gcloud beta run deploy gpu-torchserve \
 --image=$IMAGE \
 --cpu=8 --memory=32Gi \
 --gpu=1 --no-cpu-throttling --gpu-type=nvidia-l4 \
 --allow-unauthenticated \
 --region us-central1 \
 --project $PROJECT_ID \
 --execution-environment=gen2 \
 --max-instances 1 \
 --network $NETWORK_NAME \
 --vpc-egress all-traffic

6. ทดสอบบริการ

คุณสามารถทดสอบบริการได้โดยเรียกใช้คําสั่งต่อไปนี้

PROMPT_TEXT="a cat sitting in a magnolia tree"

SERVICE_URL=$(gcloud run services describe gpu-torchserve --region $REGION --format 'value(status.url)')

time curl $SERVICE_URL/predictions/stable_diffusion -d "data=$PROMPT_TEXT" | base64 --decode > image.jpg

คุณจะเห็นไฟล์ image.jpg ปรากฏในไดเรกทอรีปัจจุบัน คุณสามารถเปิดรูปภาพใน Cloud Shell Editor เพื่อดูรูปแมวนั่งอยู่บนต้นไม้

7. ยินดีด้วย

ยินดีด้วยที่ทํา Codelab จนเสร็จสมบูรณ์

เราขอแนะนําให้อ่านเอกสารประกอบเกี่ยวกับ GPU ของ Cloud Run

สิ่งที่เราได้พูดถึง

  • วิธีเรียกใช้โมเดล Stable Diffusion XL ใน Cloud Run โดยใช้ GPU

8. ล้างข้อมูล

หากต้องการหลีกเลี่ยงการเรียกเก็บเงินโดยไม่ตั้งใจ (เช่น หากมีการเรียกใช้งาน Cloud Run นี้โดยไม่ตั้งใจมากกว่าการจัดสรรการเรียกใช้ Cloud Run รายเดือนในแพ็กเกจฟรี) คุณสามารถลบงาน Cloud Run หรือลบโปรเจ็กต์ที่สร้างไว้ในขั้นตอนที่ 2

หากต้องการลบงาน Cloud Run ให้ไปที่ Cloud Console ของ Cloud Run ที่ https://console.cloud.google.com/run/ แล้วลบบริการ gpu-torchserve

นอกจากนี้ คุณยังต้องลบการกำหนดค่า Cloud NAT ด้วย

หากเลือกลบทั้งโปรเจ็กต์ ให้ไปที่ https://console.cloud.google.com/cloud-resource-manager เลือกโปรเจ็กต์ที่สร้างในขั้นตอนที่ 2 แล้วเลือก "ลบ" หากลบโปรเจ็กต์ คุณจะต้องเปลี่ยนโปรเจ็กต์ใน Cloud SDK คุณดูรายการโปรเจ็กต์ทั้งหมดที่ใช้ได้โดยการเรียกใช้ gcloud projects list