LoginSignup
32
20

Hugging FaceのZeroGPUでAIのデモを作る方法: 初級編

Last updated at Posted at 2024-06-03

はじめに

この記事ではHugging Faceという🤗なサイトでAIのデモを作ってみることを説明します。
ただし、この記事に書いてある方法でデモを作ったとして、そのデモにより起きることに責任は持てません。あらかじめご了承ください。
image.png

Hugging FaceのZeroGPUとは

ZeroGPU とは、デモの利用者が使う瞬間だけ高性能なGPUが借りられるというサービスです。現在はA100 40GBが一瞬借りられます。これを実現できているのは世界でHugging Faceだけでしょう。お値段は月額9ドル(約1500円)です。もし、ZeroGPUがなかったら、私は計算上40万円以上月に払っていることになります。それぐらいコスパの良い実験的サービスです。ぜひ使いましょう。
image.png
(ZeroGPUのページより引用)

ZeroGPUの事前準備

まず、適当なクレジットカードを用意してください。次に、Hugging Faceに登録して、Proプランに加入します

ZeroGPUの使い方

デモを公開する場であるSpaceを作る場所に移動しましょう。Gradio→text-to-image→ZeroGPU Nvidia A100を押します。
image.png
すると、準備ができ、見事にエラーが出ます。
image.png
大丈夫です。これが規定の動きです。次にエラーを取り除くためにコードを修正します。Files→app.py→editで移動します。spaceライブラリをimportするために、importとたくさん書いてある最後にimport spacesと入れます。

from diffusers import DiffusionPipeline
import torch

こんな感じなのをこうします。

from diffusers import DiffusionPipeline
import torch
import spaces

次に、GPUを動かす関数を指定します。関数にデコレータ@spaces.GPUをつけます。

def infer(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):

こんな感じなのをこうします。

@spaces.GPU
def infer(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):

これで設定自体はいいのですが、余計な処理がいっぱいあるので、このままでは動きません。したがって、最終的には下のコードをそのままコピペしてください。

#Lisence: Apache 2.0
import gradio as gr
import numpy as np
import random
from diffusers import DiffusionPipeline
import torch
import spaces

pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
pipe = pipe.to("cuda")

MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 1024

@spaces.GPU
def infer(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):

    if randomize_seed:
        seed = random.randint(0, MAX_SEED)
        
    generator = torch.Generator().manual_seed(seed)
    
    image = pipe(
        prompt = prompt, 
        negative_prompt = negative_prompt,
        guidance_scale = guidance_scale, 
        num_inference_steps = num_inference_steps, 
        width = width, 
        height = height,
        generator = generator
    ).images[0] 
    
    return image

css="""
#col-container {
    margin: 0 auto;
    max-width: 520px;
}
"""

with gr.Blocks(css=css) as demo:
    
    with gr.Column(elem_id="col-container"):
        gr.Markdown(f"""
        # Text-to-Image Gradio Template
        """)
        
        with gr.Row():
            
            prompt = gr.Text(
                label="Prompt",
                show_label=False,
                max_lines=1,
                placeholder="Enter your prompt",
                container=False,
            )
            
            run_button = gr.Button("Run", scale=0)
        
        result = gr.Image(label="Result", show_label=False)

        with gr.Accordion("Advanced Settings", open=False):
            
            negative_prompt = gr.Text(
                label="Negative prompt",
                max_lines=1,
                placeholder="Enter a negative prompt",
                visible=False,
            )
            
            seed = gr.Slider(
                label="Seed",
                minimum=0,
                maximum=MAX_SEED,
                step=1,
                value=0,
            )
            
            randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
            
            with gr.Row():
                
                width = gr.Slider(
                    label="Width",
                    minimum=256,
                    maximum=MAX_IMAGE_SIZE,
                    step=32,
                    value=512,
                )
                
                height = gr.Slider(
                    label="Height",
                    minimum=256,
                    maximum=MAX_IMAGE_SIZE,
                    step=32,
                    value=512,
                )
            
            with gr.Row():
                
                guidance_scale = gr.Slider(
                    label="Guidance scale",
                    minimum=0.0,
                    maximum=10.0,
                    step=0.1,
                    value=0.0,
                )
                
                num_inference_steps = gr.Slider(
                    label="Number of inference steps",
                    minimum=1,
                    maximum=12,
                    step=1,
                    value=2,
                )

    run_button.click(
        fn = infer,
        inputs = [prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
        outputs = [result]
    )

demo.queue().launch()

下にあるCommitボタンを押せば完成です!お疲れ様でした!

ZeroGPUっぷり

Commitボタンを押すと、画面が切り替わり、勝手にデモを作ってくれるので、しばらく待ちましょう。そうすると以下の画面が出てくるはずです。

image.png

せっかくなので、テキストボックスに"girl"とでも入れて、Runボタンをクリックしてみましょう。

image.png

画像が生成できました。めでたい。

まとめ

Hugging FaceのZeroGPUはAIのデモを作るのに最適だとわかりました。いかがでしたでしょうか。ぜひみなさんもデモを作ってみてください。なお、私は責任を持ちません。

32
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
20