{"cells":[{"metadata":{},"cell_type":"markdown","source":"### Example for implement SAINT model. \n\nI will show all the code of SAINT+ after the end of competition.\nIt's a long journey for us. Hope we can got good result in the last day.\n\nIn my history,\nI got the score as follows:\n\n1. SAKT　 LB 0.776 \n2. SAINT　LB 0.784 \n3. SAINT+ like LB 0.799\n\nThe code is modified from great notebook:\nhttps://www.kaggle.com/manikanthr5/riiid-sakt-model-training-public\n\nIf you haven't tried the SAINT model, you can try it in last day. Maybe it will be helpful."},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","collapsed":true,"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":false},"cell_type":"code","source":"import psutil\nimport joblib\nimport random\nfrom tqdm import tqdm\n\nimport numpy as np\nimport gc\nimport pandas as pd\nimport time\n\nfrom sklearn.metrics import roc_auc_score\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"MAX_SEQ = 100\nD_MODEL = 256\nN_LAYER = 4\nBATCH_SIZE = 256","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## SAINT model implementation"},{"metadata":{"trusted":true},"cell_type":"code","source":"class FFN(nn.Module):\n    def __init__(self, state_size=200):\n        super(FFN, self).__init__()\n        self.state_size = state_size\n\n        self.lr1 = nn.Linear(state_size, state_size)\n        self.relu = nn.ReLU()\n        self.lr2 = nn.Linear(state_size, state_size)\n        self.dropout = nn.Dropout(0.1)\n    \n    def forward(self, x):\n        x = self.lr1(x)\n        x = self.relu(x)\n        x = self.lr2(x)\n        return self.dropout(x)\n\ndef future_mask(seq_length):\n    future_mask = np.triu(np.ones((seq_length, seq_length)), k=1).astype('bool')\n    return torch.from_numpy(future_mask)\n\n\nclass SAINTModel(nn.Module):\n    def __init__(self, n_skill, n_part, max_seq=MAX_SEQ, embed_dim= 128):\n        super(SAINTModel, self).__init__()\n\n        self.n_skill = n_skill\n        self.embed_dim = embed_dim\n        self.n_cat = n_part\n\n        self.e_embedding = nn.Embedding(self.n_skill+1, embed_dim) ##exercise\n        self.c_embedding = nn.Embedding(self.n_cat+1, embed_dim) ##category\n        self.pos_embedding = nn.Embedding(max_seq-1, embed_dim) ## position\n        self.res_embedding = nn.Embedding(2, embed_dim) ## response\n\n        self.transformer = nn.Transformer(nhead=8, d_model = embed_dim, num_encoder_layers= N_LAYER, num_decoder_layers= N_LAYER, dropout = 0.1)\n\n        self.dropout = nn.Dropout(0.1)\n        self.layer_normal = nn.LayerNorm(embed_dim) \n        self.ffn = FFN(embed_dim)\n        self.pred = nn.Linear(embed_dim, 1)\n    \n    def forward(self, question, part, response):\n\n        device = question.device  \n\n        question = self.e_embedding(question)\n        part = self.c_embedding(part)\n        pos_id = torch.arange(question.size(1)).unsqueeze(0).to(device)\n        pos_id = self.pos_embedding(pos_id)\n        res = self.res_embedding(response)\n\n        enc = question + part + pos_id\n        dec = pos_id + res\n\n\n        enc = enc.permute(1, 0, 2) # x: [bs, s_len, embed] => [s_len, bs, embed]\n        dec = dec.permute(1, 0, 2)\n        mask = future_mask(enc.size(0)).to(device)\n\n        att_output = self.transformer(enc, dec, src_mask=mask, tgt_mask=mask)\n        att_output = self.layer_normal(att_output)\n        att_output = att_output.permute(1, 0, 2) # att_output: [s_len, bs, embed] => [bs, s_len, embed]\n\n        x = self.ffn(att_output)\n        x = self.layer_normal(x + att_output)\n        x = self.pred(x)\n\n        return x.squeeze(-1)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}