{"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":"gpu","dataSources":[{"sourceId":121150,"databundleVersionId":15061024,"sourceType":"competition"},{"sourceId":14374989,"sourceType":"datasetVersion","datasetId":9147887},{"sourceId":14376272,"sourceType":"datasetVersion","datasetId":9181082},{"sourceId":14410665,"sourceType":"datasetVersion","datasetId":9203761},{"sourceId":14661932,"sourceType":"datasetVersion","datasetId":9366631},{"sourceId":282751,"sourceType":"modelInstanceVersion","modelInstanceId":239470,"modelId":222398}],"dockerImageVersionId":31236,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"This notebook demonstrates how to ensemble two fine-tuned ByT5 models to improve translation performance.\n\nEnsembling averages the probabilities (logits) from multiple models, which often leads to more robust predictions.","metadata":{}},{"cell_type":"markdown","source":"## 1. Imports and Setup\nImport necessary libraries and set up the environment.","metadata":{}},{"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-02-04T01:05:12.680924Z","iopub.execute_input":"2026-02-04T01:05:12.681294Z","iopub.status.idle":"2026-02-04T01:05:12.686324Z","shell.execute_reply.started":"2026-02-04T01:05:12.681264Z","shell.execute_reply":"2026-02-04T01:05:12.685243Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 2. Model Configuration\nDefine paths to the two fine-tuned ByT5 models.","metadata":{}},{"cell_type":"code","source":"MODEL1_PATH = \"/kaggle/input/final-byt5/byt5-akkadian-optimized-34x\"\nMODEL2_PATH = \"/kaggle/input/byt5-akkadian-model\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-04T01:05:12.688249Z","iopub.execute_input":"2026-02-04T01:05:12.688514Z","iopub.status.idle":"2026-02-04T01:05:12.706666Z","shell.execute_reply.started":"2026-02-04T01:05:12.688489Z","shell.execute_reply":"2026-02-04T01:05:12.705837Z"}},"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-02-04T01:05:12.707822Z","iopub.execute_input":"2026-02-04T01:05:12.708165Z","iopub.status.idle":"2026-02-04T01:05:12.721624Z","shell.execute_reply.started":"2026-02-04T01:05:12.708132Z","shell.execute_reply":"2026-02-04T01:05:12.720720Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"TEST_DATA_PATH = \"/kaggle/input/deep-past-initiative-machine-translation/test.csv\"\nBATCH_SIZE = 16\nMAX_LENGTH = 512\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n# Weighted Ensemble\n# Model 1 has 0.94x performance of Model 2\nw1 = 0.94 / 1.94\nw2 = 1.00 / 1.94\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-02-04T01:05:12.722837Z","iopub.execute_input":"2026-02-04T01:05:12.723858Z","iopub.status.idle":"2026-02-04T01:05:42.620564Z","shell.execute_reply.started":"2026-02-04T01:05:12.723818Z","shell.execute_reply":"2026-02-04T01:05:42.619668Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 3. Dataset Class\nCustom Dataset class to handle Akkadian transliteration inputs.","metadata":{}},{"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-02-04T01:05:42.622729Z","iopub.execute_input":"2026-02-04T01:05:42.623111Z","iopub.status.idle":"2026-02-04T01:05:42.631365Z","shell.execute_reply.started":"2026-02-04T01:05:42.623084Z","shell.execute_reply":"2026-02-04T01:05:42.630392Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 4. Ensemble Inference\nGenerate translations by averaging the logits from both models.\nThis function handles tokenization, inference, and decoding.","metadata":{}},{"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-02-04T01:05:42.632495Z","iopub.execute_input":"2026-02-04T01:05:42.632894Z","iopub.status.idle":"2026-02-04T01:05:49.563135Z","shell.execute_reply.started":"2026-02-04T01:05:42.632858Z","shell.execute_reply":"2026-02-04T01:05:49.562233Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(next(model.parameters()).dtype)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-04T01:05:49.564336Z","iopub.execute_input":"2026-02-04T01:05:49.564618Z","iopub.status.idle":"2026-02-04T01:05:49.569618Z","shell.execute_reply.started":"2026-02-04T01:05:49.564592Z","shell.execute_reply":"2026-02-04T01:05:49.568727Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 5. Submission\nFormat the results and save them to a CSV file for submission.","metadata":{}},{"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-02-04T01:05:49.570617Z","iopub.execute_input":"2026-02-04T01:05:49.571003Z","iopub.status.idle":"2026-02-04T01:05:49.610266Z","shell.execute_reply.started":"2026-02-04T01:05:49.570975Z","shell.execute_reply":"2026-02-04T01:05:49.609349Z"}},"outputs":[],"execution_count":null}]}