{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "gpuType": "T4", "toc_visible": true }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" }, "accelerator": "GPU" }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 02 動画生成AIを Colab の GPU で動かす(Wan2.1 T2V 1.3B)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**このノートブックについて**\n", "- 動画「GPUがなくても画像・動画生成AIとLLMを動かせる? Google Colab 入門」(ずんだもんのAI教室)と、記事 [https://media.proplyd-ai.com/articles/colab-gpu/](https://media.proplyd-ai.com/articles/colab-gpu/) の配布用です。\n", "- 上から順に ▶(セルを実行)を押すだけで動きます。Hugging Face のアカウントやトークンは要りません。\n", "- **最初に** メニューの「ランタイム」→「ランタイムのタイプを変更」→ **T4 GPU** を選んで保存してください。\n", "- 無料の Colab では GPU がいつも使えるとは限りません(Google は「保証しない・使える量は変わる」としています)。混んでいるときは時間をおいてください。\n", "- 有料プランでコンピューティング単位が残っている人は、GPU をつないでいるあいだ単位が減ります。終わったら最後のセルで切断してください。\n", "- 使ってよいこと・いけないことは [Colab のよくある質問](https://research.google.com/colaboratory/faq.html) に従ってください(ディープフェイクの作成などは禁止)。モデルのライセンスも各ページで確かめてください。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. GPU を確かめる" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# GPU がつながっているかを確かめる(GPU の名前・VRAM の量・使っている量が出ます)\n", "!nvidia-smi" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import torch\n", "if not torch.cuda.is_available():\n", " raise SystemExit(\"GPU がつながっていません。「ランタイム」→「ランタイムのタイプを変更」で T4 GPU を選んでください。\")\n", "prop = torch.cuda.get_device_properties(0)\n", "GPU_NAME = prop.name\n", "VRAM_GB = prop.total_memory / 1024**3\n", "print(f\"GPU: {GPU_NAME} / VRAM: {VRAM_GB:.1f} GB / PyTorch {torch.__version__}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 時間と VRAM を測る小さな道具\n", "import time, gc, contextlib, torch\n", "\n", "RESULTS = []\n", "\n", "@contextlib.contextmanager\n", "def measure(label):\n", " gc.collect(); torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()\n", " t0 = time.perf_counter()\n", " yield\n", " torch.cuda.synchronize()\n", " sec = time.perf_counter() - t0\n", " peak = torch.cuda.max_memory_allocated() / 1024**3\n", " RESULTS.append({\"label\": label, \"sec\": round(sec, 1), \"peak_gb\": round(peak, 2)})\n", " print(f\"[{label}] {sec:.1f} 秒 / VRAM の最大 {peak:.2f} GB({torch.cuda.get_device_name(0)})\")\n", "\n", "def free(*names):\n", " \"\"\"変数を消して GPU のメモリを空ける\"\"\"\n", " for n in names:\n", " globals().pop(n, None)\n", " gc.collect(); torch.cuda.empty_cache()\n", " print(f\"空きました。いま使っている VRAM: {torch.cuda.memory_allocated()/1024**3:.2f} GB\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. ライブラリを用意する" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pip install -q -U diffusers transformers accelerate ftfy imageio imageio-ffmpeg" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. 文を数字に変える(文を読む部品だけを GPU に)\n", "Wan2.1 T2V 1.3B は、Alibaba の Wan チームが公開した「文から動画を作る」モデルの小さい版です(13億パラメータ、Apache 2.0)。\n", "公式は「必要な VRAM は 8.19GB、RTX 4090 で 480p・5秒の動画が約4分」としています(公式のコードで、文を読む部品などを CPU に逃がしたとき)。\n", "ただし文を読む部品(UMT5-XXL)は16bit でも約11GB あり、無料の Colab のふだんのメモリ(約12GB)では、動画を作る部品と一緒に置くと足りません。\n", "そこで **① 文を読む部品だけを GPU に載せて文を数字の列に変える → ② 下ろしてから動画を作る部品を載せる** の2段にします。ダウンロードは約30GB(10分前後)。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form" }, "outputs": [], "source": [ "import torch, gc\n", "from transformers import UMT5EncoderModel\n", "from diffusers import AutoencoderKLWan, WanPipeline\n", "\n", "model_id = \"Wan-AI/Wan2.1-T2V-1.3B-Diffusers\"\n", "prompt = \"A green mochi mascot walks happily on a sunny meadow, flowers swaying in the wind, cinematic\" # @param {type:\"string\"}\n", "negative_prompt = \"Bright tones, overexposed, static, blurred details, subtitles, worst quality, low quality, JPEG compression residue, ugly, deformed, still picture, messy background\"\n", "\n", "# ① 文を読む部品だけを GPU に載せる。文を変えたらこのセルからやり直す\n", "te = UMT5EncoderModel.from_pretrained(model_id, subfolder=\"text_encoder\", dtype=torch.bfloat16, device_map=\"cuda\")\n", "enc = WanPipeline.from_pretrained(model_id, text_encoder=te, transformer=None, vae=None, torch_dtype=torch.bfloat16)\n", "with torch.no_grad():\n", " prompt_embeds, negative_embeds = enc.encode_prompt(prompt, negative_prompt, device=\"cuda\")\n", "del enc, te; gc.collect(); torch.cuda.empty_cache()\n", "print(\"文を数字に変えました:\", tuple(prompt_embeds.shape))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. 動画をつくる\n", "T4 では時間がかかるので、最初は **33コマ(16コマ/秒で約2秒)** にしています。2026年11月12日に T4 で測ったときは、生成に414.7秒(約7分)、VRAM の最大は10.57GB でした。81コマ(約5秒)にすると、時間はおよそ2.5倍以上になります。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form" }, "outputs": [], "source": [ "# ② 動画を作る部品を GPU に載せる(T4 は float16、L4・A100 などは bfloat16)\n", "dtype = torch.bfloat16 if torch.cuda.get_device_capability(0)[0] >= 8 else torch.float16\n", "if \"wan\" not in globals():\n", " vae = AutoencoderKLWan.from_pretrained(model_id, subfolder=\"vae\", torch_dtype=torch.float32)\n", " wan = WanPipeline.from_pretrained(model_id, vae=vae, text_encoder=None, tokenizer=None, torch_dtype=dtype).to(\"cuda\")\n", "\n", "num_frames = 33 # @param [17, 33, 49, 81] {type:\"raw\"}\n", "steps = 30 # @param {type:\"slider\", min:10, max:50, step:5}\n", "seed = 42 # @param {type:\"integer\"}\n", "\n", "with measure(f\"Wan2.1 1.3B 480x832 {num_frames}コマ {steps}回\"):\n", " frames = wan(prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds,\n", " height=480, width=832, num_frames=num_frames, num_inference_steps=steps,\n", " guidance_scale=5.0, generator=torch.Generator(\"cuda\").manual_seed(seed)).frames[0]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from diffusers.utils import export_to_video\n", "from IPython.display import Video\n", "export_to_video(frames, \"wan.mp4\", fps=16)\n", "Video(\"wan.mp4\", embed=True, width=640)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### うまくいかないとき\n", "- **CUDA out of memory**:コマ数を減らす(17)か、高さと幅を小さくする(例:320×576)。\n", "- **時間がかかりすぎる**:回数(steps)を20に。L4・A100 などの GPU(有料プラン)だと大きく速くなります。\n", "- 画面が真っ黒・ノイズだけ:float16 で数値があふれています。L4 などの GPU に替えてください。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from google.colab import files\n", "files.download(\"wan.mp4\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "free(\"wan\", \"vae\", \"frames\", \"prompt_embeds\", \"negative_embeds\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 終わったら:ランタイムを切断する\n", "GPU をつないだままにすると、有料プランではコンピューティング単位が減り続け、無料でも使える量を使います。\n", "下のセルを実行するか、メニューの「ランタイム」→「ランタイムを接続解除して削除」を選んでください。\n", "**切断すると、ダウンロードしたモデルや作った画像・動画(左の「ファイル」の中身)は消えます。** 残したいものは先にダウンロードしてください。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 測った結果のまとめ\n", "for r in RESULTS:\n", " print(f\"{r['label']}: {r['sec']} 秒 / VRAM の最大 {r['peak_gb']} GB\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ランタイムを切断する(実行するとこのページの接続が切れます)\n", "from google.colab import runtime\n", "runtime.unassign()" ] } ] }