{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":121150,"databundleVersionId":15061024,"sourceType":"competition"},{"sourceId":14376272,"sourceType":"datasetVersion","datasetId":9181082},{"sourceId":14410665,"sourceType":"datasetVersion","datasetId":9203761}],"dockerImageVersionId":31236,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport pandas as pd\nimport torch\nfrom torch.utils.data import DataLoader, Dataset\nfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLM\nfrom tqdm.auto import tqdm\nimport re\nimport joblib","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-07T09:07:55.025618Z","iopub.execute_input":"2026-01-07T09:07:55.025913Z","iopub.status.idle":"2026-01-07T09:07:55.029884Z","shell.execute_reply.started":"2026-01-07T09:07:55.025893Z","shell.execute_reply":"2026-01-07T09:07:55.029181Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"MODEL1_PATH = \"/kaggle/input/byt5-base-big-data2\"\nMODEL2_PATH = \"/kaggle/input/byt5-akkadian-model\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-07T09:07:55.030966Z","iopub.execute_input":"2026-01-07T09:07:55.031219Z","iopub.status.idle":"2026-01-07T09:07:55.043807Z","shell.execute_reply.started":"2026-01-07T09:07:55.03118Z","shell.execute_reply":"2026-01-07T09:07:55.04317Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def replace_gaps(text):\n    if pd.isna(text): \n        return text\n    \n    text = re.sub(r'\\.3(?:\\s+\\.3)+\\.{3}(?:\\s+\\.{3})+\\s+\\.{3}(?:\\s+\\.{3})+', '<big_gap>', text)\n    text = re.sub(r'\\.3(?:\\s+\\.3)+\\.{3}(?:\\s+\\.{3})+', '<big_gap>', text)\n    text = re.sub(r'\\.{3}(?:\\s+\\.{3})+', '<big_gap>', text)\n\n    text = re.sub(r'xx', '<gap>', text)\n    text = re.sub(r' x ', ' <gap> ', text)\n    text = re.sub(r'……', '<big_gap>', text)\n    text = re.sub(r'\\.\\.\\.\\.\\.\\.', '<big_gap>', text)\n    text = re.sub(r'…', '<big_gap>', text)\n    text = re.sub(r'\\.\\.\\.', '<big_gap>', text)\n\n    return text\n\ndef replace_gaps_back(text):\n    if pd.isna(text):  \n        return text\n    \n    text = re.sub(r'<gap>', 'x', text)\n    text = re.sub(r'<big_gap>', '...', text)\n\n    return text","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-07T09:07:55.044462Z","iopub.execute_input":"2026-01-07T09:07:55.044897Z","iopub.status.idle":"2026-01-07T09:07:55.060083Z","shell.execute_reply.started":"2026-01-07T09:07:55.044874Z","shell.execute_reply":"2026-01-07T09:07:55.059415Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"TEST_DATA_PATH = \"/kaggle/input/deep-past-initiative-machine-translation/test.csv\"\nBATCH_SIZE = 8\nMAX_LENGTH = 512\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n# Weighted Ensemble\n# Model 1 has 0.98x performance of Model 2\nw1 = 0.98 / 1.98\nw2 = 1.00 / 1.98\n\nprint(\"Loading Model 1...\")\nmodel1 = AutoModelForSeq2SeqLM.from_pretrained(MODEL1_PATH)\nsd1 = model1.state_dict()\n\nprint(\"Loading Model 2...\")\nmodel2 = AutoModelForSeq2SeqLM.from_pretrained(MODEL2_PATH)\nsd2 = model2.state_dict()\n\nprint(\"Averaging weights...\")\nfor key in sd1:\n    sd2[key] = w1 * sd1[key] + w2 * sd2[key]\n\nmodel = model2\nmodel.load_state_dict(sd2)\nmodel = model.to(DEVICE)\nmodel.eval()\n\ntokenizer = AutoTokenizer.from_pretrained(MODEL2_PATH)\n\ntest_df = pd.read_csv(TEST_DATA_PATH)\ntest_df['transliteration'] = test_df['transliteration'].apply(replace_gaps)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-07T09:07:55.094966Z","iopub.execute_input":"2026-01-07T09:07:55.095401Z","iopub.status.idle":"2026-01-07T09:07:59.627772Z","shell.execute_reply.started":"2026-01-07T09:07:55.095384Z","shell.execute_reply":"2026-01-07T09:07:59.626976Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"PREFIX = \"translate Akkadian to English: \"\n\nclass InferenceDataset(Dataset):\n    def __init__(self, df, tokenizer):\n        self.texts = df['transliteration'].astype(str).tolist()\n        self.texts = [PREFIX + i for i in self.texts]\n        self.tokenizer = tokenizer\n        \n    def __len__(self):\n        return len(self.texts)\n    \n    def __getitem__(self, idx):\n        text = self.texts[idx]\n        inputs = self.tokenizer(\n            text, \n            max_length=MAX_LENGTH, \n            padding=\"max_length\", \n            truncation=True, \n            return_tensors=\"pt\"\n        )\n        return {\n            \"input_ids\": inputs[\"input_ids\"].squeeze(0),\n            \"attention_mask\": inputs[\"attention_mask\"].squeeze(0)\n        }\n\ntest_dataset = InferenceDataset(test_df, tokenizer)\ntest_loader = DataLoader(test_dataset, batch_size=BATCH_SIZE, shuffle=False)\n\nprint(\"Starting Inference...\")\nall_predictions = []","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-07T09:07:59.628943Z","iopub.execute_input":"2026-01-07T09:07:59.629247Z","iopub.status.idle":"2026-01-07T09:07:59.636651Z","shell.execute_reply.started":"2026-01-07T09:07:59.62922Z","shell.execute_reply":"2026-01-07T09:07:59.636059Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nfrom tqdm import tqdm\n\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nmodel = model.to(DEVICE)\nmodel.eval()\nmodel.float()\n\nall_predictions = []\n\ntorch.set_grad_enabled(False)\n\nwith torch.inference_mode():\n    for batch in tqdm(test_loader):\n        input_ids = batch[\"input_ids\"].to(DEVICE)              # int64, normal\n        attention_mask = batch[\"attention_mask\"].to(DEVICE)    # int64/bool, normal\n\n        outputs = model.generate(\n            input_ids=input_ids,\n            attention_mask=attention_mask,\n            max_length=MAX_LENGTH,\n            num_beams=4,\n            early_stopping=True,\n        )\n\n        decoded = tokenizer.batch_decode(outputs, skip_special_tokens=True)\n        all_predictions.extend([d.strip() for d in decoded])\n        \n        predictions = []\n        for txt in all_predictions:\n            predictions.append(txt)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-07T09:07:59.637416Z","iopub.execute_input":"2026-01-07T09:07:59.637663Z","iopub.status.idle":"2026-01-07T09:08:04.148098Z","shell.execute_reply.started":"2026-01-07T09:07:59.637648Z","shell.execute_reply":"2026-01-07T09:08:04.147536Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(next(model.parameters()).dtype)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-07T09:08:04.148751Z","iopub.execute_input":"2026-01-07T09:08:04.148929Z","iopub.status.idle":"2026-01-07T09:08:04.152771Z","shell.execute_reply.started":"2026-01-07T09:08:04.148913Z","shell.execute_reply":"2026-01-07T09:08:04.152082Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission = pd.DataFrame({\n    \"id\": test_df[\"id\"],\n    \"translation\": predictions\n})\n\nsubmission[\"translation\"] = submission[\"translation\"].apply(lambda x: x if len(x) > 0 else \"broken text\")\n\n    \nsubmission.to_csv(\"submission.csv\", index=False)\nprint(\"Submission file saved successfully!\")\nsubmission.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-07T09:08:04.154273Z","iopub.execute_input":"2026-01-07T09:08:04.154604Z","iopub.status.idle":"2026-01-07T09:08:04.173497Z","shell.execute_reply.started":"2026-01-07T09:08:04.154583Z","shell.execute_reply":"2026-01-07T09:08:04.172665Z"}},"outputs":[],"execution_count":null}]}