1. परिचय
खास जानकारी
Cloud Run में हाल ही में जीपीयू इस्तेमाल करने की सुविधा जोड़ी गई है. यह सुविधा, Public Preview के तौर पर उपलब्ध है. इसके लिए, आपको इंतज़ार की सूची में शामिल होना होगा. अगर आपको इस सुविधा को आज़माना है, तो वेटलिस्ट में शामिल होने के लिए यह फ़ॉर्म भरें. Cloud Run, Google Cloud पर एक कंटेनर प्लैटफ़ॉर्म है. इसकी मदद से, कंटेनर में कोड को आसानी से चलाया जा सकता है. इसके लिए, आपको क्लस्टर मैनेज करने की ज़रूरत नहीं होती.
फ़िलहाल, हम 24 जीबी vRAM वाले Nvidia L4 जीपीयू उपलब्ध कराते हैं. Cloud Run के हर इंस्टेंस के लिए एक जीपीयू होता है. साथ ही, Cloud Run की ऑटो स्केलिंग की सुविधा अब भी लागू होती है. इसमें ज़्यादा से ज़्यादा पांच इंस्टेंस तक स्केल आउट करने की सुविधा शामिल है. साथ ही, अनुरोध न होने पर इंस्टेंस की संख्या को घटाकर शून्य करने की सुविधा भी शामिल है. इसके अलावा, कोटे को बढ़ाने की सुविधा भी उपलब्ध है.
इस कोडलैब में, आपको एक ऐसा TorchServe ऐप्लिकेशन बनाने और डिप्लॉय करने का तरीका बताया जाएगा जो टेक्स्ट प्रॉम्प्ट से इमेज जनरेट करने के लिए, stable diffusion XL का इस्तेमाल करता है. जनरेट की गई इमेज को, कॉल करने वाले व्यक्ति को base64 एन्कोड की गई स्ट्रिंग के तौर पर भेजा जाता है.
यह उदाहरण, Torchserve में Huggingface Diffusers का इस्तेमाल करके, स्टेबल डिफ़्यूज़न मॉडल चलाने पर आधारित है. इस कोडलैब में, इस उदाहरण में बदलाव करके इसे Cloud Run के साथ इस्तेमाल करने का तरीका बताया गया है.
आपको क्या सीखने को मिलेगा
- GPU का इस्तेमाल करके, Cloud Run पर Stable Diffusion XL मॉडल चलाने का तरीका
2. एपीआई चालू करना और एनवायरमेंट वैरिएबल सेट करना
इस कोडलैब का इस्तेमाल करने से पहले, आपको कई एपीआई चालू करने होंगे. इस कोडलैब के लिए, इन एपीआई का इस्तेमाल करना ज़रूरी है. इन एपीआई को चालू करने के लिए, यह कमांड चलाएं:
gcloud services enable run.googleapis.com \
storage.googleapis.com \
cloudbuild.googleapis.com
इसके बाद, ऐसे एनवायरमेंट वैरिएबल सेट किए जा सकते हैं जिनका इस्तेमाल इस कोडलैब में किया जाएगा.
PROJECT_ID=<YOUR_PROJECT_ID> REPOSITORY=<YOUR_REPOSITORY_ID> NETWORK_NAME=default REGION=us-central1 IMAGE=us-central1-docker.pkg.dev/$PROJECT_ID/$REPOSITORY/gpu-torchserve
REPOSITORY के लिए सेट की गई वैल्यू, Artifact Registry की उस रिपॉज़िटरी के लिए होती है जहां आपकी इमेज को सेव किया जाएगा. किसी मौजूदा खाते का इस्तेमाल किया जा सकता है या नया खाता बनाया जा सकता है:
gcloud artifacts repositories create $REPOSITORY \
--location=us-central1 \
--repository-format=docker
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
ध्यान दें कि इस उदाहरण में, Cloud Run पर काम करने के लिए लिसनिंग पते http://0.0.0.0 का इस्तेमाल किया गया है. 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("Downloading 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 downloading model %s", model_name)
# open the pipeline to the refiner
# refiner is used to remove artifacts from the image
logger.info("Downloading 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 downloading 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
अगर Cloud Run को पुष्टि करने की ज़रूरत के हिसाब से कॉन्फ़िगर किया गया है, तो पक्का करें कि आपने curl कमांड में अनुमति देने वाले हेडर जोड़े हों.
आपको मौजूदा डायरेक्ट्री में image.jpg फ़ाइल दिखेगी. पेड़ पर बैठी बिल्ली की इमेज देखने के लिए, Cloud Shell Editor में इमेज खोलें.
7. बधाई हो!
कोडलैब पूरा करने के लिए बधाई!
हमारा सुझाव है कि आप Cloud Run के जीपीयू से जुड़ा दस्तावेज़ पढ़ें.
हमने क्या-क्या बताया
- GPU का इस्तेमाल करके, Cloud Run पर Stable Diffusion XL मॉडल चलाने का तरीका
8. व्यवस्थित करें
अनजाने में लगने वाले शुल्क से बचने के लिए, Cloud Run जॉब को मिटा दें या चरण 2 में बनाया गया प्रोजेक्ट मिटा दें. उदाहरण के लिए, अगर इस Cloud Run जॉब को मुफ़्त टियर में Cloud Run जॉब को हर महीने कॉल करने की तय सीमा से ज़्यादा बार कॉल किया जाता है, तो अनजाने में शुल्क लग सकता है.
Cloud Run जॉब मिटाने के लिए, Cloud Run Cloud Console पर जाएं. इसके लिए, https://console.cloud.google.com/run/ पर जाएं और gpu-torchserve सेवा मिटाएं.
आपको Cloud NAT कॉन्फ़िगरेशन भी मिटाना होगा.
अगर आपको पूरा प्रोजेक्ट मिटाना है, तो https://console.cloud.google.com/cloud-resource-manager पर जाएं. इसके बाद, दूसरे चरण में बनाया गया प्रोजेक्ट चुनें और मिटाएं को चुनें. प्रोजेक्ट मिटाने पर, आपको Cloud SDK में प्रोजेक्ट बदलने होंगे. gcloud projects list कमांड चलाकर, सभी उपलब्ध प्रोजेक्ट की सूची देखी जा सकती है.