{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2d0860b5-8e4e-4596-a81f-be259e188775",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from torch.utils.data import Dataset, DataLoader\n",
    "from transformers import AutoTokenizer, AutoModelForSeq2SeqLM\n",
    "import json\n",
    "import numpy as np\n",
    "from sacrebleu.metrics import BLEU\n",
    "from tqdm import tqdm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "7c22baec-c987-46cd-af6f-5eb594a2b1e4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义参数\n",
    "checkpoint_path = \"./step_137000_valid_bleu_25.55_model_weights.bin\"  # 假设你要加载第2个epoch中的500步的checkpoint\n",
    "data_file = \"./data/translation2019zh/translation2019zh_valid.json\"  # 假设使用验证集来测试\n",
    "model_checkpoint = \"Helsinki-NLP/opus-mt-zh-en\"\n",
    "max_dataset_size = 100\n",
    "max_input_length = 128\n",
    "max_target_length = 128\n",
    "batch_size = 8"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "fff9be9b-57d8-4203-b644-155c76baa1ff",
   "metadata": {},
   "outputs": [],
   "source": [
    "class TRANS(Dataset):\n",
    "    def __init__(self, data_file):\n",
    "        self.data = self.load_data(data_file)\n",
    "    \n",
    "    def load_data(self, data_file):\n",
    "        Data = {}\n",
    "        with open(data_file, 'rt', encoding='utf-8') as f:\n",
    "            for idx, line in enumerate(f):\n",
    "                if idx >= max_dataset_size:\n",
    "                    break\n",
    "                sample = json.loads(line.strip())\n",
    "                Data[idx] = sample\n",
    "        return Data\n",
    "    \n",
    "    def __len__(self):\n",
    "        return len(self.data)\n",
    "\n",
    "    def __getitem__(self, idx):\n",
    "        return self.data[idx]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "3be38090-c1e5-4fb5-b90d-7f18fe8dc23f",
   "metadata": {},
   "outputs": [],
   "source": [
    "def collote_fn(batch_samples):\n",
    "    batch_inputs, batch_targets = [], []\n",
    "    for sample in batch_samples:\n",
    "        batch_inputs.append(sample['chinese'])\n",
    "        batch_targets.append(sample['english'])\n",
    "    batch_data = tokenizer(\n",
    "        batch_inputs, \n",
    "        padding=True, \n",
    "        max_length=max_input_length,\n",
    "        truncation=True, \n",
    "        return_tensors=\"pt\"\n",
    "    )\n",
    "    with tokenizer.as_target_tokenizer():\n",
    "        labels = tokenizer(\n",
    "            batch_targets, \n",
    "            padding=True, \n",
    "            max_length=max_target_length,\n",
    "            truncation=True, \n",
    "            return_tensors=\"pt\"\n",
    "        )[\"input_ids\"]\n",
    "        batch_data['decoder_input_ids'] = model.prepare_decoder_input_ids_from_labels(labels)\n",
    "        end_token_index = torch.where(labels == tokenizer.eos_token_id)[1]\n",
    "        for idx, end_idx in enumerate(end_token_index):\n",
    "            labels[idx][end_idx+1:] = -100\n",
    "        batch_data['labels'] = labels\n",
    "    return batch_data\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "3d5a697a-9b44-4ff3-96df-24a2cb608773",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/25/gdz0c30x3mg1dj9qkwz0ch4w0000gq/T/ipykernel_13528/1590730426.py:6: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
      "  model.load_state_dict(torch.load(checkpoint_path, map_location=\"cpu\"))\n"
     ]
    }
   ],
   "source": [
    "# 加载模型和tokenizer\n",
    "tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)\n",
    "model = AutoModelForSeq2SeqLM.from_pretrained(model_checkpoint)\n",
    "\n",
    "# 加载checkpoint\n",
    "model.load_state_dict(torch.load(checkpoint_path, map_location=\"cpu\"))\n",
    "model.eval()\n",
    "\n",
    "# 将模型转移到设备\n",
    "device = \"cuda\" if torch.cuda.is_available() else \"mps\" if torch.backends.mps.is_available() else \"cpu\"\n",
    "model = model.to(device)\n",
    "\n",
    "# 加载测试数据\n",
    "test_data = TRANS(data_file)\n",
    "test_dataloader = DataLoader(test_data, batch_size=batch_size, shuffle=True, collate_fn=collote_fn)\n",
    "\n",
    "# 定义BLEU评估函数\n",
    "bleu = BLEU()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "6446e3f4-b6e2-4f8a-abc4-6fee7224d517",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "def test_model(dataloader, model):\n",
    "    preds, labels = [], []\n",
    "\n",
    "    model.eval()\n",
    "    for batch_data in tqdm(dataloader):\n",
    "        batch_data = batch_data.to(device)\n",
    "        with torch.no_grad():\n",
    "            generated_tokens = model.generate(\n",
    "                batch_data[\"input_ids\"],\n",
    "                attention_mask=batch_data[\"attention_mask\"],\n",
    "                max_length=max_target_length,\n",
    "            ).cpu().numpy()\n",
    "\n",
    "        label_tokens = batch_data[\"labels\"].cpu().numpy()\n",
    "        \n",
    "\n",
    "        decoded_preds = tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)\n",
    "        label_tokens = np.where(label_tokens != -100, label_tokens, tokenizer.pad_token_id)\n",
    "        decoded_labels = tokenizer.batch_decode(label_tokens, skip_special_tokens=True)\n",
    "\n",
    "        preds += [pred.strip() for pred in decoded_preds]\n",
    "        labels += [[label.strip()] for label in decoded_labels]\n",
    "    \n",
    "    bleu_score = bleu.corpus_score(preds, labels).score\n",
    "    print(f\"BLEU: {bleu_score:>0.2f}\")\n",
    "    return bleu_score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "f196f320-7d8b-44d5-9903-5fdb0532e318",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Testing model...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|███████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:33<00:00,  2.61s/it]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BLEU: 12.95\n",
      "Test BLEU score: 12.95\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "print(\"Testing model...\")\n",
    "bleu_score = test_model(test_dataloader, model)\n",
    "print(f\"Test BLEU score: {bleu_score:0.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96e1d097-93d6-482d-8836-167974de98bc",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
