{ "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": [ "# 03 オープンなLLMを Colab の GPU で動かす(Qwen)" ] }, { "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": [ "ChatGPT のように会社のサーバーに質問を送るのではなく、**公開されたモデルの重み(ファイル)を Colab の GPU に読み込んで、そこで答えを作ります**。\n", "ただし Colab そのものは Google のクラウドなので、「自分のPCの中だけで動く」「ネットにつながない」使い方とはちがいます。\n", "\n", "## 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 transformers accelerate" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. モデルを読み込む\n", "- **Qwen/Qwen3-4B-Instruct-2507**(2025年7月、40億パラメータ、Apache 2.0):すぐ答えるタイプ。T4 でも軽く動きます(おすすめ)。\n", "- **Qwen/Qwen3.5-4B**(2026年2月、40億パラメータ、Apache 2.0):新しい世代。画像も読めるモデルで、ここでは文字だけ使います。\n", "ダウンロードは約8〜9GB です。2026年11月12日に T4 で測ったときは、Qwen3-4B-Instruct-2507 が1秒あたり約8トークン(VRAM 最大7.53GB)、Qwen3.5-4B が約13トークン(7.91GB)でした。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form" }, "outputs": [], "source": [ "import torch\n", "from transformers import AutoTokenizer, AutoModelForCausalLM\n", "\n", "model_id = \"Qwen/Qwen3-4B-Instruct-2507\" # @param [\"Qwen/Qwen3-4B-Instruct-2507\", \"Qwen/Qwen3.5-4B\"]\n", "dtype = torch.bfloat16 if torch.cuda.get_device_capability(0)[0] >= 8 else torch.float16\n", "tok = AutoTokenizer.from_pretrained(model_id)\n", "llm = AutoModelForCausalLM.from_pretrained(model_id, dtype=dtype, device_map=\"cuda\")\n", "# 最初の1回は GPU の準備に時間がかかるので、短く1回動かしておく(慣らし運転)\n", "_ = llm.generate(**tok(\"こんにちは\", return_tensors=\"pt\").to(\"cuda\"), max_new_tokens=8)\n", "print(\"読み込みました:\", model_id, dtype)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. 質問する\n", "答えは少しずつ(トークンごとに)出ます。最後に、かかった時間と1秒あたりのトークン数を出します(トークンは、AIが文を区切って扱う単位。この例の日本語では1トークンが約1.5文字)。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form" }, "outputs": [], "source": [ "from transformers import TextStreamer\n", "question = \"AIエージェントとチャットボットの違いを、中学生にも分かるように3行で説明して\" # @param {type:\"string\"}\n", "max_new_tokens = 400 # @param {type:\"integer\"}\n", "\n", "messages = [{\"role\": \"user\", \"content\": question}]\n", "kwargs = {\"enable_thinking\": False} if \"Qwen3.5\" in model_id else {}\n", "inputs = tok.apply_chat_template(messages, add_generation_prompt=True, return_tensors=\"pt\",\n", " return_dict=True, **kwargs).to(\"cuda\")\n", "streamer = TextStreamer(tok, skip_prompt=True, skip_special_tokens=True)\n", "with measure(f\"{model_id.split('/')[-1]} 回答\"):\n", " out = llm.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=True,\n", " temperature=0.7, top_p=0.8, top_k=20, streamer=streamer)\n", "n = out.shape[-1] - inputs[\"input_ids\"].shape[-1]\n", "print(f\"\\n→ {n} トークン / {RESULTS[-1]['sec']} 秒 = 1秒あたり {n / RESULTS[-1]['sec']:.1f} トークン\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 大きいモデルを試したいとき\n", "- 80億パラメータ級になると、16bit のままでは T4(16GB)に入りません。**量子化**(数字を4bit などに縮めて小さくする)を使うか、VRAM の大きい GPU(L4 24GB・A100 40/80GB)を使います。\n", "- 量子化すると、答えが少し変わることがあります。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "free(\"llm\", \"tok\", \"out\", \"inputs\")" ] }, { "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()" ] } ] }