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

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

    modalとはサーバレス環境の従量課金制プラットフォームです。
    私はまだ一部の使い方しかしていませんが、構成図は以下のとおりです。

    画像
    by Gemini

    ローカルの自作PCでCustom nodedを読ませたComfyUIを起動して生成ボタンを押します。
    するとmodalのエンドポイントにアクセスして関数が立ち上がり、推論が始まり画像が返ってきます。

    modalは黒いコマンド画面のCLIがメインなので、一見するととっつきづらいかもしれません。
    でも安心してください。
    ドキュメントやサンプルが揃っているので、チャットAIに読ませれば半日程度でSDXLモデルでの画像生成ぐらいはできるようになります。
    それではステップバイステップで始めていきます。

    ローカル環境
    OS :Ubuntu 26.04 LTS
    IDE :VSS + Continue
    言語:Python 3.11

    まずmodalのアカウントを作成したら、pip install modalせよとあるのですが、Ubuntu 24以降いきなりはpipは打てません。
    打ってもいいですが、OS保護の目的で弾かれます。
    ですので、まずはvenvで仮想領域を作成するところから始まります。

    python3.11 -m venv venv

    python 3.11の理由は安定かつ高速を得るためです。
    高速化を捨てて安定さに全振りするなら3.10、怖いもの見たさでエラーを見る覚悟があるなら(おすすめしませんが)3.12以降でどうぞ。

    次に仮想領域に入り有効化した後に、プロンプトとの先頭に(venv)とついたらmodalをインストールします。

    $ source venv/bin/activate
    (venv) $ pip install modal

    modalインストール後にセットアップを開始します。

    $ modal setup
    
    -snip-
    
    Was not able to launch web browserPlease go to this URL manually and complete the flow:
    
    https://modal.com/token-flow/tf-xxxxxxxxxxxxxxxxxxxxx

    上のURLをCtrlキーを押してクリックすると、ブラウザに飛びますので認証します。
    下記のメッセージが出たら認証成功です。

    Web authentication finished successfully!
    Token is connected to the xxxxxx workspace.

    それではgithubにある公式のサンプルを見てみましょう。

    ターミナルに戻り、作業領域でサンプル集をまるごと取得します。

    gh repo clone modal-labs/modal-examples

    githubの認証が走るので、面倒な人はzipで落としてもいいです。

    画像


    サンプルのファイル集はたくさんあります。

    ls -R modal-examples
    modal-examples:
    01_getting_started      06_gpu_and_ml     11_notebooks  LICENSE
    02_building_containers  07_web_endpoints  12_datasets   README.md
    03_scaling_out          08_advanced       13_sandboxes  internal
    04_secrets              09_job_queues     14_clusters   misc
    05_scheduling           10_integrations   AGENTS.md     pyproject.toml

    ファイル群を見てもうんざりして引き返さなくても大丈夫です、全部は使いません。

    この時点で永続ストレージを作っておくといいかもしれません。
    modal volumeコマンドを確認します。

    $ modal volume --help
    
    Usage: modal volume [OPTIONS] COMMAND [ARGS]...
    
    Read and edit modal.Volume volumes.
    
    Note: users of modal.NetworkFileSystem should use the modal nfs command
    instead.
    
    ╭─ Options ────────────────────────────────────────────────────────────────────╮
    │ --help  -h        Show this message and exit.                                │
    ╰──────────────────────────────────────────────────────────────────────────────╯
    ╭─ Management ─────────────────────────────────────────────────────────────────╮
    │ create     Create a named, persistent modal.Volume.                          │
    │ list       List the details of all modal.Volume volumes in an Environment.   │
    │ delete     Delete a named Volume and all of its data.                        │
    │ rename     Rename a modal.Volume.                                            │
    │ dashboard  Open the Volume's dashboard page in your web browser.             │
    ╰──────────────────────────────────────────────────────────────────────────────╯
    ╭─ File operations ────────────────────────────────────────────────────────────╮
    │ get        Download files from a modal.Volume object.                        │
    │ ls         List files and directories in a modal.Volume volume.              │
    │ put        Upload a file or directory to a modal.Volume.                     │
    │ rm         Delete a file or directory from a modal.Volume.                   │
    │ cp         Copy within a modal.Volume. Copy source file to destination file  │
    │            or multiple source files to destination directory.                │
    ╰──────────────────────────────────────────────────────────────────────────────╯

    modal volume create <ストレージ名>で作成できます。

    次は木星探索したいですよね?


    そう、JupytarLabです。

    そうなったら公式のサンプルのJupytarLabスクリプトを実行して、木星までひとっとびしたいところですが・・・
    あくまでサンプルなので色々と手直しが必要です。
    木星まで飛ぶためのロケットを製作しましょう(コメントアウトは省いています)
    以下の公式サンプルを流用します。

    jupyter_inside_modal.py

    import os
    import subprocess
    import time
    
    import modal
    
    app = modal.App(
        "example-jupyter-inside-modal",
        image=modal.Image.debian_slim(python_version="3.12").uv_pip_install(
            "jupyter", "bing-image-downloader~=1.1.2"
        ),
    )
    volume = modal.Volume.from_name(
        "modal-examples-jupyter-inside-modal-data", create_if_missing=True
    )
    
    CACHE_DIR = "/root/cache"
    JUPYTER_TOKEN = "1234"  # Change me to something non-guessable!
    
    
    @app.function(volumes={CACHE_DIR: volume})
    def seed_volume():
        from bing_image_downloader import downloader
    
        downloader.download(
            query="modal labs",
            limit=10,
            output_dir=CACHE_DIR,
            force_replace=False,
            timeout=60,
            verbose=True,
        )
        volume.commit()
    
    @app.function(max_containers=1, volumes={CACHE_DIR: volume}, timeout=1_500)
    def run_jupyter(timeout: int):
        jupyter_port = 8888
        with modal.forward(jupyter_port) as tunnel:
            jupyter_process = subprocess.Popen(
                [
                    "jupyter",
                    "notebook",
                    "--no-browser",
                    "--allow-root",
                    "--ip=0.0.0.0",
                    f"--port={jupyter_port}",
                    "--NotebookApp.allow_origin='*'",
                    "--NotebookApp.allow_remote_access=1",
                ],
                env={**os.environ, "JUPYTER_TOKEN": JUPYTER_TOKEN},
            )
    
            print(f"Jupyter available at => {tunnel.url}")
    
            try:
                end_time = time.time() + timeout
                while time.time() < end_time:
                    time.sleep(5)
                print(f"Reached end of {timeout} second timeout period. Exiting...")
            except KeyboardInterrupt:
                print("Exiting...")
            finally:
                jupyter_process.kill()
    
    
    @app.local_entrypoint()
    def main(timeout: int = 10_000):
        seed_volume.remote()
        run_jupyter.remote(timeout=timeout)

    まずは以下の箇所インポート部分をa-z順に並べ替えしたいです(個人的に)※必須ではないです

    # 修正前
    import os
    import subprocess
    import time
    
    import modal
    # 修正後
    import modal
    import os
    import subprocess
    import time

    次にAppの記述をすっきりさせたいです。

    # 修正前
    app = modal.App(
        "example-jupyter-inside-modal",
        image=modal.Image.debian_slim(python_version="3.12").uv_pip_install(
            "jupyter", "bing-image-downloader~=1.1.2"
        ),
    )
    # 修正後
    app = modal.App("jupyterlab")

    次に木星探査する、先ほど作成した永続ストレージを指定したいです(ここでは"note"とします)

    # 修正前
    volume = modal.Volume.from_name(
        "modal-examples-jupyter-inside-modal-data", create_if_missing=True
    )
    # 修正後
    volume = modal.Volume.from_name("note")

    キャッシュディレクトリやJupyterトークンは必須ではないのでコメントアウトするか消します。

    # 修正前
    CACHE_DIR = "/root/cache"
    JUPYTER_TOKEN = "1234"  # Change me to something non-guessable!
    # 修正後
    # CACHE_DIR = "/root/cache"
    # JUPYTER_TOKEN = "1234"  # Change me to something non-guessable!

    ここから大改造します。
    モデルイメージを選定します(ここではubuntu22.04)
    推論は別のエンドポイントに任せるため最小限です。

    image = (
        modal.Image.from_registry("ubuntu:22.04", add_python="3.11")
        .pip_install(
            "jupyterlab",
            "huggingface_hub"
        )  
    )

    ここはばっさりカットします。

    @app.function(volumes={CACHE_DIR: volume})
    def seed_volume():
        from bing_image_downloader import downloader
    
        downloader.download(
            query="modal labs",
            limit=10,
            output_dir=CACHE_DIR,
            force_replace=False,
            timeout=60,
            verbose=True,
        )
        volume.commit()

    @app.functionの中身を変更します。

    # 修正前
    @app.function(max_containers=1, volumes={CACHE_DIR: volume}, timeout=1_500)
    # 修正後
    @app.function(image=image, timeout=7200)

    タイムアウトの監視を簡素化します。

    # 修正前
    def run_jupyter(timeout: int):
    # 修正後
    def run_jupyter():

    逆にここはいじらない

    jupyter_port = 8888
    with modal.forward(jupyter_port) as tunnel:
        jupyter_process = subprocess.Popen(...

    ローカルPCとJupyterLabを確立するためです。

    ここは消すかコメントアウト(本番環境では考慮してください)

                "--NotebookApp.allow_origin='*'",
                "--NotebookApp.allow_remote_access=1",
            ],
            env={**os.environ, "JUPYTER_TOKEN": JUPYTER_TOKEN},

    まるごと削除(タイムアウトでプッツンと切れるかゾンビ化するかも)

            try:
                end_time = time.time() + timeout
                while time.time() < end_time:
                    time.sleep(5)
                print(f"Reached end of {timeout} second timeout period. Exiting...")
            except KeyboardInterrupt:
                print("Exiting...")
            finally:
                jupyter_process.kill()

    代わりにこれを入れる(本番環境では考慮してください)

        jupyter_process = subprocess.Popen(
            [
                -snip-
                "--LabApp.token=''",       # トークンなしでログイン
                "--LabApp.password=''"               
            ]
        )
        jupyter_process.wait() # これを入れないと関数が終了してしまいます

    最後に仕上げ

    # 修正前
    @app.local_entrypoint()
    def main(timeout: int = 10_000):
        seed_volume.remote()
        run_jupyter.remote(timeout=timeout)
    
    # 修正後
    @app.local_entrypoint()
    def main():
        run_jupyter.remote()

    以下が全文
    jupyter_lab.py

    import modal
    import os
    import subprocess
    import time
    
    app = modal.App("jupyterlab")
    volume = modal.Volume.from_name("note")
    
    image = (
        modal.Image.from_registry("ubuntu:22.04", add_python="3.11")
        .pip_install(
            "jupyterlab",
            "huggingface_hub"
        )  
    )
    
    @app.function(image=image, timeout=7200)
    def run_jupyter():
        jupyter_port = 8888
        with modal.forward(jupyter_port) as tunnel:
            jupyter_process = subprocess.Popen(
                [
                    "jupyter",
                    "lab",
                    "--no-browser",
                    "--allow-root",
                    "--ip=0.0.0.0",
                    f"--port={jupyter_port}",
                    "--LabApp.token=''",       # トークンなしでログイン
                    "--LabApp.password=''"               
                ]
            )
            print(f"Jupyter available at => {tunnel.url}")
            jupyter_process.wait() # これを入れないと関数が終了してしまいます
    
    @app.local_entrypoint()
    def main():
        run_jupyter.remote()

    それでは最小限の装備でいってみよー

    modal run jupyterlab.py
    ✓ Initialized. View run at
    https://modal.com/apps/xxxx/main/ap-xxxxxxx
    Building image im-xxxxxxxxx
    
    => Step 0: FROM base
    => Step 1: RUN python -m pip install huggingface_hub jupyterlab

    エンジンが掛かりました。

    Jupyter available at => https://ta-xxxx-8888-xxxx.w.modal.host

    つながった!

    わーい!大成功です!!

    画像

    JupytarLabのターミナルで確認コマンド

    pwd
    python --version

    よしなに

    次は第2回に移ります。

    あなたへのおすすめ