{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Model Editing"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "NNsight's model editing feature allows you to create persistently modified versions of a model with a use of `.edit()`. Unlike interventions in a tracing context, which are temporary, the **Editor** context enables you to make lasting changes to a model instance.\n",
    "\n",
    "This feature is useful for:\n",
    "* Creating modified model variants without altering the original\n",
    "* Applying changes that persist across multiple forward passes\n",
    "* Comparing interventions between original and edited models\n",
    "\n",
    "Let's explore how to use the **Editor** context to make a simple persistent change to a model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/opt/homebrew/anaconda3/envs/nnsight_local/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n",
      "/opt/homebrew/anaconda3/envs/nnsight_local/lib/python3.12/site-packages/transformers/tokenization_utils_base.py:1601: FutureWarning: `clean_up_tokenization_spaces` was not set. It will be set to `True` by default. This behavior will be deprecated in transformers v4.45, and will be then set to `False` by default. For more details check this issue: https://github.com/huggingface/transformers/issues/31884\n",
      "  warnings.warn(\n",
      "You're using a GPT2TokenizerFast tokenizer. Please note that with a fast tokenizer, using the `__call__` method is faster than using a method to encode the text followed by a call to the `pad` method to get a padded encoding.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Original Prediction:   Rome\n",
      "Modified Prediction:   Paris\n"
     ]
    }
   ],
   "source": [
    "from nnsight import LanguageModel\n",
    "\n",
    "model = LanguageModel('openai-community/gpt2', device_map='auto')\n",
    "\n",
    "# we take the hidden states with the expected output \"Paris\"\n",
    "with model.trace(\"The Eiffel Tower is located in the city of\") as tracer:\n",
    "    hs11 = model.transformer.h[11].output[0][:, -1, :].save()\n",
    "\n",
    "# the edited model will now always predict \"Paris\" as the next token\n",
    "with model.edit() as model_edited:\n",
    "    model.transformer.h[11].output[0][:, -1, :] = hs11\n",
    "\n",
    "# we demonstrate this by comparing the output of an unmodified model...\n",
    "with model.trace(\"Vatican is located in the city of\") as tracer:\n",
    "    original_tokens = model.lm_head.output.argmax(dim=-1).save()\n",
    " \n",
    "# ...with the output of the edited model\n",
    "with model_edited.trace(\"Vatican is located in the city of\") as tracer:\n",
    "    modified_tokens = model.lm_head.output.argmax(dim=-1).save()\n",
    "\n",
    "\n",
    "print(\"\\nOriginal Prediction: \", model.tokenizer.decode(original_tokens[0][-1]))\n",
    "print(\"Modified Prediction: \", model.tokenizer.decode(modified_tokens[0][-1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Edits defined within an **Editor** context create a new, modified version of the model by default, preserving the original. This allows for safe experimentation with model changes. If you wish to modify the original model directly, you can set `inplace=True` when calling `.edit()`. \n",
    "\n",
    "Use this option cautiously, as in-place edits alter the base model for all the consequent model calls."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Modified In-place:   Paris\n"
     ]
    }
   ],
   "source": [
    "# we use the hidden state we saved above (hs11)\n",
    "with model.edit(inplace=True) as model_edited:\n",
    "    model.transformer.h[11].output[0][:, -1, :] = hs11\n",
    "\n",
    "# we demonstrate this by comparing the output of an unmodified model...\n",
    "with model.trace(\"Vatican is located in the city of\") as tracer:\n",
    "    modified_tokens = model.lm_head.output.argmax(dim=-1).save()\n",
    "\n",
    "print(\"Modified In-place: \", model.tokenizer.decode(modified_tokens[0][-1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you've made in-place edits to your model and need to revert these changes, `.clear_edits()` can help. This method removes all edits applied to the model, effectively restoring it to its original state. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Edits cleared:   Rome\n"
     ]
    }
   ],
   "source": [
    "model.clear_edits()\n",
    "\n",
    "with model.trace(\"Vatican is located in the city of\"):\n",
    "    modified_tokens = model.lm_head.output.argmax(dim=-1).save()\n",
    "\n",
    "print(\"Edits cleared: \", model.tokenizer.decode(modified_tokens[0][-1]))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "nnsight_local",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
