{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# P7 — Trace Transformer shapes (CPU)\n",
    "\n",
    "Optional companion, no TODO functions. Run top-to-bottom. Begin with B=2, T=5, C=32, H=4. Change only T=5 to T=3, rerun, then restore 5. Track every shape before looking at numeric values.\n",
    ""
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import math\n",
    "import torch\n",
    "\n",
    "torch.manual_seed(5)\n",
    "B, T, C, H = 2, 5, 32, 4  # change T to 3, then restore 5\n",
    "D = C // H\n",
    "assert C % H == 0\n",
    "x = torch.randn(B, T, C)\n",
    "q = x.reshape(B, T, H, D).transpose(1, 2)\n",
    "k = q.clone()\n",
    "v = q.clone()\n",
    "print(\"x:\", tuple(x.shape), \"q:\", tuple(q.shape))\n",
    "assert q.shape == (B, H, T, D)\n",
    ""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Scores: last two dimensions swap\n",
    "\n",
    "`matmul` combines the head-specific channel dimension D; attention scores end in (T,T). A True upper-triangle cell denotes a future position that must be blocked **before** softmax.\n",
    ""
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(D)\n",
    "mask = torch.triu(torch.ones(T, T, dtype=torch.bool), diagonal=1)\n",
    "masked_scores = scores.masked_fill(mask, float(\"-inf\"))\n",
    "weights = torch.softmax(masked_scores, dim=-1)\n",
    "print(\"scores:\", tuple(scores.shape), \"weights:\", tuple(weights.shape))\n",
    "assert scores.shape == (B, H, T, T)\n",
    "assert float(weights.masked_select(mask).abs().sum()) == 0.0\n",
    "assert torch.allclose(weights.sum(dim=-1), torch.ones(B, H, T))\n",
    ""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Multiply weights by V and join heads\n",
    "\n",
    "`weights @ v` is (B,H,T,D). `transpose(1,2)` returns the layout (B,T,H,D); `contiguous().view(B,T,C)` merges channels back. `reshape` may copy when required; `view` requires compatible strides, so call `contiguous()` after transpose if using `view`.\n",
    ""
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "head_out = weights @ v\n",
    "out = head_out.transpose(1, 2).contiguous().view(B, T, C)\n",
    "print(\"head_out:\", tuple(head_out.shape), \"out:\", tuple(out.shape))\n",
    "assert head_out.shape == (B,H,T,D)\n",
    "assert out.shape == x.shape\n",
    "print(\"PASS: causal masks and tensor shapes\")\n",
    ""
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
