{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"### Reference: https://www.kaggle.com/code/aerdem4/ai4code-pytorch-distilbert-baseline\n - replaced DistilBert ====>>> Deberta","metadata":{"papermill":{"duration":0.122804,"end_time":"2022-05-12T10:15:14.04297","exception":false,"start_time":"2022-05-12T10:15:13.920166","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:34:01.084660Z","iopub.execute_input":"2022-05-15T05:34:01.085228Z","iopub.status.idle":"2022-05-15T05:34:01.107825Z","shell.execute_reply.started":"2022-05-15T05:34:01.085122Z","shell.execute_reply":"2022-05-15T05:34:01.107184Z"}}},{"cell_type":"code","source":"import json\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nfrom scipy import sparse\nfrom tqdm import tqdm\n%env TOKENIZERS_PARALLELISM=true\npd.options.display.width = 180\npd.options.display.max_colwidth = 120\n\nBERT_PATH = \"../input/deberta-v3-base/deberta-v3-base\"\n\ndata_dir = Path('../input/AI4Code')","metadata":{"execution":{"iopub.status.busy":"2022-05-15T05:39:32.292094Z","iopub.execute_input":"2022-05-15T05:39:32.292409Z","iopub.status.idle":"2022-05-15T05:39:32.299646Z","shell.execute_reply.started":"2022-05-15T05:39:32.292379Z","shell.execute_reply":"2022-05-15T05:39:32.298681Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"NUM_TRAIN = 100\n\n\ndef read_notebook(path):\n    return (\n        pd.read_json(\n            path,\n            dtype={'cell_type': 'category', 'source': 'str'})\n        .assign(id=path.stem)\n        .rename_axis('cell_id')\n    )\n\n\npaths_train = list((data_dir / 'train').glob('*.json'))[:NUM_TRAIN]\nnotebooks_train = [\n    read_notebook(path) for path in tqdm(paths_train, desc='Train NBs')\n]\ndf = (\n    pd.concat(notebooks_train)\n    .set_index('id', append=True)\n    .swaplevel()\n    .sort_index(level='id', sort_remaining=False)\n)\n\ndf","metadata":{"papermill":{"duration":82.291505,"end_time":"2022-05-12T10:16:36.365197","exception":false,"start_time":"2022-05-12T10:15:14.073692","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:32.320710Z","iopub.execute_input":"2022-05-15T05:39:32.321013Z","iopub.status.idle":"2022-05-15T05:39:36.171481Z","shell.execute_reply.started":"2022-05-15T05:39:32.320983Z","shell.execute_reply":"2022-05-15T05:39:36.170650Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get an example notebook\nnb_id = df.index.unique('id')[6]\nprint('Notebook:', nb_id)\n\nprint(\"The disordered notebook:\")\nnb = df.loc[nb_id, :]\ndisplay(nb)\nprint()","metadata":{"papermill":{"duration":0.270693,"end_time":"2022-05-12T10:16:36.882443","exception":false,"start_time":"2022-05-12T10:16:36.61175","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:36.173123Z","iopub.execute_input":"2022-05-15T05:39:36.173537Z","iopub.status.idle":"2022-05-15T05:39:36.191952Z","shell.execute_reply.started":"2022-05-15T05:39:36.173498Z","shell.execute_reply":"2022-05-15T05:39:36.190122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_orders = pd.read_csv(\n    data_dir / 'train_orders.csv',\n    index_col='id',\n    squeeze=True,\n).str.split()  # Split the string representation of cell_ids into a list\n\ndf_orders","metadata":{"papermill":{"duration":2.835076,"end_time":"2022-05-12T10:16:39.9675","exception":false,"start_time":"2022-05-12T10:16:37.132424","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:36.193218Z","iopub.execute_input":"2022-05-15T05:39:36.193552Z","iopub.status.idle":"2022-05-15T05:39:38.828270Z","shell.execute_reply.started":"2022-05-15T05:39:36.193516Z","shell.execute_reply":"2022-05-15T05:39:38.827484Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(df_orders.loc[\"002ba502bdac45\"])","metadata":{"papermill":{"duration":0.257536,"end_time":"2022-05-12T10:16:40.472139","exception":false,"start_time":"2022-05-12T10:16:40.214603","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:38.830556Z","iopub.execute_input":"2022-05-15T05:39:38.830970Z","iopub.status.idle":"2022-05-15T05:39:38.838423Z","shell.execute_reply.started":"2022-05-15T05:39:38.830931Z","shell.execute_reply":"2022-05-15T05:39:38.837678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cell_order = df_orders.loc[nb_id]\n\nprint(\"The ordered notebook:\")\nnb.loc[cell_order, :]","metadata":{"papermill":{"duration":0.265934,"end_time":"2022-05-12T10:16:40.98571","exception":false,"start_time":"2022-05-12T10:16:40.719776","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:38.839848Z","iopub.execute_input":"2022-05-15T05:39:38.840129Z","iopub.status.idle":"2022-05-15T05:39:38.858338Z","shell.execute_reply.started":"2022-05-15T05:39:38.840091Z","shell.execute_reply":"2022-05-15T05:39:38.857541Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_ranks(base, derived):\n    return [base.index(d) for d in derived]\n\ncell_ranks = get_ranks(cell_order, list(nb.index))\nnb.insert(0, 'rank', cell_ranks)\n\nnb","metadata":{"papermill":{"duration":0.265625,"end_time":"2022-05-12T10:16:41.501618","exception":false,"start_time":"2022-05-12T10:16:41.235993","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:38.859860Z","iopub.execute_input":"2022-05-15T05:39:38.860393Z","iopub.status.idle":"2022-05-15T05:39:38.874871Z","shell.execute_reply.started":"2022-05-15T05:39:38.860354Z","shell.execute_reply":"2022-05-15T05:39:38.874194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_orders_ = df_orders.to_frame().join(\n    df.reset_index('cell_id').groupby('id')['cell_id'].apply(list),\n    how='right',\n)\n\nranks = {}\nfor id_, cell_order, cell_id in df_orders_.itertuples():\n    ranks[id_] = {'cell_id': cell_id, 'rank': get_ranks(cell_order, cell_id)}\n\ndf_ranks = (\n    pd.DataFrame\n    .from_dict(ranks, orient='index')\n    .rename_axis('id')\n    .apply(pd.Series.explode)\n    .set_index('cell_id', append=True)\n)\n\ndf_ranks","metadata":{"papermill":{"duration":2.967892,"end_time":"2022-05-12T10:16:44.752979","exception":false,"start_time":"2022-05-12T10:16:41.785087","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:38.876187Z","iopub.execute_input":"2022-05-15T05:39:38.876652Z","iopub.status.idle":"2022-05-15T05:39:38.954567Z","shell.execute_reply.started":"2022-05-15T05:39:38.876586Z","shell.execute_reply":"2022-05-15T05:39:38.953560Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_ancestors = pd.read_csv(data_dir / 'train_ancestors.csv', index_col='id')\ndf_ancestors","metadata":{"papermill":{"duration":0.44203,"end_time":"2022-05-12T10:16:45.446006","exception":false,"start_time":"2022-05-12T10:16:45.003976","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:38.956438Z","iopub.execute_input":"2022-05-15T05:39:38.956758Z","iopub.status.idle":"2022-05-15T05:39:39.158221Z","shell.execute_reply.started":"2022-05-15T05:39:38.956720Z","shell.execute_reply":"2022-05-15T05:39:39.157470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = df.reset_index().merge(df_ranks, on=[\"id\", \"cell_id\"]).merge(df_ancestors, on=[\"id\"])\ndf","metadata":{"papermill":{"duration":1.007951,"end_time":"2022-05-12T10:16:46.70626","exception":false,"start_time":"2022-05-12T10:16:45.698309","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:39.160545Z","iopub.execute_input":"2022-05-15T05:39:39.160821Z","iopub.status.idle":"2022-05-15T05:39:39.223293Z","shell.execute_reply.started":"2022-05-15T05:39:39.160786Z","shell.execute_reply":"2022-05-15T05:39:39.222486Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df[\"pct_rank\"] = df[\"rank\"] / df.groupby(\"id\")[\"cell_id\"].transform(\"count\")\n\ndf[\"pct_rank\"].hist(bins=10)","metadata":{"papermill":{"duration":0.862186,"end_time":"2022-05-12T10:16:47.820945","exception":false,"start_time":"2022-05-12T10:16:46.958759","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:39.226775Z","iopub.execute_input":"2022-05-15T05:39:39.227032Z","iopub.status.idle":"2022-05-15T05:39:39.464294Z","shell.execute_reply.started":"2022-05-15T05:39:39.226999Z","shell.execute_reply":"2022-05-15T05:39:39.463611Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import GroupShuffleSplit\n\nNVALID = 0.1  # size of validation set\n\nsplitter = GroupShuffleSplit(n_splits=1, test_size=NVALID, random_state=0)\n\ntrain_ind, val_ind = next(splitter.split(df, groups=df[\"ancestor_id\"]))\n\ntrain_df = df.loc[train_ind].reset_index(drop=True)\nval_df = df.loc[val_ind].reset_index(drop=True)","metadata":{"papermill":{"duration":1.895199,"end_time":"2022-05-12T10:16:49.969199","exception":false,"start_time":"2022-05-12T10:16:48.074","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:39.465502Z","iopub.execute_input":"2022-05-15T05:39:39.465822Z","iopub.status.idle":"2022-05-15T05:39:40.040534Z","shell.execute_reply.started":"2022-05-15T05:39:39.465782Z","shell.execute_reply":"2022-05-15T05:39:40.039799Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_df.head()","metadata":{"papermill":{"duration":0.27219,"end_time":"2022-05-12T10:16:50.495502","exception":false,"start_time":"2022-05-12T10:16:50.223312","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:40.041946Z","iopub.execute_input":"2022-05-15T05:39:40.042195Z","iopub.status.idle":"2022-05-15T05:39:40.057918Z","shell.execute_reply.started":"2022-05-15T05:39:40.042162Z","shell.execute_reply":"2022-05-15T05:39:40.057218Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from bisect import bisect\n\n\ndef count_inversions(a):\n    inversions = 0\n    sorted_so_far = []\n    for i, u in enumerate(a):\n        j = bisect(sorted_so_far, u)\n        inversions += i - j\n        sorted_so_far.insert(j, u)\n    return inversions\n\n\ndef kendall_tau(ground_truth, predictions):\n    total_inversions = 0\n    total_2max = 0  # twice the maximum possible inversions across all instances\n    for gt, pred in zip(ground_truth, predictions):\n        ranks = [gt.index(x) for x in pred]  # rank predicted order in terms of ground truth\n        total_inversions += count_inversions(ranks)\n        n = len(gt)\n        total_2max += n * (n - 1)\n    return 1 - 4 * total_inversions / total_2max","metadata":{"papermill":{"duration":0.262837,"end_time":"2022-05-12T10:16:51.011588","exception":false,"start_time":"2022-05-12T10:16:50.748751","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:40.061159Z","iopub.execute_input":"2022-05-15T05:39:40.061476Z","iopub.status.idle":"2022-05-15T05:39:40.069110Z","shell.execute_reply.started":"2022-05-15T05:39:40.061451Z","shell.execute_reply":"2022-05-15T05:39:40.068249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_dummy = val_df.groupby('id')['cell_id'].apply(list)\nkendall_tau(df_orders.loc[y_dummy.index], y_dummy)","metadata":{"papermill":{"duration":0.372005,"end_time":"2022-05-12T10:16:51.63863","exception":false,"start_time":"2022-05-12T10:16:51.266625","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:40.070335Z","iopub.execute_input":"2022-05-15T05:39:40.071113Z","iopub.status.idle":"2022-05-15T05:39:40.086970Z","shell.execute_reply.started":"2022-05-15T05:39:40.071075Z","shell.execute_reply":"2022-05-15T05:39:40.086019Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_df[\"cell_type\"].value_counts()","metadata":{"papermill":{"duration":0.27416,"end_time":"2022-05-12T10:16:52.16563","exception":false,"start_time":"2022-05-12T10:16:51.89147","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:40.088894Z","iopub.execute_input":"2022-05-15T05:39:40.089359Z","iopub.status.idle":"2022-05-15T05:39:40.098852Z","shell.execute_reply.started":"2022-05-15T05:39:40.089317Z","shell.execute_reply":"2022-05-15T05:39:40.098055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df_mark = train_df[train_df[\"cell_type\"] == \"markdown\"].reset_index(drop=True)\n\nval_df_mark = val_df[val_df[\"cell_type\"] == \"markdown\"].reset_index(drop=True)","metadata":{"papermill":{"duration":0.371916,"end_time":"2022-05-12T10:16:52.797271","exception":false,"start_time":"2022-05-12T10:16:52.425355","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:40.100284Z","iopub.execute_input":"2022-05-15T05:39:40.101059Z","iopub.status.idle":"2022-05-15T05:39:40.110934Z","shell.execute_reply.started":"2022-05-15T05:39:40.101004Z","shell.execute_reply":"2022-05-15T05:39:40.110169Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import mean_squared_error\n\nmean_squared_error(val_df_mark[\"pct_rank\"], np.ones(val_df_mark.shape[0])*train_df_mark[\"pct_rank\"].mean())","metadata":{"papermill":{"duration":0.280778,"end_time":"2022-05-12T10:16:53.349877","exception":false,"start_time":"2022-05-12T10:16:53.069099","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:40.113233Z","iopub.execute_input":"2022-05-15T05:39:40.113904Z","iopub.status.idle":"2022-05-15T05:39:40.124604Z","shell.execute_reply.started":"2022-05-15T05:39:40.113861Z","shell.execute_reply":"2022-05-15T05:39:40.123788Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tqdm import tqdm\nimport sys, os\nfrom transformers import AutoModel, AutoTokenizer\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport torch\n\nMAX_LEN = 128\n\nclass MarkdownModel(nn.Module):\n    def __init__(self):\n        super(MarkdownModel, self).__init__()\n        self.bert = AutoModel.from_pretrained(BERT_PATH)\n        self.top = nn.Linear(768, 1)\n        \n    def forward(self, ids, mask):\n        x = self.bert(ids, mask)[0]\n        x = self.top(x[:, 0, :])\n        return x","metadata":{"papermill":{"duration":7.145711,"end_time":"2022-05-12T10:17:00.757077","exception":false,"start_time":"2022-05-12T10:16:53.611366","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:40.127067Z","iopub.execute_input":"2022-05-15T05:39:40.127835Z","iopub.status.idle":"2022-05-15T05:39:40.136509Z","shell.execute_reply.started":"2022-05-15T05:39:40.127803Z","shell.execute_reply":"2022-05-15T05:39:40.135758Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from torch.utils.data import DataLoader, Dataset\n\n\n\nclass MarkdownDataset(Dataset):\n    \n    def __init__(self, df, max_len):\n        super().__init__()\n        self.df = df.reset_index(drop=True)\n        self.max_len = max_len\n        self.tokenizer = AutoTokenizer.from_pretrained(BERT_PATH, do_lower_case=True)\n\n    def __getitem__(self, index):\n        row = self.df.iloc[index]\n        \n        inputs = self.tokenizer.encode_plus(\n            row.source,\n            None,\n            add_special_tokens=True,\n            max_length=self.max_len,\n            padding=\"max_length\",\n            return_token_type_ids=True,\n            truncation=True\n        )\n        ids = torch.LongTensor(inputs['input_ids'])\n        mask = torch.LongTensor(inputs['attention_mask'])\n\n        return ids, mask, torch.FloatTensor([row.pct_rank])\n\n    def __len__(self):\n        return self.df.shape[0]\n    \ntrain_ds = MarkdownDataset(train_df_mark, max_len=MAX_LEN)\nval_ds = MarkdownDataset(val_df_mark, max_len=MAX_LEN)\n\nval_ds[0]","metadata":{"papermill":{"duration":0.474499,"end_time":"2022-05-12T10:17:01.487031","exception":false,"start_time":"2022-05-12T10:17:01.012532","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:40.139767Z","iopub.execute_input":"2022-05-15T05:39:40.140281Z","iopub.status.idle":"2022-05-15T05:39:41.910240Z","shell.execute_reply.started":"2022-05-15T05:39:40.140248Z","shell.execute_reply":"2022-05-15T05:39:41.909559Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_df_mark.iloc[0]","metadata":{"papermill":{"duration":0.317331,"end_time":"2022-05-12T10:17:02.061139","exception":false,"start_time":"2022-05-12T10:17:01.743808","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:41.911369Z","iopub.execute_input":"2022-05-15T05:39:41.911766Z","iopub.status.idle":"2022-05-15T05:39:41.920161Z","shell.execute_reply.started":"2022-05-15T05:39:41.911730Z","shell.execute_reply":"2022-05-15T05:39:41.919462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def adjust_lr(optimizer, epoch):\n    if epoch < 3:\n        lr = 3e-5\n    elif epoch < 4:\n        lr = 1e-3\n    elif epoch < 5:\n        lr = 1e-4\n    else:\n        lr = 1e-5\n\n    for p in optimizer.param_groups:\n        p['lr'] = lr\n    return lr\n    \ndef get_optimizer(net):\n    optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, net.parameters()), lr=3e-4, betas=(0.9, 0.999),\n                                 eps=1e-08)\n    return optimizer","metadata":{"papermill":{"duration":0.265988,"end_time":"2022-05-12T10:17:02.580374","exception":false,"start_time":"2022-05-12T10:17:02.314386","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:41.921470Z","iopub.execute_input":"2022-05-15T05:39:41.922236Z","iopub.status.idle":"2022-05-15T05:39:41.930001Z","shell.execute_reply.started":"2022-05-15T05:39:41.922199Z","shell.execute_reply":"2022-05-15T05:39:41.929279Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BS = 32\nNW = 8\n\ntrain_loader = DataLoader(train_ds, batch_size=BS, shuffle=True, num_workers=NW,\n                          pin_memory=False, drop_last=True)\nval_loader = DataLoader(val_ds, batch_size=BS, shuffle=False, num_workers=NW,\n                          pin_memory=False, drop_last=False)","metadata":{"papermill":{"duration":0.298424,"end_time":"2022-05-12T10:17:03.132","exception":false,"start_time":"2022-05-12T10:17:02.833576","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:41.931181Z","iopub.execute_input":"2022-05-15T05:39:41.931738Z","iopub.status.idle":"2022-05-15T05:39:41.941091Z","shell.execute_reply.started":"2022-05-15T05:39:41.931701Z","shell.execute_reply":"2022-05-15T05:39:41.940321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_data(data):\n    return tuple(d.cuda() for d in data[:-1]), data[-1].cuda()\n\n\ndef validate(model, val_loader):\n    model.eval()\n    \n    tbar = tqdm(val_loader, file=sys.stdout)\n    \n    preds = []\n    labels = []\n\n    with torch.no_grad():\n        for idx, data in enumerate(tbar):\n            inputs, target = read_data(data)\n\n            pred = model(inputs[0], inputs[1])\n\n            preds.append(pred.detach().cpu().numpy().ravel())\n            labels.append(target.detach().cpu().numpy().ravel())\n    \n    return np.concatenate(labels), np.concatenate(preds)\n\ndef train(model, train_loader, val_loader, epochs):\n    np.random.seed(42)\n    best_score = 0.\n    optimizer = get_optimizer(model)\n\n    criterion = torch.nn.MSELoss()\n    \n    for e in range(epochs):   \n        model.train()\n        tbar = tqdm(train_loader, file=sys.stdout)\n        \n        lr = adjust_lr(optimizer, e)\n        \n        loss_list = []\n        preds = []\n        labels = []\n\n        for idx, data in enumerate(tbar):\n            inputs, target = read_data(data)\n\n            optimizer.zero_grad()\n            pred = model(inputs[0], inputs[1])\n\n            loss = criterion(pred, target)\n            loss.backward()\n            optimizer.step()\n            \n            loss_list.append(loss.detach().cpu().item())\n            preds.append(pred.detach().cpu().numpy().ravel())\n            labels.append(target.detach().cpu().numpy().ravel())\n            \n            avg_loss = np.round(np.mean(loss_list), 4)\n\n            tbar.set_description(f\"Epoch {e+1} Loss: {avg_loss} lr: {lr}\")\n            \n        y_val, y_pred = validate(model, val_loader)\n        score = np.round(mean_squared_error(y_val, y_pred), 4)\n        print(\"Validation MSE:\", score)\n    return model, y_pred\n\n\nmodel = MarkdownModel()","metadata":{"papermill":{"duration":987.160977,"end_time":"2022-05-12T10:33:30.548236","exception":false,"start_time":"2022-05-12T10:17:03.387259","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:41.942426Z","iopub.execute_input":"2022-05-15T05:39:41.942844Z","iopub.status.idle":"2022-05-15T05:39:48.024749Z","shell.execute_reply.started":"2022-05-15T05:39:41.942807Z","shell.execute_reply":"2022-05-15T05:39:48.024048Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nstate = torch.load(f\"../input/ai4code-deberta-v3-base/model_best.pth\",\n                       map_location=torch.device('cpu'))\nmodel.load_state_dict(state)\nmodel=model.to(device)","metadata":{"execution":{"iopub.status.busy":"2022-05-15T05:39:48.026180Z","iopub.execute_input":"2022-05-15T05:39:48.026444Z","iopub.status.idle":"2022-05-15T05:39:59.122817Z","shell.execute_reply.started":"2022-05-15T05:39:48.026406Z","shell.execute_reply":"2022-05-15T05:39:59.122067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"paths_test = list((data_dir / 'test').glob('*.json'))\nnotebooks_test = [\n    read_notebook(path) for path in tqdm(paths_test, desc='Test NBs')\n]\ntest_df = (\n    pd.concat(notebooks_test)\n    .set_index('id', append=True)\n    .swaplevel()\n    .sort_index(level='id', sort_remaining=False)\n).reset_index()","metadata":{"papermill":{"duration":3.156008,"end_time":"2022-05-12T10:33:49.98707","exception":false,"start_time":"2022-05-12T10:33:46.831062","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:59.124096Z","iopub.execute_input":"2022-05-15T05:39:59.124329Z","iopub.status.idle":"2022-05-15T05:39:59.196073Z","shell.execute_reply.started":"2022-05-15T05:39:59.124297Z","shell.execute_reply":"2022-05-15T05:39:59.194906Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df[\"rank\"] = test_df.groupby([\"id\", \"cell_type\"]).cumcount()\ntest_df[\"pred\"] = test_df.groupby([\"id\", \"cell_type\"])[\"rank\"].rank(pct=True)","metadata":{"papermill":{"duration":3.580422,"end_time":"2022-05-12T10:33:56.648552","exception":false,"start_time":"2022-05-12T10:33:53.06813","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:59.198456Z","iopub.execute_input":"2022-05-15T05:39:59.198941Z","iopub.status.idle":"2022-05-15T05:39:59.212842Z","shell.execute_reply.started":"2022-05-15T05:39:59.198899Z","shell.execute_reply":"2022-05-15T05:39:59.212032Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df[\"pct_rank\"] = 0\ntest_ds = MarkdownDataset(test_df[test_df[\"cell_type\"] == \"markdown\"].reset_index(drop=True), max_len=MAX_LEN)\ntest_loader = DataLoader(test_ds, batch_size=BS, shuffle=False, num_workers=NW,\n                          pin_memory=False, drop_last=False)\n\nlen(test_ds), test_ds[0]","metadata":{"papermill":{"duration":3.130783,"end_time":"2022-05-12T10:34:03.120038","exception":false,"start_time":"2022-05-12T10:33:59.989255","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:59.214301Z","iopub.execute_input":"2022-05-15T05:39:59.214866Z","iopub.status.idle":"2022-05-15T05:39:59.881153Z","shell.execute_reply.started":"2022-05-15T05:39:59.214829Z","shell.execute_reply":"2022-05-15T05:39:59.880455Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"_, y_test = validate(model, test_loader)","metadata":{"papermill":{"duration":4.00212,"end_time":"2022-05-12T10:34:10.223448","exception":false,"start_time":"2022-05-12T10:34:06.221328","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:39:59.884702Z","iopub.execute_input":"2022-05-15T05:39:59.884911Z","iopub.status.idle":"2022-05-15T05:40:01.909415Z","shell.execute_reply.started":"2022-05-15T05:39:59.884887Z","shell.execute_reply":"2022-05-15T05:40:01.908569Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df.loc[test_df[\"cell_type\"] == \"markdown\", \"pred\"] = y_test","metadata":{"papermill":{"duration":3.164567,"end_time":"2022-05-12T10:34:16.415308","exception":false,"start_time":"2022-05-12T10:34:13.250741","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:40:01.911210Z","iopub.execute_input":"2022-05-15T05:40:01.911655Z","iopub.status.idle":"2022-05-15T05:40:01.918271Z","shell.execute_reply.started":"2022-05-15T05:40:01.911599Z","shell.execute_reply":"2022-05-15T05:40:01.917382Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub_df = test_df.sort_values(\"pred\").groupby(\"id\")[\"cell_id\"].apply(lambda x: \" \".join(x)).reset_index()\nsub_df.rename(columns={\"cell_id\": \"cell_order\"}, inplace=True)\nsub_df.head()","metadata":{"papermill":{"duration":3.093752,"end_time":"2022-05-12T10:34:22.827853","exception":false,"start_time":"2022-05-12T10:34:19.734101","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:40:01.919548Z","iopub.execute_input":"2022-05-15T05:40:01.919928Z","iopub.status.idle":"2022-05-15T05:40:01.938726Z","shell.execute_reply.started":"2022-05-15T05:40:01.919889Z","shell.execute_reply":"2022-05-15T05:40:01.937816Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub_df.to_csv(\"submission.csv\", index=False)","metadata":{"papermill":{"duration":3.551878,"end_time":"2022-05-12T10:34:29.528868","exception":false,"start_time":"2022-05-12T10:34:25.97699","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-15T05:40:01.940135Z","iopub.execute_input":"2022-05-15T05:40:01.940730Z","iopub.status.idle":"2022-05-15T05:40:01.950162Z","shell.execute_reply.started":"2022-05-15T05:40:01.940611Z","shell.execute_reply":"2022-05-15T05:40:01.949413Z"},"trusted":true},"execution_count":null,"outputs":[]}]}