{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Iterative Interventions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A simple `for` loop with a **Tracer context** inside it results in many intervention graphs created over and over at each iteration - this is not scalable. \n",
    "\n",
    "The **Iterator context** allows us to run an intervention loop at scale. It iteratively executes and updates a single intervention graph.\n",
    "\n",
    "Use a `session` to define the **Iterator context** and pass in a sequence of items that you want to loop over at each iteration:"
   ]
  },
  {
   "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"
     ]
    }
   ],
   "source": [
    "import nnsight\n",
    "from nnsight import LanguageModel\n",
    "\n",
    "model = LanguageModel('openai-community/gpt2', device_map='auto')\n",
    "\n",
    "\n",
    "with model.session() as session:\n",
    "\n",
    "  with session.iter([0, 1, 2]) as item:\n",
    "    # define intervention body here ...\n",
    "\n",
    "    with model.trace(\"_\"):\n",
    "      # define interventions here ...\n",
    "      pass\n",
    "\n",
    "    with model.trace(\"_\"):\n",
    "      # define interventions here ...\n",
    "      pass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `Iterator` context extends all the `nnsight` graph-based functionalities, but also closely mimics the conventional `for` loop statement in Python, which allows it to support all kind of iterative operations with a use of `as item` syntax:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "List:  [0, 1, 2]\n"
     ]
    }
   ],
   "source": [
    "\n",
    "with model.session() as session:\n",
    "\n",
    "  li = nnsight.list() # an NNsight built-in list object\n",
    "  [li.append([num]) for num in range(0, 3)] # adding [0], [1], [2] to the list\n",
    "  li2 = nnsight.list().save()\n",
    "  \n",
    "  # You can create nested Iterator contexts\n",
    "  with session.iter(li) as item:\n",
    "    with session.iter(item) as item_2:\n",
    "      li2.append(item_2)\n",
    "\n",
    "print(\"\\nList: \", li2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can also expose the `iterator` context object via a `return_context` flag. You can then use it to `exit` out of the Iteration loop early and log the intermediate outputs within the loop:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "with model.session() as session:\n",
    "  \n",
    "  with session.iter([0, 1, 2, 3], return_context=True) as (item, iterator):\n",
    "      \n",
    "      iterator.log(item)\n",
    "      \n",
    "      with iterator.cond(item == 2):\n",
    "        iterator.exit()\n"
   ]
  }
 ],
 "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
}
