{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ca718b3f",
   "metadata": {},
   "source": [
    "# Advanced Google Colab: GPUs, PyTorch, and Efficient Workflows\n",
    "\n",
    "Run cells in order. Optional interactive examples are marked and left as text."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "25196f93",
   "metadata": {},
   "source": [
    "## Introduction\n",
    "\n",
    "Google Colab can support much more than short Python examples. This tutorial covers practical workflows for numerical computing and future machine learning projects, without assuming that you already know how to train a model.\n",
    "\n",
    "Complete [Google Colab for Beginners](/articles/google-colab-for-beginners/) first if you are unfamiliar with notebook execution or Google Drive.\n",
    "\n",
    "[Download the companion notebook](/notebooks/advanced-google-colab.ipynb) and upload it to Colab using File > Upload notebook.\n",
    "\n",
    "## 1. Understand the runtime\n",
    "\n",
    "Your notebook document and its computing runtime are separate. The notebook can be saved in Drive, while Python variables, installed packages, and files under `/content` belong to the current remote session. A replacement runtime can lose all of that state.\n",
    "\n",
    "Use the CPU runtime for general scripting. Select a GPU through Runtime > Change runtime type for GPU experiments. TPU runtimes require a different software workflow and are not used in this tutorial. Free hardware availability and session duration are not guaranteed.\n",
    "\n",
    "## 2. Inspect available resources\n",
    "\n",
    "Colab runs a Linux-based environment. Inspect the Python version, CPU count, and available memory before starting a large computation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c5351035",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "import os\n",
    "import shutil\n",
    "import psutil\n",
    "\n",
    "print(\"Python:\", sys.version)\n",
    "print(\"Logical CPUs:\", os.cpu_count())\n",
    "print(\"Available RAM (GiB):\", round(psutil.virtual_memory().available / 2**30, 2))\n",
    "print(\"Free disk (GiB):\", round(shutil.disk_usage(\"/content\").free / 2**30, 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3a089bc7",
   "metadata": {},
   "source": [
    "Shell commands can be executed using `!`. For example, the following command displays files in the current directory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4d26865a",
   "metadata": {},
   "outputs": [],
   "source": [
    "!ls -lah /content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "82f2aefa",
   "metadata": {},
   "source": [
    "On a GPU runtime, inspect the NVIDIA device and its memory usage."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "253f590a",
   "metadata": {},
   "outputs": [],
   "source": [
    "!nvidia-smi"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "efafd4bc",
   "metadata": {},
   "source": [
    "If the command is unavailable or reports no device, check your runtime type. GPU models and memory capacities vary between sessions.\n",
    "\n",
    "## 3. Manage dependencies\n",
    "\n",
    "Use `%pip` to install packages into the notebook's Python environment. Avoid upgrading every package indiscriminately, especially GPU-enabled libraries that depend on compatible binary versions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "feb410bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import numpy as np\n",
    "\n",
    "print(\"PyTorch:\", torch.__version__)\n",
    "print(\"NumPy:\", np.__version__)\n",
    "print(\"CUDA build:\", torch.version.cuda)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9c5aafab",
   "metadata": {},
   "source": [
    "Record the installed versions so that another reader can understand your environment. For a project with a tested requirements file, install it using `%pip install -r requirements.txt` after obtaining that file. A runtime restart may be necessary after changing packages."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d4711025",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip freeze > /content/colab-environment.txt"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32775bbc",
   "metadata": {},
   "source": [
    "This snapshot is useful for diagnostics but may include many unrelated preinstalled packages. For a portable project, maintain a smaller requirements file containing the dependencies you actually use and test it in a fresh runtime.\n",
    "\n",
    "## 4. Work with GitHub repositories and Python modules\n",
    "\n",
    "Git allows you to obtain a project without copying each file manually. The following example clones a public educational repository into temporary storage. Only clone and execute code from sources you trust."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21d4c257",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "import subprocess\n",
    "\n",
    "repo = Path(\"/content/hello-world\")\n",
    "if not repo.exists():\n",
    "    subprocess.run([\"git\", \"clone\", \"https://github.com/octocat/Hello-World.git\", str(repo)], check=True)\n",
    "print(list(repo.iterdir()))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "275fa642",
   "metadata": {},
   "source": [
    "This example repository demonstrates cloning rather than providing an ML package. For your own Python projects, keep reusable functions in `.py` files instead of placing everything in notebook cells."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f3a61ec1",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "import sys\n",
    "\n",
    "module_dir = Path(\"/content/tutorial_modules\")\n",
    "module_dir.mkdir(exist_ok=True)\n",
    "(module_dir / \"operations.py\").write_text(\"def square(value):\\n    return value ** 2\\n\")\n",
    "if str(module_dir) not in sys.path:\n",
    "    sys.path.insert(0, str(module_dir))\n",
    "from operations import square\n",
    "\n",
    "print(square(7))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3714522",
   "metadata": {},
   "source": [
    "The expected output is 49. If you edit an imported module, Python may retain the old version until you reload it or restart the runtime. For reproducibility, record the Git commit used by your project rather than relying on a moving branch.\n",
    "\n",
    "## 5. Manage persistent and temporary data\n",
    "\n",
    "Drive is useful for persistent storage, but repeated small reads from mounted Drive may be slower than reading runtime-local files. A common workflow is to copy the required data into `/content`, process it there, and copy important results back to Drive."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "de8ce581",
   "metadata": {},
   "outputs": [],
   "source": [
    "from google.colab import drive\n",
    "from pathlib import Path\n",
    "import shutil\n",
    "\n",
    "drive.mount(\"/content/drive\")\n",
    "project = Path(\"/content/drive/MyDrive/AdvancedColabTutorial\")\n",
    "project.mkdir(parents=True, exist_ok=True)\n",
    "source = project / \"example.txt\"\n",
    "source.write_text(\"Example dataset\\n\")\n",
    "local_data = Path(\"/content/tutorial_data\")\n",
    "local_data.mkdir(exist_ok=True)\n",
    "shutil.copy2(source, local_data / source.name)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "953428e4",
   "metadata": {},
   "source": [
    "This creates a small example file rather than downloading a large dataset. Ensure that sufficient local disk space exists before copying real datasets. Mount Drive only in trusted notebooks.\n",
    "\n",
    "## 6. Store credentials securely\n",
    "\n",
    "Colab's Secrets panel lets you store API keys without embedding them in notebook code. Open the key icon in the sidebar, add a secret named `EXAMPLE_API_KEY`, and grant notebook access only if needed."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2817463c",
   "metadata": {},
   "source": [
    "Optional example (copy into a new cell to run or edit):\n",
    "\n",
    "```python\n",
    "from google.colab import userdata\n",
    "\n",
    "api_key = userdata.get(\"EXAMPLE_API_KEY\")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "517958c1",
   "metadata": {},
   "source": [
    "This optional example requires you to create the secret first. Never print the value, include it in a public notebook, or commit it to GitHub. Notebook code with access to a secret can use it, so inspect unfamiliar notebooks before granting permission.\n",
    "\n",
    "## 7. Use PyTorch with a GPU\n",
    "\n",
    "A tensor is a multidimensional numerical array. PyTorch can place tensors on a CPU or compatible CUDA GPU. Select the device programmatically so the same code can run without a GPU."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "741090b9",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "\n",
    "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
    "print(\"Device:\", device)\n",
    "if device.type == \"cuda\":\n",
    "    print(\"GPU:\", torch.cuda.get_device_name(0))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "efc854b4",
   "metadata": {},
   "outputs": [],
   "source": [
    "x = torch.tensor([1.0, 2.0, 3.0], device=device)\n",
    "y = x ** 2\n",
    "print(y.cpu())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3bfc7349",
   "metadata": {},
   "source": [
    "The values should be 1, 4, and 9. The `.cpu()` method moves the result to CPU memory when necessary. Tensors participating in the same operation generally need to be on compatible devices.\n",
    "\n",
    "## 8. Benchmark CPU and GPU computation\n",
    "\n",
    "GPU acceleration is most useful for sufficiently large parallel operations. Small calculations can be slower on a GPU because of launch and transfer overhead. CUDA operations are asynchronous, so synchronize before and after timing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d9aeb5b4",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "import statistics\n",
    "import torch\n",
    "\n",
    "def benchmark_matmul(device, size=1024, repeats=5):\n",
    "    device = torch.device(device)\n",
    "    a = torch.randn(size, size, device=device)\n",
    "    b = torch.randn(size, size, device=device)\n",
    "    for _ in range(3):\n",
    "        result = a @ b\n",
    "    if device.type == \"cuda\":\n",
    "        torch.cuda.synchronize(device)\n",
    "    timings = []\n",
    "    for _ in range(repeats):\n",
    "        start = time.perf_counter()\n",
    "        result = a @ b\n",
    "        if device.type == \"cuda\":\n",
    "            torch.cuda.synchronize(device)\n",
    "        timings.append(time.perf_counter() - start)\n",
    "    return statistics.median(timings)\n",
    "\n",
    "cpu_time = benchmark_matmul(\"cpu\")\n",
    "print(f\"CPU: {cpu_time * 1000:.3f} ms\")\n",
    "if torch.cuda.is_available():\n",
    "    gpu_time = benchmark_matmul(\"cuda\")\n",
    "    print(f\"GPU: {gpu_time * 1000:.3f} ms\")\n",
    "    print(f\"Speedup: {cpu_time / gpu_time:.2f}x\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e21544eb",
   "metadata": {},
   "source": [
    "This measures matrix multiplication with tensors already on the selected device. It excludes initial allocation and CPU-to-GPU transfers. Results depend on hardware, numerical precision settings, CPU threading, and workload size. Try different matrix sizes and compare the results rather than assuming the GPU is always faster.\n",
    "\n",
    "## 9. Inspect and manage GPU memory\n",
    "\n",
    "GPU memory is distinct from system RAM. PyTorch uses a caching allocator, so allocated memory and reserved memory are different quantities."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2fd48d68",
   "metadata": {},
   "outputs": [],
   "source": [
    "if torch.cuda.is_available():\n",
    "    print(\"Allocated MiB:\", torch.cuda.memory_allocated() / 2**20)\n",
    "    print(\"Reserved MiB:\", torch.cuda.memory_reserved() / 2**20)\n",
    "    print(\"Total MiB:\", torch.cuda.get_device_properties(0).total_memory / 2**20)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "587f73fb",
   "metadata": {},
   "source": [
    "If a computation runs out of memory, reduce tensor sizes or batch sizes, remove references to unused tensors, and consider suitable lower-precision operations after checking numerical accuracy. `torch.cuda.empty_cache()` releases unused cached blocks, not memory occupied by live tensors. Restarting the runtime can clear remaining state but also destroys unsaved work.\n",
    "\n",
    "## 10. Save and restore checkpoints\n",
    "\n",
    "Long-running computations should save intermediate results to persistent storage. Here we save a simple tensor rather than a trained neural network. Run the Drive setup section first."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "000355ac",
   "metadata": {},
   "outputs": [],
   "source": [
    "checkpoint = project / \"tensor_checkpoint.pt\"\n",
    "torch.save({\"step\": 1, \"values\": y.cpu()}, checkpoint)\n",
    "restored = torch.load(checkpoint, map_location=\"cpu\", weights_only=True)\n",
    "print(restored[\"step\"])\n",
    "print(restored[\"values\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9e52b76f",
   "metadata": {},
   "source": [
    "For future model training, checkpoints can include model weights, optimizer state, training progress, and configuration. Save periodically rather than waiting until the entire computation finishes. Only load files from trusted sources.\n",
    "\n",
    "## 11. Improve reproducibility\n",
    "\n",
    "Random seeds help make numerical experiments repeatable. Set them before creating random data or initializing a model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3015e1da",
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "import numpy as np\n",
    "import torch\n",
    "\n",
    "seed = 42\n",
    "random.seed(seed)\n",
    "np.random.seed(seed)\n",
    "torch.manual_seed(seed)\n",
    "print(torch.rand(3))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d55bd3f",
   "metadata": {},
   "source": [
    "A fixed seed does not guarantee identical results across PyTorch releases, hardware, or all GPU algorithms. Record package versions, hardware, data sources, and experiment settings. Test your notebook from a fresh runtime to detect hidden dependencies on earlier cell execution.\n",
    "\n",
    "## 12. Troubleshoot and organize larger projects\n",
    "\n",
    "| Problem | Possible solution |\n",
    "|---|---|\n",
    "| CUDA unavailable | Check the selected runtime and PyTorch build. |\n",
    "| Device mismatch | Move related tensors to the same device. |\n",
    "| CUDA out of memory | Reduce workload size and release unused tensors. |\n",
    "| Slow file reads | Copy frequently accessed data to runtime-local storage. |\n",
    "| Lost runtime | Restore persistent files and rerun setup cells. |\n",
    "| Dependency conflict | Use a tested dependency set and restart if necessary. |\n",
    "\n",
    "For larger projects, separate configuration, reusable Python modules, data, and saved outputs. Keep notebooks focused on orchestration, analysis, and visualization. Save important results before disconnecting, and avoid relying on uninterrupted free runtime access.\n",
    "\n",
    "## Practice exercises\n",
    "\n",
    "1. Benchmark matrix multiplication at sizes 256, 512, and 1024.\n",
    "2. Compare the CPU and GPU timings when a GPU is available.\n",
    "3. Save the timing results as a CSV file in Drive.\n",
    "4. Restart the runtime and restore the saved tensor checkpoint.\n",
    "5. Record your Python and PyTorch versions alongside the results.\n",
    "\n",
    "## Further reading\n",
    "\n",
    "You are now ready to use Colab for introductory scikit-learn, XGBoost, and PyTorch tutorials. Consult the [Colab FAQ](https://research.google.com/colaboratory/faq.html), [PyTorch documentation](https://docs.pytorch.org/docs/stable/index.html), and [PyTorch reproducibility guide](https://docs.pytorch.org/docs/stable/notes/randomness.html) for more details."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
