{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# default_exp models.mf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#hide\n",
    "!pip install pytorch-lightning\n",
    "!git clone --branch US632593 https://github.com/RecoHut-Projects/recohut.git\n",
    "%cd recohut\n",
    "!pip install -U .\n",
    "!apt-get -qq install tree\n",
    "!pip install -q watermark"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# MF\n",
    "> Implementation of Matrix Factorization model in PyTorch Lightning."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#hide\n",
    "from nbdev.showdoc import *\n",
    "from fastcore.nb_imports import *\n",
    "from fastcore.test import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#export\n",
    "from typing import Any, Iterable, List, Optional, Tuple, Union, Callable\n",
    "import os\n",
    "\n",
    "import torch\n",
    "from torch import nn\n",
    "from torch.nn import functional as F\n",
    "\n",
    "from recohut.models.bases.common import PointModel"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#export\n",
    "class MF(PairModel):\n",
    "    \"\"\"A matrix factorization model trained using SGD and negative sampling.\"\"\"\n",
    "\n",
    "    def __init__(self, n_users, n_items, embedding_dim):\n",
    "        super().__init__()\n",
    "        self.user_embedding = nn.Embedding(\n",
    "            num_embeddings=n_users, embedding_dim=embedding_dim\n",
    "        )\n",
    "        self.item_embedding = nn.Embedding(\n",
    "            num_embeddings=n_items, embedding_dim=embedding_dim\n",
    "        )\n",
    "        self.user_bias = nn.Parameter(torch.zeros((n_users)))\n",
    "        self.item_bias = nn.Parameter(torch.zeros((n_items)))\n",
    "        self.bias = nn.Parameter(torch.Tensor([0]))\n",
    "\n",
    "    def forward(self, users, items):\n",
    "        return (\n",
    "                self.bias +\n",
    "                self.user_bias[users] +\n",
    "                self.item_bias[items] +\n",
    "                (self.user_embedding(users).mul(self.item_embedding(items))).sum(dim=-1)\n",
    "        )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "from recohut.utils.common_utils import *\n",
    "from recohut.datasets.bases.commons.interactions import InteractionsDataset, InteractionsDataModule\n",
    "\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "\n",
    "\n",
    "class ML1mDataset(InteractionsDataset):\n",
    "    url = \"http://files.grouplens.org/datasets/movielens/ml-1m.zip\"\n",
    "\n",
    "    @property\n",
    "    def raw_file_names(self):\n",
    "        return 'ratings.dat'\n",
    "\n",
    "    def download(self):\n",
    "        path = download_url(self.url, self.raw_dir)\n",
    "        extract_zip(path, self.raw_dir)\n",
    "        from shutil import move, rmtree\n",
    "        move(os.path.join(self.raw_dir, 'ml-1m', self.raw_file_names), self.raw_dir)\n",
    "        rmtree(os.path.join(self.raw_dir, 'ml-1m'))\n",
    "        os.unlink(path)\n",
    "\n",
    "    def load_ratings_df(self):\n",
    "        df = pd.read_csv(self.raw_paths[0], sep='::', header=None, engine='python')\n",
    "        df.columns = ['uid', 'sid', 'rating', 'timestamp']\n",
    "        # drop duplicate user-item pair records, keeping recent ratings only\n",
    "        df.drop_duplicates(subset=['uid', 'sid'], keep='last', inplace=True)\n",
    "        return df\n",
    "\n",
    "\n",
    "class ML1mDataModule(InteractionsDataModule):\n",
    "    dataset_cls = ML1mDataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Trainer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Args:\n",
    "    def __init__(self):\n",
    "        self.data_dir = '/content/data'\n",
    "        self.min_rating = 4\n",
    "        self.num_negative_samples = 99\n",
    "        self.min_uc = 5\n",
    "        self.min_sc = 5\n",
    "\n",
    "        self.log_dir = '/content/logs'\n",
    "        self.model_dir = '/content/models'\n",
    "\n",
    "        self.val_p = 0.2\n",
    "        self.test_p = 0.2\n",
    "        self.num_workers = 2\n",
    "        self.normalize = False\n",
    "        self.batch_size = 32\n",
    "        self.seed = 42\n",
    "        self.shuffle = True\n",
    "        self.pin_memory = True\n",
    "        self.drop_last = False\n",
    "        self.split_type = 'stratified'\n",
    "\n",
    "        self.embedding_dim = 20\n",
    "        self.max_epochs = 5\n",
    "\n",
    "args = Args()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pytorch_lightning import Trainer\n",
    "from pytorch_lightning.callbacks import ModelCheckpoint\n",
    "from pytorch_lightning.loggers import TensorBoardLogger\n",
    "\n",
    "ds = ML1mDataModule(**args.__dict__)\n",
    "\n",
    "logger = TensorBoardLogger(\n",
    "    save_dir=args.log_dir,\n",
    ")\n",
    "\n",
    "checkpoint_callback = ModelCheckpoint(\n",
    "    monitor=\"valid_loss\",\n",
    "    mode=\"min\",\n",
    "    dirpath=args.model_dir,\n",
    "    filename=\"recommender\",\n",
    ")\n",
    "\n",
    "def pl_trainer(model, datamodule):\n",
    "\n",
    "    trainer = Trainer(\n",
    "    max_epochs=args.max_epochs,\n",
    "    logger=logger,\n",
    "    check_val_every_n_epoch=10,\n",
    "    callbacks=[checkpoint_callback],\n",
    "    gpus=None\n",
    "    )\n",
    "\n",
    "    trainer.fit(model, datamodule=datamodule)\n",
    "    test_result = trainer.test(model, datamodule=datamodule)\n",
    "    return test_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Downloading http://files.grouplens.org/datasets/movielens/ml-1m.zip\n",
      "Extracting /content/data/raw/ml-1m.zip\n",
      "Processing...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Turning into implicit ratings\n",
      "Filtering triplets\n",
      "Densifying index\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Done!\n"
     ]
    }
   ],
   "source": [
    "ds.prepare_data()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "GPU available: False, used: False\n",
      "TPU available: False, using: 0 TPU cores\n",
      "IPU available: False, using: 0 IPUs\n",
      "Missing logger folder: /content/logs/default\n",
      "\n",
      "  | Name           | Type      | Params\n",
      "---------------------------------------------\n",
      "0 | user_embedding | Embedding | 120 K \n",
      "1 | item_embedding | Embedding | 62.5 K\n",
      "---------------------------------------------\n",
      "192 K     Trainable params\n",
      "0         Non-trainable params\n",
      "192 K     Total params\n",
      "0.769     Total estimated model params size (MB)\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "69173e04440842b7a9f527c42f053a89",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Validation sanity check: 0it [00:00, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "ae9feb6b783245ef9a8bea3922668a95",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Training: 0it [00:00, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6d70023f1f424301bd21e6851ae1bad3",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Testing: 0it [00:00, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--------------------------------------------------------------------------------\n",
      "DATALOADER:0 TEST RESULTS\n",
      "{'Test Metrics': {'apak': tensor(0.0213),\n",
      "                  'hr': tensor(0.0810),\n",
      "                  'loss': tensor(0.9917),\n",
      "                  'ncdg': tensor(0.0349)}}\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[{'Test Metrics': {'apak': tensor(0.0213),\n",
       "   'hr': tensor(0.0810),\n",
       "   'loss': tensor(0.9917),\n",
       "   'ncdg': tensor(0.0349)}}]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model = MF(n_items=ds.data.num_items, n_users=ds.data.num_users, embedding_dim=args.embedding_dim)\n",
    "\n",
    "pl_trainer(model, ds)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[01;34m/content/data\u001b[00m\n",
      "├── [ 11M]  \u001b[01;34mprocessed\u001b[00m\n",
      "│   ├── [2.3M]  data_test_neg.pt\n",
      "│   ├── [ 95K]  data_test_pos.pt\n",
      "│   ├── [6.5M]  data_train.pt\n",
      "│   ├── [2.3M]  data_valid_neg.pt\n",
      "│   └── [ 95K]  data_valid_pos.pt\n",
      "└── [ 23M]  \u001b[01;34mraw\u001b[00m\n",
      "    └── [ 23M]  ratings.dat\n",
      "\n",
      "  35M used in 2 directories, 6 files\n"
     ]
    }
   ],
   "source": [
    "# !apt-get -qq install tree\n",
    "!tree -h --du -C \"{args.data_dir}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Author: Sparsh A.\n",
      "\n",
      "Last updated: 2022-01-10 09:09:05\n",
      "\n",
      "recohut          : 0.0.10\n",
      "pytorch_lightning: 1.5.8\n",
      "\n",
      "Compiler    : GCC 7.5.0\n",
      "OS          : Linux\n",
      "Release     : 5.4.144+\n",
      "Machine     : x86_64\n",
      "Processor   : x86_64\n",
      "CPU cores   : 2\n",
      "Architecture: 64bit\n",
      "\n",
      "numpy  : 1.19.5\n",
      "pandas : 1.1.5\n",
      "torch  : 1.10.0+cu111\n",
      "IPython: 5.5.0\n",
      "\n"
     ]
    }
   ],
   "source": [
    "#hide\n",
    "%reload_ext watermark\n",
    "%watermark -a \"Sparsh A.\" -m -iv -u -t -d -p recohut,pytorch_lightning"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
