{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Experiments\n",
    "\n",
    "An _experiment_ allows you to run different models, or several variants of\n",
    "the same model, in a deployment to compare their performance on real data. They can be used to implement [A / B testing](https://en.wikipedia.org/wiki/A/B_testing),\n",
    "shadow deployments, and many other multi-model comparisons.\n",
    "\n",
    "There are currently three supported modes, random split, key split and shadow deploy. Random split will route incoming requests to specified\n",
    "models randomly in accordance with the specified percentages. Key split will route incoming requests to the specified models based on the value of a meta key field. This allows you to treat a cohort of models as a single functional unit where all incoming inferences are routed to the correct model in the cohort. Shadow deploy will send each request to multiple models, return the result from the default model and log the results of all the models.\n",
    "\n",
    "The random split mode allows you to perform _randomized control trial_ type experiment where the model is chosen randomly. You can specify the percentage of requests each model recieives by assigning a 'weight'. Weights are automatically normalized into a percentage for you so you don't need to worry about them adding up to a particular value. You can also specify a meta key field to be used to generate the random cohort in a consistent manner. This might be useful if you want the model that handles requests from a particular user (or group) to be random but consistent. In that case the split_key might be the session_id or something similar.\n",
    "\n",
    "Value split allows you to specifically choose which model handles requests for a user (or group). For example, if you want all 'gold' card users to go to one fraud prediction model and all 'black' card users to go to another.\n",
    "\n",
    "Shadow deploy allows you to test new models without removing the default/control model. This is particularly useful for “burn-in” testing a new model with real world data without displacing the currently proven model.\n",
    "\n",
    "Use cases include validation of a new model variant, and comparison of the performance of different models.\n",
    "\n",
    "## Random Split Experiment Example\n",
    "\n",
    "Let's take a quick look at how we can define and deploy an experiment. First, let's initialize a reference to the Wallaroo system.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import wallaroo\n",
    "\n",
    "wl = wallaroo.Client()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First we'll upload our \"default\" or control model along with an alternate \"challenger\" model that we'll use in this notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "default_model    = wl.upload_model(\"control\", \"./keras_ccfraud.onnx\")\n",
    "challenger_model = wl.upload_model(\"challenger\", \"./modelA.onnx\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we can verify that the models have been uploaded."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'model_class': 'challenger',\n",
       "  'model_name': '61aa19e7-6ef3-4bed-b9ea-41e56478fdee'},\n",
       " {'model_class': 'control',\n",
       "  'model_name': 'cb89782b-4dba-45de-b85e-83f485bbfa28'}]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "models = wl.list_models()\n",
    "[{\"model_class\": m.name(), \"model_name\": m.version()} for m in models]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Experiments run in Pipelines\n",
    "\n",
    "To set up an experiment we create a `pipeline` to process the request in each inference engine.\n",
    "There are convenience classes and methods to help create appropriate pipelines for each mode.\n",
    "\n",
    "Let's set up a random split experiment pipeline where the default model has a weight of 2 and the challenger has a weight of 1. This means that the default model will receive approx 66% (2/3) of the traffic and the challenger 33%. Feel free to use .66 and .33 as weights if you prefer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "pipeline = (wl.build_pipeline(\"randomsplitpipeline\")\n",
    "            .add_random_split([(2, default_model), (1, challenger_model)], \"session_id\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, let's deploy that pipeline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Waiting for deployment - this will take up to 45s ...... ok\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'name': 'randomsplitpipeline', 'create_time': datetime.datetime(2022, 3, 3, 22, 15, 35, 649256, tzinfo=tzutc()), 'definition': \"[{'RandomSplit': {'hash_key': 'session_id', 'weights': [{'model': {'name': 'control', 'version': '59d4baf0-152b-4b62-aae8-caa095436414', 'sha': 'bc85ce596945f876256f41515c7501c399fd97ebcb9ab3dd41bf03f8937b4507'}, 'weight': 2}, {'model': {'name': 'challenger', 'version': '98679550-af37-4709-b930-d114b53acc8a', 'sha': '438cd2762590b712106235dc4d635ca50b21304f42ee9529c7acd0b0aecac624'}, 'weight': 1}]}}]\"}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pipeline.deploy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While that is coming up, lets create a little function that will help us calculate the percentage of requests each model gets."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "import collections\n",
    "\n",
    "def frequencies(responses):\n",
    "    c = collections.Counter([r.model()[0] for r in responses])\n",
    "    total = 0\n",
    "    for k,v in c.items():\n",
    "        total += v\n",
    "\n",
    "    for k,v in c.items():\n",
    "        print(f\"{k:15} {v} inferences {v/total*100:5.2f}%\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And let's load some test data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "with open('dev_smoke_test.json', \"rb\") as f:\n",
    "    data = json.load(f)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, let's run a number of inferences and look at the percentages. We should see that the control model gets ~66% of the requests. Note that this is a random process so actual ratios will vary."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "control         661 inferences 66.10%\n",
      "challenger      339 inferences 33.90%\n"
     ]
    }
   ],
   "source": [
    "num_runs = 1000\n",
    "responses = []\n",
    "for _ in range(num_runs):\n",
    "    responses.extend(pipeline.infer(data))\n",
    "\n",
    "frequencies(responses)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Let's try a stable hash key\n",
    "\n",
    "The hash key `session_id` was set up in our pipeline configuration, but we didn't pass it in during that first trial.\n",
    "Let's set an arbitrary key and see what happens. It should result in similar ratios."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "control         694 inferences 69.40%\n",
      "challenger      306 inferences 30.60%\n"
     ]
    }
   ],
   "source": [
    "responses = []\n",
    "for i in range(num_runs):\n",
    "    data['session_id'] = f\"session_{i}\"\n",
    "    responses.extend(pipeline.infer(data))\n",
    "frequencies(responses)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Let's try a constant stability key\n",
    "\n",
    "With a constant key we'd expect every request to go to the same randomly choosen model. You can change the session_id value and see that the model chosen changes randomly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "control         1000 inferences 100.00%\n"
     ]
    }
   ],
   "source": [
    "responses = []\n",
    "for i in range(num_runs):\n",
    "    data['session_id'] = f\"session_abc\"\n",
    "    responses.extend(pipeline.infer(data))\n",
    "frequencies(responses)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, let's shut down this experiment and try another one."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'name': 'randomsplitpipeline', 'create_time': datetime.datetime(2022, 3, 3, 22, 15, 35, 649256, tzinfo=tzutc()), 'definition': \"[{'RandomSplit': {'hash_key': 'session_id', 'weights': [{'model': {'name': 'control', 'version': '59d4baf0-152b-4b62-aae8-caa095436414', 'sha': 'bc85ce596945f876256f41515c7501c399fd97ebcb9ab3dd41bf03f8937b4507'}, 'weight': 2}, {'model': {'name': 'challenger', 'version': '98679550-af37-4709-b930-d114b53acc8a', 'sha': '438cd2762590b712106235dc4d635ca50b21304f42ee9529c7acd0b0aecac624'}, 'weight': 1}]}}]\"}"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pipeline.undeploy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Key Split Experiment Example\n",
    "\n",
    "Now, let's define a _pipeline_ that automatically splits inference data on a given `meta_key_name`. Requests with `card_type == gold` go to the challenger. All other requests go to the default model. We'll use the same model variants as before to save time but each experiment deployment would typically have its own models."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "meta_key_name = 'card_type'\n",
    "pipeline = wl.build_pipeline(\"keysplitpipeline\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'name': 'keysplitpipeline', 'create_time': datetime.datetime(2022, 3, 3, 22, 39, 56, 44234, tzinfo=tzutc()), 'definition': \"[{'MetaValueSplit': {'split_key': 'card_type', 'control': {'name': 'control', 'version': '59d4baf0-152b-4b62-aae8-caa095436414', 'sha': 'bc85ce596945f876256f41515c7501c399fd97ebcb9ab3dd41bf03f8937b4507'}, 'routes': {'gold': {'name': 'challenger', 'version': '98679550-af37-4709-b930-d114b53acc8a', 'sha': '438cd2762590b712106235dc4d635ca50b21304f42ee9529c7acd0b0aecac624'}}}}]\"}"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pipeline.add_key_split(default_model, meta_key_name, {\"gold\": challenger_model}).deploy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And test that inference data goes to the control by default:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('control', 'cb89782b-4dba-45de-b85e-83f485bbfa28')"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data['card_type'] = 'silver'\n",
    "pipeline.infer(data)[0].model()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And finally, test that data gets routed to the experimental model when the right meta-value is set:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('challenger', '61aa19e7-6ef3-4bed-b9ea-41e56478fdee')"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data['card_type'] = 'gold'\n",
    "pipeline.infer(data)[0].model()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The get audit logs function can be used to get the logs for further analysis. Each log record is similar the the result of an inference  and will contain the pipeline_id, model and variant chosen as well as the inputs, outputs time and elapsed time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2022-02-04 20:19:32.769000 control\n",
      "2022-02-04 20:19:35.871000 challenger\n"
     ]
    }
   ],
   "source": [
    "logs = pipeline.logs()\n",
    "for log in logs:\n",
    "    print(log.timestamp, log.model_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'name': 'keysplitpipeline', 'create_time': datetime.datetime(2022, 3, 3, 22, 39, 56, 44234, tzinfo=tzutc()), 'definition': \"[{'MetaValueSplit': {'split_key': 'card_type', 'control': {'name': 'control', 'version': '59d4baf0-152b-4b62-aae8-caa095436414', 'sha': 'bc85ce596945f876256f41515c7501c399fd97ebcb9ab3dd41bf03f8937b4507'}, 'routes': {'gold': {'name': 'challenger', 'version': '98679550-af37-4709-b930-d114b53acc8a', 'sha': '438cd2762590b712106235dc4d635ca50b21304f42ee9529c7acd0b0aecac624'}}}}]\"}"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pipeline.undeploy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Shadow Deploy Experiment Example\n",
    "\n",
    "Finally, let's create a \"shadow deployment\" experiment pipeline. The `champion` model and all `challengers` are run for each input. The result data for all models is logged, but the output of the `champion` is the only result returned.\n",
    "\n",
    "This is particularly useful for \"burn-in\" testing a new model with real world data without displacing the currently proven model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Waiting for deployment - this will take up to 45s ...... ok\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'name': 'shadowdeploypipeline', 'create_time': datetime.datetime(2022, 3, 3, 22, 42, 53, 628431, tzinfo=tzutc()), 'definition': \"[{'ModelInference': {'models': [{'name': 'control', 'version': '59d4baf0-152b-4b62-aae8-caa095436414', 'sha': 'bc85ce596945f876256f41515c7501c399fd97ebcb9ab3dd41bf03f8937b4507'}, {'name': 'challenger', 'version': '98679550-af37-4709-b930-d114b53acc8a', 'sha': '438cd2762590b712106235dc4d635ca50b21304f42ee9529c7acd0b0aecac624'}]}}, {'AuditResults': {'from': 1, 'to': None}}, {'Nth': {'index': 0}}]\"}"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pipeline = wl.build_pipeline(\"shadowdeploypipeline\")\n",
    "pipeline.add_shadow_deploy(default_model, [challenger_model])\n",
    "pipeline.deploy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We get the response from the control model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('control', 'cb89782b-4dba-45de-b85e-83f485bbfa28')"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res = pipeline.infer(data)\n",
    "res[0].model()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And logs are created for both models."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2022-02-04 20:20:26.072000 challenger\n",
      "2022-02-04 20:20:26.072000 control\n"
     ]
    }
   ],
   "source": [
    "logs = pipeline.logs()\n",
    "for log in logs:\n",
    "    print(log.timestamp, log.model_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'name': 'shadowdeploypipeline', 'create_time': datetime.datetime(2022, 3, 3, 22, 42, 53, 628431, tzinfo=tzutc()), 'definition': \"[{'ModelInference': {'models': [{'name': 'control', 'version': '59d4baf0-152b-4b62-aae8-caa095436414', 'sha': 'bc85ce596945f876256f41515c7501c399fd97ebcb9ab3dd41bf03f8937b4507'}, {'name': 'challenger', 'version': '98679550-af37-4709-b930-d114b53acc8a', 'sha': '438cd2762590b712106235dc4d635ca50b21304f42ee9529c7acd0b0aecac624'}]}}, {'AuditResults': {'from': 1, 'to': None}}, {'Nth': {'index': 0}}]\"}"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pipeline.undeploy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## API Reference\n",
    "\n",
    "See:\n",
    "\n",
    "- [Model](sdk.rst#wallaroo.model.Model)\n",
    "- [ModelConfig](sdk.rst#wallaroo.model_config.ModelConfig)\n",
    "- [Pipeline](sdk.rst#wallaroo.pipeline.Pipeline)\n",
    "- [Deployment](sdk.rst#wallaroo.deployment.Deployment)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.8.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
