{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":121150,"databundleVersionId":15061024,"sourceType":"competition"},{"sourceId":14410665,"sourceType":"datasetVersion","datasetId":9203761},{"sourceId":14376272,"sourceType":"datasetVersion","datasetId":9181082}],"dockerImageVersionId":31234,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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-17T15:19:25.614044Z","iopub.execute_input":"2026-01-17T15:19:25.614589Z","iopub.status.idle":"2026-01-17T15:19:25.620439Z","shell.execute_reply.started":"2026-01-17T15:19:25.614517Z","shell.execute_reply":"2026-01-17T15:19:25.619496Z"}},"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-17T15:19:25.622377Z","iopub.execute_input":"2026-01-17T15:19:25.622834Z","iopub.status.idle":"2026-01-17T15:19:25.645460Z","shell.execute_reply.started":"2026-01-17T15:19:25.622804Z","shell.execute_reply":"2026-01-17T15:19:25.644367Z"}},"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-17T15:19:25.646840Z","iopub.execute_input":"2026-01-17T15:19:25.647187Z","iopub.status.idle":"2026-01-17T15:19:25.923013Z","shell.execute_reply.started":"2026-01-17T15:19:25.647158Z","shell.execute_reply":"2026-01-17T15:19:25.922061Z"}},"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-17T15:19:25.924857Z","iopub.execute_input":"2026-01-17T15:19:25.925149Z","iopub.status.idle":"2026-01-17T15:19:33.062017Z","shell.execute_reply.started":"2026-01-17T15:19:25.925122Z","shell.execute_reply":"2026-01-17T15:19:33.060759Z"}},"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-17T15:19:33.064735Z","iopub.execute_input":"2026-01-17T15:19:33.065888Z","iopub.status.idle":"2026-01-17T15:19:33.081138Z","shell.execute_reply.started":"2026-01-17T15:19:33.065815Z","shell.execute_reply":"2026-01-17T15:19:33.079670Z"}},"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-17T15:19:33.082501Z","iopub.execute_input":"2026-01-17T15:19:33.083131Z","iopub.status.idle":"2026-01-17T15:21:22.569734Z","shell.execute_reply.started":"2026-01-17T15:19:33.083088Z","shell.execute_reply":"2026-01-17T15:21:22.568336Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(next(model.parameters()).dtype)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-17T15:21:22.571588Z","iopub.execute_input":"2026-01-17T15:21:22.572033Z","iopub.status.idle":"2026-01-17T15:21:22.581594Z","shell.execute_reply.started":"2026-01-17T15:21:22.571991Z","shell.execute_reply":"2026-01-17T15:21:22.580668Z"}},"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-17T15:21:22.582923Z","iopub.execute_input":"2026-01-17T15:21:22.583239Z","iopub.status.idle":"2026-01-17T15:21:22.641834Z","shell.execute_reply.started":"2026-01-17T15:21:22.583212Z","shell.execute_reply":"2026-01-17T15:21:22.640833Z"}},"outputs":[],"execution_count":null}]}