{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b6c029bc",
   "metadata": {
    "tags": [
     "colab",
     "pip",
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "# Installing required packages\n",
    "\n",
    "%pip install setuptools==80.9.0\n",
    "\n",
    "# Installing main packages\n",
    "\n",
    "%pip install matplotlib==3.10.8\n",
    "%pip install pandas==2.3.3\n",
    "%pip install su-master-mind==2026.1.25.4\n",
    "%pip install torch==2.9.1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a44640be",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import torch\n",
    "from master_mind.teaching.hf import HFModel\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea91915e",
   "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": "markdown",
   "id": "2f6ad8ef",
   "metadata": {},
   "source": [
    "## Environmental Impact\n",
    "\n",
    "Training and running LLMs has environmental costs. In this exercise,\n",
    "we'll measure CO2 emissions and understand trade-offs between model size\n",
    "and environmental impact."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c4c5bb4",
   "metadata": {},
   "source": [
    "### Exercise 4.1: Track Emissions Across Model Sizes\n",
    "\n",
    "We'll use `codecarbon` to track CO2 emissions for different model sizes.\n",
    "\n",
    "### Environmental Impact Measurement"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "46e95693",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import codecarbon\n",
    "import platform\n",
    "\n",
    "# On macOS, patch codecarbon to skip powermetrics (requires sudo)\n",
    "if platform.system() == \"Darwin\":\n",
    "    import codecarbon.core.powermetrics as pm\n",
    "\n",
    "    pm.is_powermetrics_available = lambda: False\n",
    "\n",
    "from codecarbon import OfflineEmissionsTracker\n",
    "\n",
    "print(\"Using offline emissions tracker (estimated carbon intensity)\")\n",
    "\n",
    "\n",
    "def get_tracker(project_name: str) -> OfflineEmissionsTracker:\n",
    "    \"\"\"Create an emissions tracker.\"\"\"\n",
    "    # Offline mode with France carbon intensity (~50 gCO2/kWh)\n",
    "    return OfflineEmissionsTracker(\n",
    "        project_name=project_name,\n",
    "        country_iso_code=\"FRA\",\n",
    "        log_level=\"error\",\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2b1ee31e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Models to compare (from smallest to largest)\n",
    "MODELS_TO_COMPARE = {\n",
    "    \"DistilGPT-2 (82M)\": HFModel(\n",
    "        \"distilgpt2\", tokenizer_cls=GPT2Tokenizer, model_cls=GPT2LMHeadModel\n",
    "    ),\n",
    "    \"GPT-2 Small (124M)\": HFModel(\n",
    "        \"gpt2\", tokenizer_cls=GPT2Tokenizer, model_cls=GPT2LMHeadModel\n",
    "    ),\n",
    "    \"GPT-2 Medium (355M)\": HFModel(\n",
    "        \"gpt2-medium\", tokenizer_cls=GPT2Tokenizer, model_cls=GPT2LMHeadModel\n",
    "    ),\n",
    "}\n",
    "\n",
    "\n",
    "\n",
    "def generate_text(model, tokenizer, prompt: str, max_new_tokens: int = 50) -> str:\n",
    "    \"\"\"Generate text from a prompt.\"\"\"\n",
    "    inputs = tokenizer(prompt, return_tensors=\"pt\").to(device)\n",
    "    with torch.no_grad():\n",
    "        outputs = model.generate(\n",
    "            **inputs,\n",
    "            max_new_tokens=max_new_tokens,\n",
    "            do_sample=True,\n",
    "            temperature=0.7,\n",
    "            pad_token_id=tokenizer.eos_token_id,\n",
    "        )\n",
    "    return tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
    "\n",
    "\n",
    "# Test prompts\n",
    "test_prompts = [\n",
    "    \"The future of artificial intelligence is\",\n",
    "    \"Climate change is affecting\",\n",
    "    \"The most important thing in life is\",\n",
    "]\n",
    "\n",
    "# Number of generations per model\n",
    "n_generations = 10\n",
    "\n",
    "\n",
    "# Track emissions for each model\n",
    "results = []\n",
    "\n",
    "for model_label, hf_model in MODELS_TO_COMPARE.items():\n",
    "    print(f\"\\nTesting {model_label}...\")\n",
    "\n",
    "    # Load model and tokenizer (cached properties)\n",
    "    tokenizer = hf_model.tokenizer\n",
    "    model = hf_model.model\n",
    "    model = model.to(device)\n",
    "    model.eval()\n",
    "\n",
    "    # Set pad token\n",
    "    tokenizer.pad_token = tokenizer.eos_token\n",
    "\n",
    "    # Track emissions\n",
    "    tracker = get_tracker(project_name=model_label)\n",
    "    tracker.start()\n",
    "\n",
    "    for _ in range(n_generations):\n",
    "        prompt = np.random.choice(test_prompts)\n",
    "        _ = generate_text(model, tokenizer, prompt)\n",
    "\n",
    "    emissions = tracker.stop()\n",
    "\n",
    "    # Get model size\n",
    "    n_params = sum(p.numel() for p in model.parameters())\n",
    "\n",
    "    results.append(\n",
    "        {\n",
    "            \"model\": model_label,\n",
    "            \"params_millions\": n_params / 1e6,\n",
    "            \"emissions_g\": emissions * 1000,  # Convert kg to g\n",
    "            \"emissions_per_gen_mg\": (emissions * 1e6) / n_generations,\n",
    "        }\n",
    "    )\n",
    "\n",
    "    # Free memory\n",
    "    del model\n",
    "    torch.cuda.empty_cache() if torch.cuda.is_available() else None\n",
    "\n",
    "# Display results\n",
    "df_emissions = pd.DataFrame(results)\n",
    "print(\"\\n\" + \"=\" * 60)\n",
    "print(\"Emissions Comparison\")\n",
    "print(\"=\" * 60)\n",
    "print(df_emissions.to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d1d3c32",
   "metadata": {},
   "source": [
    "### Exercise 4.2: Visualize the Trade-offs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ecb92763",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(1, 2, figsize=(12, 5))\n",
    "\n",
    "# Plot 1: Emissions vs Model Size\n",
    "ax1 = axes[0]\n",
    "ax1.bar(\n",
    "    df_emissions[\"model\"], df_emissions[\"emissions_per_gen_mg\"], color=\"forestgreen\"\n",
    ")\n",
    "ax1.set_xlabel(\"Model\")\n",
    "ax1.set_ylabel(\"CO2 Emissions per Generation (mg)\")\n",
    "ax1.set_title(\"Carbon Footprint by Model Size\")\n",
    "ax1.tick_params(axis=\"x\", rotation=15)\n",
    "\n",
    "# Plot 2: Emissions scaling with parameters\n",
    "ax2 = axes[1]\n",
    "ax2.scatter(\n",
    "    df_emissions[\"params_millions\"],\n",
    "    df_emissions[\"emissions_per_gen_mg\"],\n",
    "    s=100,\n",
    "    color=\"forestgreen\",\n",
    ")\n",
    "ax2.set_xlabel(\"Parameters (Millions)\")\n",
    "ax2.set_ylabel(\"CO2 Emissions per Generation (mg)\")\n",
    "ax2.set_title(\"Emissions Scaling with Model Size\")\n",
    "\n",
    "# Add labels\n",
    "for _, row in df_emissions.iterrows():\n",
    "    ax2.annotate(\n",
    "        row[\"model\"].split(\" \")[0],\n",
    "        (row[\"params_millions\"], row[\"emissions_per_gen_mg\"]),\n",
    "        textcoords=\"offset points\",\n",
    "        xytext=(5, 5),\n",
    "        fontsize=8,\n",
    "    )\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f5ccf32e",
   "metadata": {},
   "source": [
    "### Discussion: Environmental Impact\n",
    "\n",
    "**Key observations:**\n",
    "- Emissions scale roughly linearly (or worse) with model size\n",
    "- A single generation has tiny emissions, but at scale it matters\n",
    "- A model 4x larger doesn't necessarily give 4x better results\n",
    "\n",
    "**Putting it in perspective:**\n",
    "- 1g CO2 ≈ driving a car 4 meters\n",
    "- Training GPT-3 emitted ~552 tonnes CO2 (≈ 120 cars/year)\n",
    "- Inference costs dominate at scale (millions of queries per day)\n",
    "\n",
    "**What can we do?**\n",
    "- Choose appropriately-sized models for the task\n",
    "- Use distilled models when possible\n",
    "- Consider carbon-aware computing (run when grid is cleaner)\n",
    "- Cache and reuse results"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec8cba81",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## Summary and Key Takeaways\n",
    "\n",
    "In this practical, you learned about:\n",
    "\n",
    "1. **Security Threats** (Exercise 1)\n",
    "   - Tested prompt injection and jailbreak attacks\n",
    "   - Implemented basic defenses (pattern detection, delimiters)\n",
    "   - Understood limitations of simple defenses\n",
    "\n",
    "2. **Bias Measurement & Steering** (Exercise 2)\n",
    "   - Measured gender bias with CrowS-Pairs benchmark\n",
    "   - Identified bias direction in activation space\n",
    "   - Applied activation steering to reduce bias\n",
    "   - Generated preference data for alignment\n",
    "\n",
    "3. **Preference Learning** (Exercise 3)\n",
    "   - Trained Bradley-Terry reward model on preference pairs\n",
    "   - Explored DPO (Direct Preference Optimization) concepts\n",
    "   - Compared steering vs training approaches\n",
    "\n",
    "4. **Environmental Impact** (Exercise 4)\n",
    "   - Measured CO2 emissions across model sizes\n",
    "   - Understood trade-offs between performance and sustainability\n",
    "\n",
    "### Key Tools & Concepts\n",
    "\n",
    "| Topic | Tool/Method | Key Insight |\n",
    "|-------|-------------|-------------|\n",
    "| Security | Pattern matching, delimiters | No perfect defense exists yet |\n",
    "| Bias measurement | CrowS-Pairs | Quantify stereotypical biases |\n",
    "| Bias mitigation | Activation steering | Fast, no training needed |\n",
    "| Alignment | Reward models, DPO | Learn from human preferences |\n",
    "| Sustainability | codecarbon | Make environmental costs visible |\n",
    "\n",
    "### Going Further\n",
    "\n",
    "- **Red teaming**: Systematic adversarial testing at scale\n",
    "- **Constitutional AI**: Training with ethical principles\n",
    "- **Advanced interpretability**: Causal tracing, circuit analysis\n",
    "- **Robust alignment**: Multi-stakeholder frameworks\n",
    "- **Efficient inference**: Quantization, pruning, distillation"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_name": "Environmental Footprint"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
