{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4c71ef6d",
   "metadata": {},
   "source": [
    "# Week 7.2: Bias Mitigation with Activation Steering\n",
    "\n",
    "In this practical, we'll explore how to measure and mitigate bias in language models\n",
    "using activation steering - a technique that modifies internal representations\n",
    "during inference without retraining the model."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5bed55d6",
   "metadata": {},
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "220216a7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load CrowS-Pairs dataset from GitHub\n",
    "crows_url = \"https://raw.githubusercontent.com/nyu-mll/crows-pairs/master/data/crows_pairs_anonymized.csv\"\n",
    "crows_df = pd.read_csv(crows_url)\n",
    "\n",
    "# Filter for gender bias examples only\n",
    "crows_gender_df = crows_df[crows_df[\"bias_type\"] == \"gender\"]\n",
    "\n",
    "# Extract pairs: (stereotypical, anti-stereotypical)\n",
    "# Note: sent_more is ALWAYS more stereotypical, sent_less is ALWAYS less stereotypical\n",
    "crows_pairs_gender = []\n",
    "for _, row in crows_gender_df.iterrows():\n",
    "    crows_pairs_gender.append((row[\"sent_more\"], row[\"sent_less\"]))\n",
    "\n",
    "print(f\"Loaded {len(crows_pairs_gender)} gender bias pairs from CrowS-Pairs dataset\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "494ff33c",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "outputs": [],
   "source": [
    "import warnings\n",
    "import torch\n",
    "import pandas as pd\n",
    "from master_mind.teaching.hf import load_hf_model, load_hf_tokenizer\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dda49def",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_best_device():\n",
    "    \"\"\"Returns the best device on this computer\"\"\"\n",
    "\n",
    "    if torch.cuda.is_available():\n",
    "        device = torch.device(\"cuda\")\n",
    "        total_memory = torch.cuda.get_device_properties(device).total_memory\n",
    "        print(f\"GPU Memory: {total_memory / 1e9:.1f} GB\")\n",
    "        print(f\"GPU Name: {torch.cuda.get_device_name(device)}\")\n",
    "    elif torch.backends.mps.is_available():\n",
    "        device = torch.device(\"mps\")\n",
    "    else:\n",
    "        device = torch.device(\"cpu\")\n",
    "    print(f\"Found device: {device}\")\n",
    "    return device\n",
    "\n",
    "\n",
    "device = get_best_device()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72ff3afb",
   "metadata": {},
   "outputs": [],
   "source": [
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cd9967cf",
   "metadata": {},
   "source": [
    "## Exercise 1: Measuring Bias with CrowS-Pairs\n",
    "\n",
    "CrowS-Pairs is a benchmark dataset for measuring stereotypical biases in language models.\n",
    "Each example contains a pair of sentences:\n",
    "- A **stereotypical** sentence (reinforces a stereotype)\n",
    "- An **anti-stereotypical** sentence (challenges the stereotype)\n",
    "\n",
    "We measure bias by checking which sentence the model assigns higher probability to.\n",
    "A perfectly unbiased model would prefer each sentence 50% of the time.\n",
    "\n",
    "### CrowS-Pairs Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b2ef6238",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(f\"Number of gender bias pairs: {len(crows_pairs_gender)}\")\n",
    "print(\"\\nExample pairs:\")\n",
    "for i, (stereo, anti) in enumerate(crows_pairs_gender[:3]):\n",
    "    print(f\"\\nPair {i+1}:\")\n",
    "    print(f\"  Stereotypical:     {stereo}\")\n",
    "    print(f\"  Anti-stereotypical: {anti}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0c1d2da3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load model and tokenizer\n",
    "tokenizer = load_hf_tokenizer(\"gpt2\", GPT2Tokenizer)\n",
    "tokenizer.pad_token = tokenizer.eos_token\n",
    "\n",
    "model = load_hf_model(\"gpt2\", GPT2LMHeadModel).to(device)\n",
    "model.eval()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "24c721b1",
   "metadata": {},
   "outputs": [],
   "source": [
    "@torch.no_grad()\n",
    "def compute_sentence_log_prob(sentence: str, model, tokenizer) -> float:\n",
    "    \"\"\"Compute log-likelihood of a sentence under the model.\"\"\"\n",
    "    inputs = tokenizer(sentence, return_tensors=\"pt\").to(device)\n",
    "    input_ids = inputs[\"input_ids\"]\n",
    "\n",
    "    outputs = model(**inputs)\n",
    "    logits = outputs.logits\n",
    "\n",
    "    # Get log probabilities\n",
    "    log_probs = torch.nn.functional.log_softmax(logits, dim=-1)\n",
    "\n",
    "    # Shift: predict next token from current position\n",
    "    shift_log_probs = log_probs[0, :-1, :]\n",
    "    shift_labels = input_ids[0, 1:]\n",
    "\n",
    "    # Gather log probs for actual tokens\n",
    "    token_log_probs = shift_log_probs.gather(\n",
    "        dim=-1, index=shift_labels.unsqueeze(-1)\n",
    "    ).squeeze(-1)\n",
    "\n",
    "    return token_log_probs.sum().item()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "366d7e8a",
   "metadata": {},
   "source": [
    "### Measuring Baseline Bias"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7113335e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Implement bias measurement\n",
    "\n",
    "# Count how often the model prefers the stereotypical sentence\n",
    "# Bias score = stereotypical_wins / total_pairs\n",
    "assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "print(f\"Baseline bias score: {baseline_bias_score:.2%}\")\n",
    "print(\"(50% = no bias, >50% = stereotypical bias)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "46481763",
   "metadata": {},
   "source": [
    "## Exercise 2: Activation Steering\n",
    "\n",
    "Activation steering modifies the model's internal representations during inference\n",
    "to steer its behavior. The key idea:\n",
    "\n",
    "1. **Find a steering direction**: Compute the difference between activations for\n",
    "   stereotypical vs anti-stereotypical sentences\n",
    "2. **Apply steering**: Add/subtract this direction from activations during generation\n",
    "\n",
    "This allows bias mitigation without retraining!\n",
    "\n",
    "### Computing Steering Vector"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72b8b35b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Hook to capture activations\n",
    "class ActivationCapture:\n",
    "    def __init__(self):\n",
    "        self.activations = None\n",
    "\n",
    "    def hook(self, module, input, output):\n",
    "        # Capture the hidden states (output of transformer block)\n",
    "        if isinstance(output, tuple):\n",
    "            self.activations = output[0].detach()\n",
    "        else:\n",
    "            self.activations = output.detach()\n",
    "\n",
    "\n",
    "# We'll steer at a middle layer (layer 6 of GPT-2's 12 layers)\n",
    "steering_layer = 6\n",
    "\n",
    "# Compute average activations for stereotypical and anti-stereotypical sentences\n",
    "stereo_activations = []\n",
    "anti_activations = []\n",
    "\n",
    "capture = ActivationCapture()\n",
    "handle = model.transformer.h[steering_layer].register_forward_hook(capture.hook)\n",
    "\n",
    "\n",
    "# [[unindent]]\n",
    "pairs_to_use = crows_pairs_gender\n",
    "# [[/unindent]]\n",
    "\n",
    "with torch.no_grad():\n",
    "    for stereo, anti in pairs_to_use:\n",
    "        # Get activations for stereotypical sentence\n",
    "        inputs = tokenizer(stereo, return_tensors=\"pt\").to(device)\n",
    "        model(**inputs)\n",
    "        stereo_activations.append(\n",
    "            capture.activations.mean(dim=1)\n",
    "        )  # Average over sequence\n",
    "\n",
    "        # Get activations for anti-stereotypical sentence\n",
    "        inputs = tokenizer(anti, return_tensors=\"pt\").to(device)\n",
    "        model(**inputs)\n",
    "        anti_activations.append(capture.activations.mean(dim=1))\n",
    "\n",
    "handle.remove()\n",
    "\n",
    "# Compute steering vector: direction from stereotypical to anti-stereotypical\n",
    "stereo_mean = torch.stack(stereo_activations).mean(dim=0)\n",
    "anti_mean = torch.stack(anti_activations).mean(dim=0)\n",
    "steering_vector = anti_mean - stereo_mean\n",
    "\n",
    "print(f\"Steering vector shape: {steering_vector.shape}\")\n",
    "print(f\"Steering vector norm: {steering_vector.norm().item():.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "23f13800",
   "metadata": {},
   "source": [
    "### Applying Activation Steering"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "128489ad",
   "metadata": {},
   "outputs": [],
   "source": [
    "class SteeringHook:\n",
    "    def __init__(self, steering_vector, strength=1.0):\n",
    "        self.steering_vector = steering_vector\n",
    "        self.strength = strength\n",
    "\n",
    "    def hook(self, module, input, output):\n",
    "        if isinstance(output, tuple):\n",
    "            hidden_states = output[0]\n",
    "            # Add steering vector to all positions\n",
    "            steered = hidden_states + self.strength * self.steering_vector\n",
    "            return (steered,) + output[1:]\n",
    "        else:\n",
    "            return output + self.strength * self.steering_vector\n",
    "\n",
    "\n",
    "# Measure bias with steering applied\n",
    "\n",
    "# 1. Register the steering hook on the same layer\n",
    "# 2. Measure bias score with steering active\n",
    "# 3. Compare to baseline\n",
    "assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "# Remove the forward hook\n",
    "handle.remove()\n",
    "\n",
    "print(f\"Baseline bias score: {baseline_bias_score:.2%}\")\n",
    "print(f\"Steered bias score:  {steered_bias_score:.2%}\")\n",
    "print(f\"Bias reduction:      {baseline_bias_score - steered_bias_score:.2%}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cbddf447",
   "metadata": {},
   "source": [
    "## Exercise 3: Exploring Steering Strength\n",
    "\n",
    "The steering strength controls how much we modify the activations.\n",
    "Let's explore how different strengths affect bias.\n",
    "\n",
    "### Steering Strength Analysis"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ce4f164f",
   "metadata": {},
   "outputs": [],
   "source": [
    "strengths = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]\n",
    "bias_scores = []\n",
    "\n",
    "for strength in strengths:\n",
    "    steering_hook = SteeringHook(steering_vector, strength=strength)\n",
    "    handle = model.transformer.h[steering_layer].register_forward_hook(\n",
    "        steering_hook.hook\n",
    "    )\n",
    "\n",
    "    stereo_wins = 0\n",
    "    for stereo, anti in crows_pairs_gender:\n",
    "        prob_stereo = compute_sentence_log_prob(stereo, model, tokenizer)\n",
    "        prob_anti = compute_sentence_log_prob(anti, model, tokenizer)\n",
    "        if prob_stereo > prob_anti:\n",
    "            stereo_wins += 1\n",
    "\n",
    "    bias_score = stereo_wins / len(crows_pairs_gender)\n",
    "    bias_scores.append(bias_score)\n",
    "    handle.remove()\n",
    "\n",
    "    print(f\"Strength {strength:.1f}: Bias score = {bias_score:.2%}\")"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_name": "Bias Mitigation with Steering"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
