{ "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": [ "# 01 画像生成AIを Colab の GPU で動かす(SDXL と FLUX.2 klein)" ] }, { "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 を確かめる\n", "`nvidia-smi` は NVIDIA の GPU の状態を見るコマンドです。T4 なら「Tesla T4」「15360MiB」(約16GB)のように出ます。" ] }, { "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. ライブラリを用意する\n", "画像生成には Hugging Face の **Diffusers** を使います。Colab にはもともと入っていますが、新しいモデルに合わせて更新します(1〜2分)。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pip install -q -U diffusers transformers accelerate" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Stable Diffusion XL(SDXL)で1枚つくる\n", "Stability AI の公開モデルです(ライセンスは CreativeML Open RAIL++-M)。最初の1回はモデルのダウンロード(約7GB)に数分かかります。\n", "右のフォームで文(英語がおすすめ)と回数を変えられます。2026年11月12日に T4 で測ったときは、1024×1024・30回で26.2秒、VRAM の最大は9.73GB でした。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import torch\n", "from diffusers import StableDiffusionXLPipeline\n", "\n", "sdxl = StableDiffusionXLPipeline.from_pretrained(\n", " \"stabilityai/stable-diffusion-xl-base-1.0\",\n", " torch_dtype=torch.float16, variant=\"fp16\", use_safetensors=True,\n", ").to(\"cuda\")\n", "_ = sdxl(\"warm up\", num_inference_steps=1) # 最初の1回は準備に時間がかかるので、1回だけ慣らし運転\n", "print(\"読み込みました\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form" }, "outputs": [], "source": [ "prompt = \"a cute green mochi mascot reading a book in a cozy library, warm light, illustration\" # @param {type:\"string\"}\n", "steps = 30 # @param {type:\"slider\", min:10, max:50, step:5}\n", "seed = 42 # @param {type:\"integer\"}\n", "\n", "with measure(\"SDXL 1024x1024\"):\n", " image = sdxl(prompt, num_inference_steps=steps,\n", " generator=torch.Generator(\"cuda\").manual_seed(seed)).images[0]\n", "image.save(\"sdxl.png\")\n", "image" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### メモリが足りないとき(CUDA out of memory)\n", "- 上の読み込みのセルの `.to(\"cuda\")` を消し、かわりに `sdxl.enable_model_cpu_offload()` を実行すると、使っていない部品をふだんのメモリ(CPU側)に逃がします(少し遅くなります)。\n", "- 画像を小さくする(`height=768, width=768` を足す)、回数(steps)を減らすのも効きます。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "free(\"sdxl\", \"image\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. 応用:FLUX.2 [klein] 4B(Black Forest Labs)\n", "2026年1月に公開された 40億パラメータの画像モデルで、ライセンスは Apache 2.0。公式は「約13GB の VRAM で動く」としています。\n", "中身は「文を読む部品」(Qwen3 の 4B、約8GB)と「絵を描く部品」(約8GB)。T4(16GB)に両方は入らず、無料の Colab はふだんのメモリ(RAM)も約12GB しかないので、\n", "**① 文を読む部品だけを GPU に載せて、文を数字の列に変える → ② その部品を下ろして、絵を描く部品を載せる** の2段で動かします。ダウンロードは約16GB(5〜10分)。T4 で測ったときは、1024×1024・4回で9.6秒、VRAM の最大は9.80GB でした(2026年11月12日)。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form" }, "outputs": [], "source": [ "import torch, gc\n", "from transformers import AutoTokenizer, Qwen3ForCausalLM\n", "from diffusers import Flux2KleinPipeline\n", "\n", "repo = \"black-forest-labs/FLUX.2-klein-4B\"\n", "prompt = \"a cute green mochi mascot reading a book in a cozy library, warm light, illustration\" # @param {type:\"string\"}\n", "\n", "# ① 文を読む部品だけを GPU に載せて、文を数字の列(埋め込み)に変える。文を変えたらこのセルからやり直す\n", "te = Qwen3ForCausalLM.from_pretrained(repo, subfolder=\"text_encoder\", dtype=torch.bfloat16, device_map=\"cuda\")\n", "enc = Flux2KleinPipeline.from_pretrained(repo, text_encoder=te, transformer=None, vae=None, torch_dtype=torch.bfloat16)\n", "with torch.no_grad():\n", " prompt_embeds, _ = enc.encode_prompt(prompt=prompt, device=\"cuda\")\n", "del enc, te; gc.collect(); torch.cuda.empty_cache()\n", "print(\"文を数字に変えました:\", tuple(prompt_embeds.shape))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form" }, "outputs": [], "source": [ "# ② 絵を描く部品を GPU に載せて、4回の計算で1枚つくる\n", "# T4 は bfloat16 を速く計算できないので float16 にする(L4・A100 などは bfloat16)\n", "dtype = torch.bfloat16 if torch.cuda.get_device_capability(0)[0] >= 8 else torch.float16\n", "if \"flux\" not in globals():\n", " flux = Flux2KleinPipeline.from_pretrained(repo, text_encoder=None, tokenizer=None, torch_dtype=dtype).to(\"cuda\")\n", "seed = 42 # @param {type:\"integer\"}\n", "\n", "with measure(\"FLUX.2 klein 4B 1024x1024\"):\n", " image = flux(prompt_embeds=prompt_embeds.to(dtype), height=1024, width=1024, guidance_scale=1.0,\n", " num_inference_steps=4, generator=torch.Generator(\"cuda\").manual_seed(seed)).images[0]\n", "image.save(\"flux2_klein.png\")\n", "image" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "画像が真っ黒・灰色になるときは、float16 で数値があふれています。L4 などの GPU に替えるか、SDXL を使ってください。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "free(\"flux\", \"image\", \"prompt_embeds\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. 作った画像をダウンロードする\n", "左の「ファイル」(フォルダのアイコン)から右クリックでダウンロードするか、下のセルを実行します。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from google.colab import files\n", "import os\n", "for f in [\"sdxl.png\", \"flux2_klein.png\"]:\n", " if os.path.exists(f):\n", " files.download(f)" ] }, { "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()" ] } ] }