summaryrefslogtreecommitdiff
path: root/train_colab.ipynb
blob: afae94d5549987fa8d75ff9975c94898b53df17d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
{
 "nbformat": 4,
 "nbformat_minor": 0,
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3"
  },
  "accelerator": "GPU"
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# Blazing Eights - Colab GPU Training\n\nClone repo → Train PPO agent (CPU collect, GPU update) → Push trained model back to GitHub\n\n**Game**: UNO variant with custom special cards (8=Wild, K=All draw, J=Skip, Swap=Swap hands)."
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Setup: Clone repo & install deps"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": "# ====== CONFIG ======\nGITHUB_USERNAME = \"YurenHao0426\"\nREPO_NAME = \"blazing8\"\n# ====================\n\n!git clone https://github.com/{GITHUB_USERNAME}/{REPO_NAME}.git\n%cd {REPO_NAME}\n!pip install -q torch numpy tqdm",
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import torch\n",
    "print(f\"PyTorch: {torch.__version__}\")\n",
    "print(f\"CUDA available: {torch.cuda.is_available()}\")\n",
    "if torch.cuda.is_available():\n",
    "    print(f\"GPU: {torch.cuda.get_device_name(0)}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Train"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": "# 2-player training with greedy warmup + CSV logging\n# Game simulation on CPU, PPO updates on GPU automatically\n!python train.py --num_players 2 --episodes 200000 --save_path blazing_ppo_2p\n\n# Show training log\nimport pandas as pd\ndf = pd.read_csv(\"blazing_ppo_2p_log.csv\")\nprint(df.to_string(index=False))",
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": "# (Optional) 3-player training\n# !python train.py --num_players 3 --episodes 300000 --save_path blazing_ppo_3p\n\n# (Optional) Skip greedy warmup\n# !python train.py --num_players 2 --episodes 200000 --greedy_warmup 0 --save_path blazing_ppo_2p_no_warmup",
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Download model locally (Option A)\n",
    "Download .pt files directly from Colab to your machine."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from google.colab import files\n",
    "import glob\n",
    "\n",
    "# Download the final model\n",
    "for f in glob.glob(\"*_final.pt\"):\n",
    "    print(f\"Downloading {f}...\")\n",
    "    files.download(f)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Push model to GitHub (Option B)\n",
    "\n",
    "Push trained .pt files to a `models/` directory in the repo.\n",
    "\n",
    "You'll need a **GitHub Personal Access Token** (PAT).\n",
    "Create one at: https://github.com/settings/tokens → Generate new token (classic) → check `repo` scope."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from getpass import getpass\n",
    "import os\n",
    "\n",
    "TOKEN = getpass(\"Enter your GitHub PAT: \")\n",
    "\n",
    "# Configure git\n",
    "!git config user.email \"colab@training.ai\"\n",
    "!git config user.name \"Colab Training\"\n",
    "\n",
    "# Create models dir, move .pt files there\n",
    "os.makedirs(\"models\", exist_ok=True)\n",
    "!mv *_final.pt models/\n",
    "!ls -lh models/\n",
    "\n",
    "# Remove .pt from gitignore temporarily for models/ dir\n",
    "with open(\".gitignore\", \"r\") as f:\n",
    "    lines = f.readlines()\n",
    "with open(\".gitignore\", \"w\") as f:\n",
    "    for line in lines:\n",
    "        f.write(line)\n",
    "    f.write(\"\\n# Allow models dir\\n!models/\\n!models/*.pt\\n\")\n",
    "\n",
    "!git add models/ .gitignore\n",
    "!git commit -m \"Add trained models from Colab GPU\"\n",
    "!git push https://{TOKEN}@github.com/{GITHUB_USERNAME}/{REPO_NAME}.git main"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Quick evaluation"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": "import sys\nsys.path.insert(0, \".\")\nfrom train import PolicyValueNet, evaluate_vs_random\n\ndevice = \"cpu\"  # eval on CPU (single-sample inference)\nmodel = PolicyValueNet().to(device)\n\nimport glob\nfinal_models = glob.glob(\"*_final.pt\") + glob.glob(\"models/*_final.pt\")\nif final_models:\n    ckpt = torch.load(final_models[0], map_location=device, weights_only=True)\n    model.load_state_dict(ckpt[\"model\"])\n    model.eval()\n    print(f\"Loaded: {final_models[0]}\")\n    print(f\"Trained for {ckpt.get('episode', '?')} episodes\")\n    print()\n\n    for n in [2, 3, 4]:\n        wr = evaluate_vs_random(model, num_players=n, num_games=2000, device=device)\n        print(f\"  {n} players: win rate = {wr:.1%} (random baseline: {1/n:.1%})\")\nelse:\n    print(\"No model found. Train first!\")",
   "execution_count": null,
   "outputs": []
  }
 ]
}