{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "from torch.utils.data import Dataset, DataLoader\n",
    "\n",
    "from htools import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SeqDataset(Dataset):\n",
    "    \n",
    "    def __init__(self, sentence_tokens, labels):\n",
    "        self.x = sentence_tokens\n",
    "        self.y = labels\n",
    "        \n",
    "    def __getitem__(self, i):\n",
    "        return self.x[i], self.y[i]\n",
    "        \n",
    "    def __len__(self):\n",
    "        return len(self.x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class PositionalAdjustment(nn.Module):\n",
    "    \n",
    "    def __init__(self, seq_len, emb_len):\n",
    "        super().__init__()\n",
    "        self.weight = nn.Parameter(torch.Tensor(seq_len, emb_len))\n",
    "        self.weight.data.uniform_(-1, 1)\n",
    "        \n",
    "    def forward(self, x):\n",
    "        return x + self.weight"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Parameter containing:\n",
       "tensor([[-0.0878, -0.3883, -0.8043, -0.2112, -0.8069],\n",
       "        [ 0.7833,  0.1276, -0.5188,  0.5671, -0.8165],\n",
       "        [ 0.4665, -0.1780,  0.3808, -0.4395,  0.7865]], requires_grad=True)"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pos = PositionalAdjustment(3, 5)\n",
    "pos.weight"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SeqNet(nn.Module):\n",
    "    \n",
    "    def __init__(self, vocab_size, emb_len, seq_len):\n",
    "        super().__init__()\n",
    "        self.emb = nn.Embedding(vocab_size, emb_len)\n",
    "        self.pos = PositionalAdjustment(seq_len, emb_len)\n",
    "#         self.emb_t = nn.Embedding(seq_len, emb_len)\n",
    "#         self.t_idx = torch.arange(0, seq_len, dtype=torch.long)\n",
    "    \n",
    "    def forward(self, x):\n",
    "#         return self.emb(x) + self.emb_t(self.t_idx)\n",
    "        x = self.emb(x)\n",
    "        print(x)\n",
    "        return self.pos(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "v_size = 5\n",
    "e_len = 4\n",
    "s_len = 3\n",
    "bs = 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[0, 3, 4],\n",
      "        [4, 4, 1]]) tensor([0, 1])\n"
     ]
    }
   ],
   "source": [
    "sent_tokens = torch.randint(0, 5, (8, 3))\n",
    "labels = torch.randint(0, 2, size=(8,))\n",
    "ds = SeqDataset(sent_tokens, labels)\n",
    "dl = DataLoader(ds, batch_size=bs, shuffle=False)\n",
    "x, y = next(iter(dl))\n",
    "print(x, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "SeqNet(\n",
       "  (emb): Embedding(5, 4)\n",
       "  (pos): PositionalAdjustment()\n",
       ")"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net = SeqNet(v_size, e_len, s_len)\n",
    "net"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Parameter containing:\n",
       "tensor([[-0.2536,  1.8791,  2.1079,  1.7764],\n",
       "        [-2.3785, -1.0723,  1.1331, -0.1812],\n",
       "        [-0.7185, -0.6620, -0.3901,  2.9127],\n",
       "        [-2.1197,  0.3470, -0.3491,  0.1351],\n",
       "        [-0.3396, -0.5042, -1.4771,  0.5427]], requires_grad=True)"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net.emb.weight"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Parameter containing:\n",
       "tensor([[ 0.4808, -0.4810, -0.3525,  0.1046],\n",
       "        [ 0.9008, -0.3267, -0.8862, -0.6773],\n",
       "        [ 0.0175,  0.0239,  0.3719, -0.9512]], requires_grad=True)"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net.pos.weight"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[[-0.2536,  1.8791,  2.1079,  1.7764],\n",
      "         [-2.1197,  0.3470, -0.3491,  0.1351],\n",
      "         [-0.3396, -0.5042, -1.4771,  0.5427]],\n",
      "\n",
      "        [[-0.3396, -0.5042, -1.4771,  0.5427],\n",
      "         [-0.3396, -0.5042, -1.4771,  0.5427],\n",
      "         [-2.3785, -1.0723,  1.1331, -0.1812]]], grad_fn=<EmbeddingBackward>)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "torch.Size([2, 3, 4])"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "yhat = net(x)\n",
    "yhat.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[ 0.2272,  1.3980,  1.7555,  1.8809],\n",
       "         [-1.2188,  0.0203, -1.2352, -0.5422],\n",
       "         [-0.3221, -0.4803, -1.1052, -0.4085]],\n",
       "\n",
       "        [[ 0.1411, -0.9852, -1.8295,  0.6472],\n",
       "         [ 0.5612, -0.8309, -2.3632, -0.1347],\n",
       "         [-2.3610, -1.0484,  1.5050, -1.1324]]], grad_fn=<AddBackward0>)"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "yhat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Parameter containing:\n",
       "tensor([[ 0.3051, -0.2961,  0.4608, -0.0259]], requires_grad=True)"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fc = nn.Linear(4, 1)\n",
    "fc.weight"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([-2.1298], grad_fn=<AddBackward0>)"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# First row of item 1 in batch dotted with weight matrix.\n",
    "-1.2705*.3051 -.2961*4.62 +.4608*-.6619 +.5565*.0259 + fc.bias"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[-2.1299],\n",
       "         [ 1.0206],\n",
       "         [-0.1805]],\n",
       "\n",
       "        [[-1.0462],\n",
       "         [-0.2085],\n",
       "         [-1.2599]]], grad_fn=<AddBackward0>)"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "yhat @ fc.weight.t() + fc.bias"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[-2.1299],\n",
       "         [ 1.0206],\n",
       "         [-0.1805]],\n",
       "\n",
       "        [[-1.0462],\n",
       "         [-0.2085],\n",
       "         [-1.2599]]], grad_fn=<AddBackward0>)"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fc(yhat)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Dropin(nn.Module):\n",
    "    \"\"\"Think about if this would need to work differently in training vs.\n",
    "    eval mode, like multiplicative dropout.\n",
    "    \n",
    "    Work in progress, not sure if xavier normal is a good choice - just an \n",
    "    example.\n",
    "    \n",
    "    Also look into if floating point addition might be faster/slower on gpu\n",
    "    than multiplication.\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self, *dims):\n",
    "        super().__init__()\n",
    "        self.weight = nn.Parameter(torch.Tensor(*dims))\n",
    "        nn.init.xavier_normal_(self.weight.data)\n",
    "        \n",
    "    def forward(self, x):\n",
    "        return x + self.weight"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Parameter containing:\n",
       "tensor([[[ 0.2117,  0.6571, -1.0676, -0.6031],\n",
       "         [ 0.7047,  0.7008,  0.2394, -0.0974],\n",
       "         [-0.0186,  0.0943,  0.0224,  0.4781]],\n",
       "\n",
       "        [[-0.1908, -0.3783, -0.1678, -0.6919],\n",
       "         [ 0.4274, -0.0934,  0.2975, -0.4185],\n",
       "         [-0.0236, -0.0022,  0.5413,  0.0780]]], requires_grad=True)"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "drop = Dropin(*yhat.shape)\n",
    "drop.weight"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[ 0.2272,  1.3980,  1.7555,  1.8809],\n",
       "         [-1.2188,  0.0203, -1.2352, -0.5422],\n",
       "         [-0.3221, -0.4803, -1.1052, -0.4085]],\n",
       "\n",
       "        [[ 0.1411, -0.9852, -1.8295,  0.6472],\n",
       "         [ 0.5612, -0.8309, -2.3632, -0.1347],\n",
       "         [-2.3610, -1.0484,  1.5050, -1.1324]]], grad_fn=<AddBackward0>)"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "yhat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[ 0.4389,  2.0551,  0.6879,  1.2779],\n",
       "         [-0.5141,  0.7211, -0.9958, -0.6397],\n",
       "         [-0.3407, -0.3860, -1.0828,  0.0695]],\n",
       "\n",
       "        [[-0.0497, -1.3636, -1.9973, -0.0447],\n",
       "         [ 0.9886, -0.9243, -2.0657, -0.5532],\n",
       "         [-2.3846, -1.0506,  2.0464, -1.0544]]], grad_fn=<AddBackward0>)"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "drop(yhat)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Object `torch.corr` not found.\n"
     ]
    }
   ],
   "source": [
    "torch.corr?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1.        , 0.92782724],\n",
       "       [0.92782724, 1.        ]])"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.corrcoef(yhat.detach().numpy().flatten(),\n",
    "            drop(yhat).detach().numpy().flatten())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1.        , 0.17803766],\n",
       "       [0.17803766, 1.        ]])"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.corrcoef(drop.weight.detach().numpy().flatten(),\n",
    "            drop(yhat).detach().numpy().flatten())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
