{
  "nbformat": 4,
  "nbformat_minor": 5,
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.12.14"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Does GPT-2 read the future?\n",
        "\n",
        "Predict before running: will changing a suffix change an earlier position’s next-token distribution? Then change a word in the prefix as a positive control.\n",
        "\n",
        "This notebook loads pinned GPT-2 weights on CPU. First run downloads roughly 0.5 GB; allow several GB of available RAM. It performs no remote inference and needs no account.\n",
        "\n",
        "Source: https://huggingface.co/openai-community/gpt2/tree/607a30d783dfa663caf39e06633721c8d4cfcd7e\n",
        "\n",
        "Published measurements: https://insidethemodel.app/trace/gpt2-causal-check.json\n",
        "\n",
        "The measured result concerns causal information flow in these comparisons, not general model understanding.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "%pip install --extra-index-url https://download.pytorch.org/whl/cpu torch==2.14.1+cpu transformers==5.19.0 huggingface_hub==2.2.0\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Controlled measurement\n",
        "\n",
        "The code verifies equal sequence lengths, identical token prefixes, dropout disabled, future attention exactly zero, and a changed-prefix positive control. It fails before publishing a result if a check fails.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "\"\"\"Reproduce causal prefix invariance on pinned GPT-2 weights, on a CPU.\n",
        "\n",
        "Install torch and transformers in a virtual environment; see the accompanying\n",
        "requirements and notebook. First run downloads roughly 0.5 GB of model weights.\n",
        "No account, token, GPU, remote inference, or trust_remote_code is required.\n",
        "\"\"\"\n",
        "import argparse\n",
        "import hashlib\n",
        "import importlib.metadata\n",
        "import json\n",
        "import platform\n",
        "from datetime import datetime, timezone\n",
        "from pathlib import Path\n",
        "\n",
        "MODEL = \"openai-community/gpt2\"\n",
        "REVISION = \"607a30d783dfa663caf39e06633721c8d4cfcd7e\"\n",
        "\n",
        "\n",
        "def prepare_pair(tokenizer, prefix, suffix_a, suffix_b, control_prefix):\n",
        "    \"\"\"Validate the tokenized complete inputs, including the text boundary.\"\"\"\n",
        "    prefix_ids = tokenizer.encode(prefix)\n",
        "    control_ids = tokenizer.encode(control_prefix)\n",
        "    a = tokenizer.encode(prefix + suffix_a)\n",
        "    b = tokenizer.encode(prefix + suffix_b)\n",
        "    control = tokenizer.encode(control_prefix + suffix_a)\n",
        "    n = len(prefix_ids)\n",
        "    if not n or len(control_ids) != n:\n",
        "        raise ValueError(\"Use nonempty prefixes with equal token counts.\")\n",
        "    if a[:n] != prefix_ids or b[:n] != prefix_ids or control[:n] != control_ids:\n",
        "        raise ValueError(\"The prefix tokenization changes at the text boundary. Try suffixes with a leading space.\")\n",
        "    if len(a) != len(b) or len(a) != len(control) or len(a) <= n:\n",
        "        raise ValueError(\"Keep complete input lengths equal, with at least one suffix token.\")\n",
        "    if a[n:] == b[n:]:\n",
        "        raise ValueError(\"The suffixes must change at least one token.\")\n",
        "    if prefix_ids == control_ids or a[n:] != control[n:]:\n",
        "        raise ValueError(\"The positive control must change the prefix while preserving the suffix tokens.\")\n",
        "    return a, b, control, n - 1\n",
        "\n",
        "\n",
        "def run(output: Path, pairs=None):\n",
        "    import torch\n",
        "    from huggingface_hub import hf_hub_download\n",
        "    from transformers import AutoModelForCausalLM, AutoTokenizer\n",
        "\n",
        "    torch.set_num_threads(2)\n",
        "    tokenizer = AutoTokenizer.from_pretrained(MODEL, revision=REVISION)\n",
        "    model = AutoModelForCausalLM.from_pretrained(\n",
        "        MODEL, revision=REVISION, use_safetensors=True,\n",
        "        attn_implementation=\"eager\", trust_remote_code=False,\n",
        "    ).cpu().eval()\n",
        "    tolerance = 1e-6\n",
        "    measurements = []\n",
        "    pairs = pairs if pairs is not None else [\n",
        "        (\"The cat sat\", \" on the mat\", \" on the bed\", \"The dog sat\"),\n",
        "        (\"Alice and Bob went\", \" to the park\", \" to the beach\", \"Alice and Sam went\"),\n",
        "    ]\n",
        "    with torch.inference_mode():\n",
        "        for prefix, suffix_a, suffix_b, control_prefix in pairs:\n",
        "            a, b, control, position = prepare_pair(tokenizer, prefix, suffix_a, suffix_b, control_prefix)\n",
        "            if len(a) > model.config.n_positions:\n",
        "                raise ValueError(\"The input exceeds this model's context length.\")\n",
        "            out_a = model(torch.tensor([a]), output_attentions=True)\n",
        "            out_b = model(torch.tensor([b]), output_attentions=True)\n",
        "            out_control = model(torch.tensor([control]))\n",
        "            pa = out_a.logits[0, position].softmax(-1)\n",
        "            pb = out_b.logits[0, position].softmax(-1)\n",
        "            pc = out_control.logits[0, position].softmax(-1)\n",
        "            difference = float((pa - pb).abs().max())\n",
        "            control_difference = float((pa - pc).abs().max())\n",
        "            future = max(float(layer[0, :, position, position + 1:].abs().max())\n",
        "                         for out in [out_a, out_b] for layer in out.attentions)\n",
        "            assert difference <= tolerance, \"causal prefix check failed\"\n",
        "            assert future == 0.0, \"future attention is not zero\"\n",
        "            assert control_difference > tolerance, \"positive control did not change the distribution\"\n",
        "            top = pa.topk(5)\n",
        "            measurements.append({\n",
        "                \"prefix\": prefix, \"input_a\": prefix + suffix_a,\n",
        "                \"input_b\": prefix + suffix_b, \"positive_control\": control_prefix + suffix_a,\n",
        "                \"token_ids_a\": a, \"token_ids_b\": b, \"token_ids_positive_control\": control, \"position\": position,\n",
        "                \"max_probability_difference\": difference,\n",
        "                \"max_future_attention\": future,\n",
        "                \"positive_control_max_probability_difference\": control_difference,\n",
        "                \"top_tokens_at_prefix\": [\n",
        "                    {\"token_id\": int(i), \"text\": tokenizer.decode([int(i)]), \"probability\": float(p)}\n",
        "                    for p, i in zip(top.values, top.indices)\n",
        "                ],\n",
        "            })\n",
        "    weight_path = hf_hub_download(MODEL, \"model.safetensors\", revision=REVISION)\n",
        "    digest = hashlib.sha256()\n",
        "    with open(weight_path, \"rb\") as handle:\n",
        "        for block in iter(lambda: handle.read(1024 * 1024), b\"\"):\n",
        "            digest.update(block)\n",
        "    result = {\n",
        "        \"schema_version\": 1, \"executed_at\": datetime.now(timezone.utc).isoformat(),\n",
        "        \"model\": MODEL, \"revision\": REVISION, \"weight_sha256\": digest.hexdigest(),\n",
        "        \"parameter_count\": sum(p.numel() for p in model.parameters()),\n",
        "        \"device\": \"cpu\", \"dtype\": str(next(model.parameters()).dtype),\n",
        "        \"attention_implementation\": \"eager\", \"dropout\": \"disabled via eval()\",\n",
        "        \"python\": platform.python_version(), \"platform\": platform.platform(),\n",
        "        \"packages\": {name: importlib.metadata.version(name) for name in [\"torch\", \"transformers\", \"huggingface_hub\"]},\n",
        "        \"tolerance\": tolerance, \"measurements\": measurements,\n",
        "        \"scope\": f\"{len(measurements)} controlled prefix/suffix comparisons and changed-prefix positive controls. This tests causal information flow, not interpretability of GPT-2 behavior generally.\",\n",
        "    }\n",
        "    output = Path(output)\n",
        "    output.parent.mkdir(parents=True, exist_ok=True)\n",
        "    output.write_text(json.dumps(result, indent=2) + \"\\n\", encoding=\"utf-8\")\n",
        "    print(json.dumps({\"output\": str(output), \"revision\": REVISION, \"checks\": len(measurements), \"max_difference\": max(m[\"max_probability_difference\"] for m in measurements)}))\n",
        "    return result\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "result = run(Path(\"gpt2-causal-check.json\"))\n",
        "for measurement in result[\"measurements\"]:\n",
        "    print(measurement[\"prefix\"], measurement[\"max_probability_difference\"], measurement[\"positive_control_max_probability_difference\"])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Try your own controlled inputs\n",
        "\n",
        "Keep the measured prefix token IDs fixed and use equal-length suffixes. The helper validates complete text tokenization, including the prefix/suffix boundary.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "custom = run(Path(\"my-gpt2-check.json\"), pairs=[(\"The dog ran\", \" to the park\", \" to the beach\", \"The cat ran\")])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Investigate further\n",
        "\n",
        "1. Predict and test another equal-token-length suffix pair.\n",
        "2. Change a token before the selected position; explain why this control should be able to change the result.\n",
        "3. Repeat with another pinned causal model, record model/revision/environment, and compare tolerances.\n",
        "4. Write what the result does not establish: zero future attention does not identify the algorithm used to choose a token.\n",
        "\n",
        "This notebook is distributed with the site’s noncommercial code license. GPT-2 has its own model license, linked in its model card.\n"
      ]
    }
  ]
}
