{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Custom Functions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Everything within the tracing context operates on the intervention graph. Therefore for `nnsight` to trace a  function it must also be a part of the intervention graph. \n",
    "\n",
    "Out-of-the-box `nnsight` supports Pytorch functions and methods, all operators, as well the `einops` library. We don't need to do anything special to use them. \n",
    "\n",
    "For custom functions we can use `nnsight.apply()` to add them to the intervention graph:"
   ]
  },
  {
   "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",
      "PyTorch sum:  tensor(191.2442, device='mps:0', grad_fn=<SumBackward0>)\n",
      "Our sum:  tensor(191.2442)\n"
     ]
    }
   ],
   "source": [
    "import nnsight\n",
    "from nnsight import LanguageModel\n",
    "import torch\n",
    "\n",
    "model = LanguageModel('openai-community/gpt2', device_map='auto')\n",
    "\n",
    "# We define a simple custom function that sums all the elements of a tensor\n",
    "def tensor_sum(tensor):\n",
    "    flat = tensor.flatten()\n",
    "    total = 0\n",
    "    for element in flat:\n",
    "        total += element.item()\n",
    "    \n",
    "    return torch.tensor(total)\n",
    "\n",
    "with model.trace(\"The Eiffel Tower is in the city of\") as tracer:\n",
    "\n",
    "    # Specify the function name and its arguments (in a coma-separated form) to add to the intervention graph\n",
    "    custom_sum = nnsight.apply(tensor_sum, model.transformer.h[0].output[0]).save()\n",
    "    sum = model.transformer.h[0].output[0].sum().save()\n",
    "    \n",
    "\n",
    "print(\"\\nPyTorch sum: \", sum)\n",
    "print(\"Our sum: \", custom_sum)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`nnsight.apply()` executes the function it wraps and returns its output as a Proxy object. We can then use this Proxy object as we would any other.\n",
    "\n",
    "The applications of `nnsight.apply` are wide. It can be used to wrap any custom function or functions from libraries that `nnsight` does not support out-of-the-box."
   ]
  }
 ],
 "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
}
