メインコンテンツへスキップ
見出し画像

modalで自前AI画像生成サーバーを立てる!

    前回の記事はこちら

    ねんがんのmodalを手に入れた!


    システム構成図を再掲します。

    画像

    前回はubuntuサーバーにJupytarLabをインストールして接続するところまでいきました。
    今回はやりたいことは、おおまかにわけて2つです。

    ・SDXLのt2iエンドポイントを作成
    ・ローカルPCのComfyUIでカスタムノードからリクエストを送り画像を取得

    実際のコードはローカルPCにて以下の組み合わせでAIにプログラミングしてもらった後にGeminiで仕上げました。

    Ubuntu 26.4 lTS

    • Visual Source Code (Continue)

    • Deepseek V4 Pro (Openrouter)

    sdxl_run.py

    import io
    import base64
    import torch
    import modal
    from fastapi import Body
    
    # Modal構成設定
    app = modal.App("sdxl-server")
    image = modal.Image.debian_slim(python_version="3.11").pip_install(
        "diffusers", "transformers", "accelerate", "fastapi[standard]"
    )
    vol = modal.Volume.from_name("note")    # ストレージは前の記事で作成したもの
    
    @app.cls(
        image=image,
        volumes={"/models": vol},
        gpu="T4",
        scaledown_window=300,
    )
    class SDXLEndpoint:
        @modal.enter()
        def setup(self):
            from diffusers import StableDiffusionXLPipeline
            
            # モデルのロード(初回は自動ダウンロード)
            self.pipe = StableDiffusionXLPipeline.from_pretrained(
                "stabilityai/stable-diffusion-xl-base-1.0",
                torch_dtype=torch.float16,
                cache_dir="/models",
            ).to("cuda")
    
        @modal.fastapi_endpoint(method="POST")
        async def generate(self, payload: dict = Body(...)):
            # 推論実行
            generator = torch.Generator("cuda").manual_seed(payload.get("seed", 42))
            image = self.pipe(
                prompt=payload.get("prompt", "a cat"),
                negative_prompt=payload.get("negative_prompt", ""),
                num_inference_steps=payload.get("steps", 25),
                width=payload.get("width", 1024),
                height=payload.get("height", 1024),
                generator=generator,
            ).images[0]
    
            # Base64エンコードして返却
            buf = io.BytesIO()
            image.save(buf, format="PNG")
            return {"image_base64": base64.b64encode(buf.getvalue()).decode()}

    ではさっそくビルドしてみましょう。
    と、その前にvenv環境でpip install torch numpyもしておきましょう。

    pip install torch numpy
    modal deploy sdxl_run.py
    Saving image...Image saved, took 4.84s
    
    Built image im-xxxxxxxxx in 79.41s
    
    ✓ Created objects.├── 🔨 Created mount /home/user/Workspace/note/sdxl_run.py├── 
    🔨 Created function SDXLEndpoint.*.└── 
    🔨 Created web endpoint for SDXLEndpoint.generate => https://xxxx.modal.run

    ビルドできた!
    まだターミナルの画面は閉じません。
    次にローカルPCのComfyUIのカスタムノードフォルダにフォルダとスクリプトを新規作成します。

    ComfyUI/custom_nodes/modal_sdxl

    __init__.py

    from .modal_sdxl_node import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
    
    # ComfyUIがカスタムノードを認識するために必要な定義
    __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
    

    modal_sdxl_node.py

    import requests
    import base64
    import io
    import torch
    import numpy as np
    from PIL import Image
    
    # Modalでデプロイした際に出力されるエンドポイントURL
    MODAL_ENDPOINT = ""
    
    class ModalSDXLNode:
        """Modal上でSDXLを実行し、結果をComfyUIに返すカスタムノード"""
        
        @classmethod
        def INPUT_TYPES(s):
            return {
                "required": {
                    "prompt": ("STRING", {"default": "a cat", "multiline": True}),
                    "negative_prompt": ("STRING", {"default": "", "multiline": True}),
                    "steps": ("INT", {"default": 25, "min": 1, "max": 100}),
                    "seed": ("INT", {"default": 42}),
                    "width": ("INT", {"default": 1024, "min": 64, "max": 2048, "step": 64}),
                    "height": ("INT", {"default": 1024, "min": 64, "max": 2048, "step": 64}),
                }
            }
    
        RETURN_TYPES = ("IMAGE",)
        FUNCTION = "generate"
        CATEGORY = "Modal"
    
        def generate(self, **kwargs):
            # 1. ModalエンドポイントへPOSTリクエスト
            response = requests.post(MODAL_ENDPOINT, json=kwargs)
            response.raise_for_status()
            
            # 2. Base64デコードしてPIL Imageへ変換
            img_b64 = response.json()["image_base64"]
            img_data = base64.b64decode(img_b64)
            img = Image.open(io.BytesIO(img_data)).convert("RGB")
            
            # 3. ComfyUIが扱えるテンソル形式 [B, H, W, C] に変換
            img_np = np.array(img).astype(np.float32) / 255.0
            img_tensor = torch.from_numpy(img_np).unsqueeze(0)
            
            return (img_tensor,)
    
    NODE_CLASS_MAPPINGS = {"ModalSDXLNode": ModalSDXLNode}
    NODE_DISPLAY_NAME_MAPPINGS = {"ModalSDXLNode": "Modal SDXL Generator"}
    

    要はここです。
    さきほどビルドした際の.runで終わるエンドポイントのURLをソースに貼り付けます。

    修正前

    # Modalでデプロイした際に出力されるエンドポイントURL
    MODAL_ENDPOINT = ""

    修正後

    # Modalでデプロイした際に出力されるエンドポイントURL
    MODAL_ENDPOINT = "https://xxxx.modal.run"

    準備ができたらローカルPCでComfyUIを起動します。
    先ほど作成したカスタムノードのインポートエラーが出ていなことを確認します。

    ComfyUIを起動したら、キャンバス上でノード名を("modal"と打って)検索します。

    画像


    出力ノードはPreview ImageでもSave Imageでもお好みでどうぞ。

    それでは実行します。

    初回にsdxlベースモデルのダウンロード(約7GB)が発生するため、数分待ちます。

    modalのダッシュボードからログを見てみる・・・

    Fetching 19 files: 0%| | 0/19 [00:00<?, ?it/s]Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
    Fetching 19 files: 16%|█▌ | 3/19 [00:00<00:00, 29.67it/s]
    Loading pipeline components...: 0%| | 0/7 [00:00<?, ?it/s]
    Loading weights: 100%|██████████| 196/196 [00:00<00:00, 2032.49it/s]
    Loading pipeline components...: 57%|█████▋ | 4/7 [00:07<00:03, 1.16s/it]
    Loading weights: 0%| | 0/517 [00:00<?, ?it/s]
    Loading weights: 0%| | 2/517 [00:00<00:26, 19.48it/s]
    Loading weights: 38%|███▊ | 197/517 [00:00<00:00, 1142.30it/s]
    Loading weights: 61%|██████ | 313/517 [00:00<00:00, 1053.73it/s]
    Loading weights: 100%|██████████| 517/517 [00:00<00:00, 1017.26it/s]
    Loading pipeline components...: 100%|██████████| 7/7 [00:08<00:00, 1.14s/it]
    0%| | 0/25 [00:00<?, ?it/s]
    /usr/local/lib/python3.11/site-packages/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py:748: FutureWarning: `upcast_vae` is deprecated and will be removed in version 1.0.0. `upcast_vae` is deprecated. Please use `pipe.vae.to(torch.float32)`. For more details, please refer to: https://github.com/huggingface/diffusers/pull/12619#issue-3606633695.
    deprecate(
    POST / -> 200 OK (duration: 125.7 s, execution: 21.1 s)

    すると、どうでしょう!
    じゃじゃーん

    画像

    立派なねこ画像が召喚できました!
    やったね!!

    おしまい

    あなたへのおすすめ