[ { "paper_id": 0, "paper_details": { "title": "From Zero to Hero: Cold-Start Anomaly Detection", "url": "https://arxiv.org/pdf/2405.20341" }, "repo_original_url": "https://github.com/talreiss/ColdFusion", "project_path": "Benchmark/0-coldfusion/ColdFusion-main", "enviorment_name": "ColdFusion", "file_organization": "\nColdFusion-main/\n coldfusion.py\n data/\n BANKING77-OOS/\n id-oos/\n test/\n label\n label_original\n seq.in\n train/\n label\n label_original\n seq.in\n valid/\n label\n label_original\n seq.in\n ood-oos/\n test/\n label\n seq.in\n valid/\n label\n seq.in\n test/\n label\n seq.in\n train/\n label\n seq.in\n valid/\n label\n seq.in\n CLINC-Single-Domain-OOS/\n banking/\n id-oos/\n test/\n label\n label_original\n seq.in\n valid/\n label\n seq.in\n ood-oos/\n test/\n label\n seq.in\n valid/\n label\n seq.in\n test/\n label\n seq.in\n train/\n label\n seq.in\n valid/\n label\n seq.in\n credit_cards/\n id-oos/\n test/\n label\n label_original\n seq.in\n valid/\n label\n seq.in\n ood-oos/\n test/\n label\n seq.in\n valid/\n label\n seq.in\n test/\n label\n seq.in\n train/\n label\n seq.in\n valid/\n label\n seq.in\n enviornment.sh\n extract_features.py\n features/\n banking77/\n gte/\n clinc_banking/\n gte/\n id-oos-test.npy\n id-oos-valid.npy\n test.npy\n train.npy\n README.md\n requirements.txt\n\n", "latex_code_path": "Benchmark/0-coldfusion/From_Zero_to_Hero_Cold-Start_Anomaly_Detection", "task_details": [ { "task_id": 0, "indent": 1, "script": "\npython coldfusion.py --dataset clinc_banking\n", "completion_path": "./coldfusion.py", "latex_code": "\n\\textbf{Assignment.} We assign each of the $t$ observations to the nearest class as measured in the feature space $\\phi$. We denote the class assignment of observation $x$ as $a(x)$. More formally:\n\\vspace{-0.25em}\n\\begin{equation}\n a(x) = \\arg\\min_k \\{d(\\phi(x),\\phi(c_k))\\}_{k=1}^K\n \\vspace{-0.25em}\n\\end{equation}\n", "namespace": "coldfusion.assign_observations_to_classes", "type": "function", "signature_position": [ 176, 176 ], "body_position": [ 177, 181 ], "test_case_code": { "insert_pos": -1, "indent": 1, "code": "\nimport pickle, os\noutputDirTask = 'SavedOutputRun/task1'\ntask = I\nif os.path.exists(outputDirTask) == False:\n os.makedirs(outputDirTask)\nfiles = [f for f in os.listdir(outputDirTask) if os.path.isfile(os.path.join(outputDirTask, f))]\nnum_file = len(files)\nif num_file < 10:\n id = num_file\n if os.path.exists(outputDirTask) == False:\n os.makedirs(outputDirTask)\n filepathTask = os.path.join(outputDirTask, 'output_' + str(id) + '.pickle')\n with open(filepathTask, 'wb') as f:\n pickle.dump(task, f)\n" }, "Description": "\nDescription: \n Assigns each observation in the training set to the nearest class in the feature space, aligning with Equation (1) from the LaTeX snippet: \\( a(x) = \\arg\\min_{k} \\{ d(\\phi(x), \\phi(c_k))\\}_{k=1}^K \\). This implements the assignment function \\( a(\\cdot) \\) by finding the class with minimal distance to each observation in cur_trainset.\n", "ReferenceCode_With_Comments": "\nindex = faiss.IndexFlatL2(cur_trainset.shape[1])\nindex.add(in_scope_topic_features)\n\n# ---------------------------------------------------------------------------\n# Snippet 1: For every observation in cur_trainset, search for the single\n# nearest class vector (k=1) based on their Euclidean distances. The returned I array gives the index of the\n# closest class feature (i.e., \\(\\arg\\min_k d(\\phi(x), \\phi(c_k))\\)).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\n_, I = index.search(cur_trainset, 1)\nI = I[:, 0]\n# [End Snippet 1]\n\nreturn I\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The function adopt L2 norm for calculating the Euclidean distance between the feature vectors.\n\n Mismatched Details:\n - None\n", "Missing_details": [ "\n- The function adopt L2 norm for calculating the Euclidean distance between the feature vectors.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - cur_trainset (ndarray, shape=[num_observations, num_features]): \n Represents the feature vectors of the current training observations.\n - in_scope_topic_features (ndarray, shape=[num_classes, num_features]): \n Represents the class feature vectors (e.g., centroids or some representative embeddings.\n", "Arguments_list": [ { "name": "cur_trainset", "string": "\n- cur_trainset (ndarray, shape=[num_observations, num_features]): \n Represents the feature vectors of the current training observations.\n", "dependency": null }, { "name": "in_scope_topic_features", "string": "\n- in_scope_topic_features (ndarray, shape=[num_classes, num_features]): \n Represents the class feature vectors (e.g., centroids or some representative embeddings.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra File Dependencies: \n - None\n \n Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - faiss.IndexFlatL2\n", "list": [ "faiss.IndexFlatL2" ] }, "Return": { "Return_String": "\nOutput Variables:\n - I (ndarray, shape=[num_observations]): \n A one-dimensional array of indices indicating, for each observation in cur_trainset, which class \n in_scope_topic_features it was assigned to (i.e., the result of \\(\\arg\\min_k d(\\phi(x), \\phi(c_k))\\)).\n", "Return_list": [ { "name": "I", "string": "\n- I (ndarray, shape=[num_observations]): \n A one-dimensional array of indices indicating, for each observation in cur_trainset, which class \n in_scope_topic_features it was assigned to (i.e., the result of \\(\\arg\\min_k d(\\phi(x), \\phi(c_k))\\)).\n", "dependency": null } ] }, "ori_python_file": "import torch\nfrom torch import Tensor\nfrom transformers import AutoTokenizer, AutoModel\nfrom tqdm import tqdm\nfrom sklearn.metrics import roc_auc_score\nimport faiss\nimport numpy as np\nimport argparse\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nimport seaborn as sns\nimport os, pickle, shutil\nimport pickle\n\ndef average_pool(last_hidden_states: Tensor, attention_mask: Tensor) -> Tensor:\n last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0)\n return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]\n\ndef mean_pooling(model_output, attention_mask):\n token_embeddings = model_output[0]\n input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()\n return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)\n\ndef get_model(model_name):\n if model_name == 'mpnet':\n tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-mpnet-base-v2')\n model = AutoModel.from_pretrained('sentence-transformers/all-mpnet-base-v2')\n elif model_name == 'gte':\n tokenizer = AutoTokenizer.from_pretrained(\"thenlper/gte-large\")\n model = AutoModel.from_pretrained(\"thenlper/gte-large\")\n else:\n raise ValueError(f\"Unknown model: {model_name}\")\n return model, tokenizer\n\ndef get_in_scope_queries(dataset):\n if dataset == 'banking77':\n queries = {\n 'activate my card': 'How can I activate my new card?',\n 'age limit': 'Is there an age limit to open a bank account with your service?',\n 'apple pay or google pay': 'Do you support Apple Pay or Google Pay for transactions?',\n 'atm support': 'Which ATMs can I use for withdrawals with your bank card?',\n 'automatic top up': 'How can I set up automatic top-up for my account?',\n 'balance not updated after bank transfer': 'My balance hasn\u2019t updated after a bank transfer. What should I do?',\n 'balance not updated after cheque or cash deposit': 'I deposited a cheque/cash, but my balance hasn\u2019t updated. Why?',\n 'beneficiary not allowed': 'Why am I unable to add a particular beneficiary to my account?',\n 'cancel transfer': 'Can I cancel a transfer I initiated recently?',\n 'card about to expire': 'How can I check when my card is about to expire?',\n 'card acceptance': 'Which merchants or services accept your bank cards?',\n 'card arrival': 'When can I expect the arrival of my new bank card?',\n 'card delivery estimate': 'What is the estimated delivery time for a new bank card?',\n 'card linking': 'How do I link my card to other accounts or services?',\n 'card not working': 'My card is not working. What troubleshooting steps should I follow?',\n 'card payment fee charged': 'Why was I charged a fee for a card payment?',\n 'card payment not recognised': 'I made a card payment, but it\\'s not recognized in my account. What should I do?',\n 'card payment wrong exchange rate': 'I noticed a wrong exchange rate for a recent card payment. How can I address this?',\n 'card swallowed': 'My card got swallowed by an ATM. What should I do now?',\n 'cash withdrawal charge': 'Is there a charge for cash withdrawals using your bank card?',\n 'cash withdrawal not recognised': 'I withdrew cash, but the transaction is not recognized in my account. What\\'s the issue?',\n 'change pin': 'How can I change the PIN for my bank card?',\n 'compromised card': 'I suspect my card details are compromised. What should I do to secure my account?',\n 'contactless not working': 'My contactless payment is not working. How can I fix this issue?',\n 'country support': 'Which countries does your bank service support?',\n 'declined card payment': 'My card payment was declined. What could be the reasons for this?',\n 'declined cash withdrawal': 'Why was my cash withdrawal declined at the ATM?',\n 'declined transfer': 'A transfer I attempted was declined. What steps should I take?',\n 'direct debit payment not recognised': 'I have a direct debit payment not recognized in my account. What\\'s the reason?',\n 'disposable card limits': 'What are the limits for transactions with disposable virtual cards?',\n 'edit personal details': 'How can I edit or update my personal details on the account?',\n 'exchange charge': 'Is there a charge for currency exchange using your bank card?',\n 'exchange rate': 'How can I check the current exchange rates for currencies?',\n 'exchange via app': 'Can I perform currency exchange directly through the mobile app?',\n 'extra charge on statement': 'I noticed an extra charge on my statement. Can you explain this?',\n 'failed transfer': 'A transfer I initiated has failed. What could be the reasons?',\n 'fiat currency support': 'Which fiat currencies are supported by your bank?',\n 'get disposable virtual card': 'How can I obtain a disposable virtual card?',\n 'get physical card': 'What is the process for obtaining a physical bank card?',\n 'getting spare card': 'Can I get a spare or backup bank card?',\n 'getting virtual card': 'How can I get a virtual bank card?',\n 'lost or stolen card': 'My card is lost or stolen. What immediate steps should I take?',\n 'lost or stolen phone': 'If I lose my phone, how can I secure my bank account?',\n 'order physical card': 'How can I order a new physical bank card?',\n 'passcode forgotten': 'I forgot my passcode. How can I recover or reset it?',\n 'pending card payment': 'Why is a card payment showing as pending in my account?',\n 'pending cash withdrawal': 'I have a pending cash withdrawal. When will it be processed?',\n 'pending top up': 'My top-up is pending. When will it reflect in my account balance?',\n 'pending transfer': 'How long does it take for a transfer to move from pending to completed status?',\n 'pin blocked': 'My PIN got blocked. How can I unblock it?',\n 'receiving money': 'How can I receive money into my account?',\n 'Refund not showing up': 'I initiated a refund, but it\\'s not showing up in my account. What should I do?',\n 'request refund': 'How can I request a refund for a transaction?',\n 'reverted card payment?': 'A card payment was reverted. What could be the reason for this?',\n 'supported cards and currencies': 'Which types of cards and currencies does your bank support?',\n 'terminate account': 'What is the process for terminating or closing my bank account?',\n 'top up by bank transfer charge': 'Is there a charge for topping up my account via bank transfer?',\n 'top up by card charge': 'Are there any charges for topping up my account using a bank card?',\n 'top up by cash or cheque': 'Can I top up my account using cash or a cheque?',\n 'top up failed': 'My top-up attempt failed. What could be the reasons for this?',\n 'top up limits': 'Are there any limits on the amount I can top up into my account?',\n 'top up reverted': 'Why was my top-up amount reverted? What should I do?',\n 'topping up by card': 'How can I top up my account using a bank card?',\n 'transaction charged twice': 'I noticed a transaction charged twice. How can I rectify this?',\n 'transfer fee charged': 'Why was I charged a fee for a transfer?',\n 'transfer into account': 'How can I transfer funds into my account from another bank?',\n 'transfer not received by recipient': 'The recipient didn\u2019t receive the funds I transferred. What should I do?',\n 'transfer timing': 'What are the processing times for fund transfers?',\n 'unable to verify identity': 'I am unable to verify my identity. What should I do?',\n 'verify my identity': 'How can I verify my identity with your bank?',\n 'verify source of funds': 'Why do I need to verify the source of funds in my account?',\n 'verify top up': 'Why do I need to verify my top-up transactions?',\n 'virtual card not working': 'My virtual card is not working. What steps should I take?',\n 'visa or mastercard': 'Do you issue Visa or Mastercard for your bank cards?',\n 'why verify identity': 'Why is identity verification necessary for using your bank services?',\n 'wrong amount of cash received': 'I received the wrong amount of cash after a withdrawal. How can this be corrected?',\n 'wrong exchange rate for cash withdrawal': 'The exchange rate for my recent cash withdrawal seems incorrect. What should I do?'\n }\n elif dataset == 'clinc_banking':\n queries = {\n 'transactions': \"Can you provide a list of my recent transactions?\",\n 'report_fraud': \"I suspect fraudulent activity on my account, how can I report it?\",\n 'routing': \"What is the bank's routing number for wire transfers?\",\n 'interest_rate': \"What is the current interest rate on savings accounts?\",\n 'bill_balance': \"What is the outstanding balance on my credit card bill?\",\n 'order_checks': \"How can I order a new set of checks for my checking account?\",\n 'pin_change': \"I need to change my PIN, how can I do that?\",\n 'pay_bill': \"How do I set up automatic bill payments from my account?\",\n 'spending_history': \"Can you provide a summary of my spending history for the last month?\",\n 'account_blocked': \"Why is my account blocked, and how can I resolve this issue?\"\n }\n elif dataset == 'clinc_credit_cards':\n queries = {\n 'expiration_date': \"Can you remind me of my credit card's expiration date?\",\n 'apr': \"What is the current APR on my credit card?\",\n 'new_card': \"How can I apply for a new credit card?\",\n 'redeem_rewards': \"What are the options to redeem my credit card rewards?\",\n 'credit_score': \"Could you provide information about my current credit score?\",\n 'card_declined': \"Why was my credit card declined during the recent transaction?\",\n 'damaged_card': \"My credit card got damaged, what should I do to get a replacement?\",\n 'credit_limit_change': \"Can I request a change in my credit card's limit?\",\n 'international_fees': \"What are the international transaction fees on my credit card?\",\n 'credit_limit': \"What is my current credit card limit?\"\n }\n else:\n raise ValueError(f\"Unknown dataset: {dataset}\")\n for key, value in queries.items():\n queries[key] = [value]\n return queries\n\ndef encode_queries(queries, model, tokenizer, model_name):\n in_scope_topic_features = []\n with torch.no_grad():\n for key, value in tqdm(queries.items(), total=len(queries)):\n if model_name == 'gte':\n batch_dict = tokenizer(queries[key], max_length=512, padding=True, truncation=True, return_tensors='pt')\n outputs = model(**batch_dict)\n cur_occ = average_pool(outputs.last_hidden_state,\n batch_dict['attention_mask']).contiguous().cpu().numpy()\n else:\n batch_dict = tokenizer(queries[key], padding=True, truncation=True, return_tensors='pt')\n outputs = model(**batch_dict)\n cur_occ = mean_pooling(outputs, batch_dict['attention_mask'])\n in_scope_topic_features.append(cur_occ)\n in_scope_topic_features = np.array(in_scope_topic_features)\n return in_scope_topic_features\n\ndef prepare_class_assignments(I, cur_trainset, in_scope_topic_features):\n each_class_assignments = []\n for q in range(len(in_scope_topic_features)):\n each_class_assignments.append([in_scope_topic_features[q][None]])\n for q in range(len(I)):\n each_class_assignments[I[q]].append(cur_trainset[q][None])\n for q in range(len(in_scope_topic_features)):\n each_class_assignments[q] = np.median(each_class_assignments[q], axis=0)\n adapted_class_embeddings = np.concatenate(each_class_assignments, axis=0)\n return adapted_class_embeddings\n\ndef assign_observations_to_classes(cur_trainset, in_scope_topic_features):\n index = faiss.IndexFlatL2(cur_trainset.shape[1])\n index.add(in_scope_topic_features)\n _, I = index.search(cur_trainset, 1)\n I = I[:, 0]\n return I\n\ndef calculate_auroc_scores(testset, labels, cur_trainset, in_scope_topic_features, adapted_class_embeddings):\n k = 1\n index = faiss.IndexFlatL2(cur_trainset.shape[1])\n index.add(in_scope_topic_features)\n D, _ = index.search(testset, k)\n distances_zero = np.mean(D, axis=1)\n auc_zero = roc_auc_score(labels, distances_zero)\n index = faiss.IndexFlatL2(cur_trainset.shape[1])\n index.add(cur_trainset)\n D, _ = index.search(testset, k)\n distances = np.mean(D, axis=1)\n auc_dn2 = roc_auc_score(labels, distances)\n index = faiss.IndexFlatL2(cur_trainset.shape[1])\n index.add(adapted_class_embeddings)\n D, _ = index.search(testset, k)\n distances_coldfusion = np.mean(D, axis=1)\n auc_coldfusion = roc_auc_score(labels, distances_coldfusion)\n return auc_zero, auc_dn2, auc_coldfusion\n\ndef main(args):\n np.random.seed(0)\n model_name = args.model\n dataset = args.dataset\n train_normal = np.load(f'./features/{dataset}/{model_name}/train.npy')\n train_id_oos = np.load(f'./features/{dataset}/{model_name}/id-oos-valid.npy')\n test_normal = np.load(f'./features/{dataset}/{model_name}/test.npy')\n test_id_oos = np.load(f'./features/{dataset}/{model_name}/id-oos-test.npy')\n model, tokenizer = get_model(model_name)\n queries = get_in_scope_queries(dataset)\n in_scope_topic_features = encode_queries(queries, model, tokenizer, model_name)\n anom_prec = args.anom_prec\n number_of_in_scope_topics = len(in_scope_topic_features)\n topk_perc = args.topk_prec\n trainset_1 = train_normal\n num_of_anom = np.round(len(trainset_1) * anom_prec).astype(np.int32)\n indices = np.random.permutation(len(train_id_oos))[:num_of_anom]\n trainset_2 = train_id_oos[indices]\n trainset = np.concatenate((trainset_1, trainset_2), 0)\n shuffle = np.random.permutation(len(trainset))\n trainset = trainset[shuffle]\n testset = np.concatenate((test_normal, test_id_oos), 0)\n labels = np.zeros(len(testset))\n labels[len(test_normal):] = 1\n in_scope_topic_features = np.concatenate(in_scope_topic_features, 0)\n all_aucs_zero = []\n all_aucs_occ = []\n all_aucs_coldfusion = []\n for i in range(0, len(trainset)):\n cur_trainset = trainset[:i + 1]\n if i >= 1 and anom_prec > 0:\n index = faiss.IndexFlatL2(cur_trainset.shape[1])\n index.add(in_scope_topic_features)\n D, _ = index.search(cur_trainset, 1)\n distances = np.mean(D, axis=1)\n indices = np.argsort(distances)\n topk = np.round(len(cur_trainset) * topk_perc).astype(np.int32)\n cur_trainset = cur_trainset[indices[:topk]].astype(np.float32)\n I = assign_observations_to_classes(cur_trainset, in_scope_topic_features)\n adapted_class_embeddings = prepare_class_assignments(I, cur_trainset, in_scope_topic_features)\n auc_zero, auc_dn2, auc_coldfusion = calculate_auroc_scores(\n testset, labels, cur_trainset, in_scope_topic_features, adapted_class_embeddings\n )\n all_aucs_zero.append(auc_zero * 100)\n all_aucs_occ.append(auc_dn2 * 100)\n all_aucs_coldfusion.append(auc_coldfusion * 100)\n if args.TestCode:\n if i == 10:\n return\n output_path = f'./figures/{dataset}/{model_name}/{anom_prec}/'\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n final_output_path = os.path.join(output_path, 'output.png')\n sns.set_style(\"whitegrid\")\n num_of_steps = np.arange(len(trainset))\n plt.figure()\n plt.plot(num_of_steps, all_aucs_zero, label=f'ZS', color='tab:red')\n plt.plot(num_of_steps, all_aucs_occ, label=f'DN2', color='tab:purple')\n plt.plot(num_of_steps, all_aucs_coldfusion, label=f'ColdFusion', color='tab:blue')\n plt.xlabel('Number of queries', fontsize='xx-large')\n plt.ylabel('AUROC (%)', fontsize='xx-large')\n plt.legend(fontsize='xx-large')\n plt.savefig(final_output_path, dpi=600)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--dataset', default='banking77', choices=['banking77', 'clinc_banking', 'clinc_credit_cards'])\n parser.add_argument('--model', default='gte', choices=['gte', 'mpnet'])\n parser.add_argument('--anom_prec', type=float, default=0.05)\n parser.add_argument('--topk_prec', type=float, default=0.9)\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n if os.path.exists('SavedOutputRun'):\n shutil.rmtree('SavedOutputRun')\n main(args)" }, { "task_id": 1, "indent": 1, "script": "\npython coldfusion.py --dataset clinc_banking\n", "latex_code": "\nWe further define $\\mathcal{C}_k$, the set of all observations assigned to class $k$ as $\\mathcal{C}_k = \\{\\phi(x)|a(x)=k\\}$.\n\\textbf{Adaptation.} We now adapt each class embedding by considering both the initial class description and the assigned observations. Concretely, the adapted code for each class is the median of the set containing the embedding of the class descriptions and the embeddings of all assigned observations:\n\\begin{equation}\n z_k = median(\\{\\phi(c_k)\\} \\cup \\mathcal{C}_k)\n % \\vspace{-0.35em}\n\\end{equation}\nWe chose the median and not mean for contamination robustness. Note that this step will not modify the embedding of classes with no observations.\n", "completion_path": "./coldfusion.py", "namespace": "coldfusion.prepare_class_assignments", "type": "function", "signature_position": [ 165, 165 ], "body_position": [ 166, 174 ], "test_case_code": { "insert_pos": -2, "indent": 1, "code": "\noutputDirtask2 = 'SavedOutputRun/task2'\ntask2 = adapted_class_embeddings\nif os.path.exists(outputDirtask2) == False:\n os.makedirs(outputDirtask2)\nfiles = [f for f in os.listdir(outputDirtask2) if os.path.isfile(os.path.join(outputDirtask2, f))]\nnum_file = len(files)\nif num_file < 10:\n id = num_file\n if os.path.exists(outputDirtask2) == False:\n os.makedirs(outputDirtask2)\n filepathtask2 = os.path.join(outputDirtask2, 'output_' + str(id) + '.pickle')\n with open(filepathtask2, 'wb') as f:\n pickle.dump(task2, f)\n" }, "Description": "\nDescription: \n Prepare class assignments by grouping training set observations with their nearest class embeddings and then adapting each class embedding based on the median of its assigned observations.\n", "ReferenceCode_With_Comments": "\neach_class_assignments = []\nfor q in range(len(in_scope_topic_features)):\n # Start each class's assignment list with its original (class description) embedding\n each_class_assignments.append([in_scope_topic_features[q][None]])\n\nfor q in range(len(I)):\n each_class_assignments[I[q]].append(cur_trainset[q][None])\n\n# ---------------------------------------------------------------------------\n# Snippet 1: For each class, compute the median embedding over all assigned\n# items\u2014both the original class description and the newly assigned observations.\n# This implements \\( z_k = \\text{median}\\bigl(\\{\\phi(c_k)\\} \\cup \\mathcal{C}_k \\bigr)\\)\n# as stated in the LaTeX.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nfor q in range(len(in_scope_topic_features)):\n each_class_assignments[q] = np.median(each_class_assignments[q], axis=0)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Concatenate all adapted class embeddings into a single array to\n# produce the final adapted representations across all classes.\n# Return this array.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nadapted_class_embeddings = np.concatenate(each_class_assignments, axis=0)\nreturn adapted_class_embeddings\n# [End Snippet 2]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - None\n \n Mismatched Details:\n - None\n", "Missing_details": [], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - I (ndarray, shape=[num_observations]): \n Contains feature vectors of the observations we want to assign to classes.\n - cur_trainset (ndarray, shape=[num_observations, num_features]): \n Contains feature vectors of the observations we want to assign to classes.\n - in_scope_topic_features (ndarray, shape=[num_classes, num_features]): \n Holds the original class description embeddings.\n", "Arguments_list": [ { "name": "I", "string": "\n- I (ndarray, shape=[num_observations]): \n Contains feature vectors of the observations we want to assign to classes.\n", "dependency": null }, { "name": "cur_trainset", "string": "\n- cur_trainset (ndarray, shape=[num_observations, num_features]): \n Contains feature vectors of the observations we want to assign to classes.\n", "dependency": null }, { "name": "in_scope_topic_features", "string": "\n- in_scope_topic_features (ndarray, shape=[num_classes, num_features]): \n Holds the original class description embeddings.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra File Dependencies: \n - None \n\n Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - numpy.median\n - numpy.concatenate\n", "list": [ "numpy.median", "numpy.concatenate" ] }, "Return": { "Return_String": "\nOutput Variables:\n - adapted_class_embeddings (ndarray, shape=[num_classes, num_features]): \n Contains the adapted class embeddings after adjusting each class embedding based on the median of its assigned observations.\n", "Return_list": [ { "name": "adapted_class_embeddings", "string": "\n- adapted_class_embeddings (ndarray, shape=[num_classes, num_features]): \n Contains the adapted class embeddings after adjusting each class embedding based on the median of its assigned observations.\n", "dependency": null } ] }, "ori_python_file": "import torch\nfrom torch import Tensor\nfrom transformers import AutoTokenizer, AutoModel\nfrom tqdm import tqdm\nfrom sklearn.metrics import roc_auc_score\nimport faiss\nimport numpy as np\nimport argparse\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nimport seaborn as sns\nimport os, pickle, shutil\nimport pickle\n\ndef average_pool(last_hidden_states: Tensor, attention_mask: Tensor) -> Tensor:\n last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0)\n return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]\n\ndef mean_pooling(model_output, attention_mask):\n token_embeddings = model_output[0]\n input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()\n return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)\n\ndef get_model(model_name):\n if model_name == 'mpnet':\n tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-mpnet-base-v2')\n model = AutoModel.from_pretrained('sentence-transformers/all-mpnet-base-v2')\n elif model_name == 'gte':\n tokenizer = AutoTokenizer.from_pretrained(\"thenlper/gte-large\")\n model = AutoModel.from_pretrained(\"thenlper/gte-large\")\n else:\n raise ValueError(f\"Unknown model: {model_name}\")\n return model, tokenizer\n\ndef get_in_scope_queries(dataset):\n if dataset == 'banking77':\n queries = {\n 'activate my card': 'How can I activate my new card?',\n 'age limit': 'Is there an age limit to open a bank account with your service?',\n 'apple pay or google pay': 'Do you support Apple Pay or Google Pay for transactions?',\n 'atm support': 'Which ATMs can I use for withdrawals with your bank card?',\n 'automatic top up': 'How can I set up automatic top-up for my account?',\n 'balance not updated after bank transfer': 'My balance hasn\u2019t updated after a bank transfer. What should I do?',\n 'balance not updated after cheque or cash deposit': 'I deposited a cheque/cash, but my balance hasn\u2019t updated. Why?',\n 'beneficiary not allowed': 'Why am I unable to add a particular beneficiary to my account?',\n 'cancel transfer': 'Can I cancel a transfer I initiated recently?',\n 'card about to expire': 'How can I check when my card is about to expire?',\n 'card acceptance': 'Which merchants or services accept your bank cards?',\n 'card arrival': 'When can I expect the arrival of my new bank card?',\n 'card delivery estimate': 'What is the estimated delivery time for a new bank card?',\n 'card linking': 'How do I link my card to other accounts or services?',\n 'card not working': 'My card is not working. What troubleshooting steps should I follow?',\n 'card payment fee charged': 'Why was I charged a fee for a card payment?',\n 'card payment not recognised': 'I made a card payment, but it\\'s not recognized in my account. What should I do?',\n 'card payment wrong exchange rate': 'I noticed a wrong exchange rate for a recent card payment. How can I address this?',\n 'card swallowed': 'My card got swallowed by an ATM. What should I do now?',\n 'cash withdrawal charge': 'Is there a charge for cash withdrawals using your bank card?',\n 'cash withdrawal not recognised': 'I withdrew cash, but the transaction is not recognized in my account. What\\'s the issue?',\n 'change pin': 'How can I change the PIN for my bank card?',\n 'compromised card': 'I suspect my card details are compromised. What should I do to secure my account?',\n 'contactless not working': 'My contactless payment is not working. How can I fix this issue?',\n 'country support': 'Which countries does your bank service support?',\n 'declined card payment': 'My card payment was declined. What could be the reasons for this?',\n 'declined cash withdrawal': 'Why was my cash withdrawal declined at the ATM?',\n 'declined transfer': 'A transfer I attempted was declined. What steps should I take?',\n 'direct debit payment not recognised': 'I have a direct debit payment not recognized in my account. What\\'s the reason?',\n 'disposable card limits': 'What are the limits for transactions with disposable virtual cards?',\n 'edit personal details': 'How can I edit or update my personal details on the account?',\n 'exchange charge': 'Is there a charge for currency exchange using your bank card?',\n 'exchange rate': 'How can I check the current exchange rates for currencies?',\n 'exchange via app': 'Can I perform currency exchange directly through the mobile app?',\n 'extra charge on statement': 'I noticed an extra charge on my statement. Can you explain this?',\n 'failed transfer': 'A transfer I initiated has failed. What could be the reasons?',\n 'fiat currency support': 'Which fiat currencies are supported by your bank?',\n 'get disposable virtual card': 'How can I obtain a disposable virtual card?',\n 'get physical card': 'What is the process for obtaining a physical bank card?',\n 'getting spare card': 'Can I get a spare or backup bank card?',\n 'getting virtual card': 'How can I get a virtual bank card?',\n 'lost or stolen card': 'My card is lost or stolen. What immediate steps should I take?',\n 'lost or stolen phone': 'If I lose my phone, how can I secure my bank account?',\n 'order physical card': 'How can I order a new physical bank card?',\n 'passcode forgotten': 'I forgot my passcode. How can I recover or reset it?',\n 'pending card payment': 'Why is a card payment showing as pending in my account?',\n 'pending cash withdrawal': 'I have a pending cash withdrawal. When will it be processed?',\n 'pending top up': 'My top-up is pending. When will it reflect in my account balance?',\n 'pending transfer': 'How long does it take for a transfer to move from pending to completed status?',\n 'pin blocked': 'My PIN got blocked. How can I unblock it?',\n 'receiving money': 'How can I receive money into my account?',\n 'Refund not showing up': 'I initiated a refund, but it\\'s not showing up in my account. What should I do?',\n 'request refund': 'How can I request a refund for a transaction?',\n 'reverted card payment?': 'A card payment was reverted. What could be the reason for this?',\n 'supported cards and currencies': 'Which types of cards and currencies does your bank support?',\n 'terminate account': 'What is the process for terminating or closing my bank account?',\n 'top up by bank transfer charge': 'Is there a charge for topping up my account via bank transfer?',\n 'top up by card charge': 'Are there any charges for topping up my account using a bank card?',\n 'top up by cash or cheque': 'Can I top up my account using cash or a cheque?',\n 'top up failed': 'My top-up attempt failed. What could be the reasons for this?',\n 'top up limits': 'Are there any limits on the amount I can top up into my account?',\n 'top up reverted': 'Why was my top-up amount reverted? What should I do?',\n 'topping up by card': 'How can I top up my account using a bank card?',\n 'transaction charged twice': 'I noticed a transaction charged twice. How can I rectify this?',\n 'transfer fee charged': 'Why was I charged a fee for a transfer?',\n 'transfer into account': 'How can I transfer funds into my account from another bank?',\n 'transfer not received by recipient': 'The recipient didn\u2019t receive the funds I transferred. What should I do?',\n 'transfer timing': 'What are the processing times for fund transfers?',\n 'unable to verify identity': 'I am unable to verify my identity. What should I do?',\n 'verify my identity': 'How can I verify my identity with your bank?',\n 'verify source of funds': 'Why do I need to verify the source of funds in my account?',\n 'verify top up': 'Why do I need to verify my top-up transactions?',\n 'virtual card not working': 'My virtual card is not working. What steps should I take?',\n 'visa or mastercard': 'Do you issue Visa or Mastercard for your bank cards?',\n 'why verify identity': 'Why is identity verification necessary for using your bank services?',\n 'wrong amount of cash received': 'I received the wrong amount of cash after a withdrawal. How can this be corrected?',\n 'wrong exchange rate for cash withdrawal': 'The exchange rate for my recent cash withdrawal seems incorrect. What should I do?'\n }\n elif dataset == 'clinc_banking':\n queries = {\n 'transactions': \"Can you provide a list of my recent transactions?\",\n 'report_fraud': \"I suspect fraudulent activity on my account, how can I report it?\",\n 'routing': \"What is the bank's routing number for wire transfers?\",\n 'interest_rate': \"What is the current interest rate on savings accounts?\",\n 'bill_balance': \"What is the outstanding balance on my credit card bill?\",\n 'order_checks': \"How can I order a new set of checks for my checking account?\",\n 'pin_change': \"I need to change my PIN, how can I do that?\",\n 'pay_bill': \"How do I set up automatic bill payments from my account?\",\n 'spending_history': \"Can you provide a summary of my spending history for the last month?\",\n 'account_blocked': \"Why is my account blocked, and how can I resolve this issue?\"\n }\n elif dataset == 'clinc_credit_cards':\n queries = {\n 'expiration_date': \"Can you remind me of my credit card's expiration date?\",\n 'apr': \"What is the current APR on my credit card?\",\n 'new_card': \"How can I apply for a new credit card?\",\n 'redeem_rewards': \"What are the options to redeem my credit card rewards?\",\n 'credit_score': \"Could you provide information about my current credit score?\",\n 'card_declined': \"Why was my credit card declined during the recent transaction?\",\n 'damaged_card': \"My credit card got damaged, what should I do to get a replacement?\",\n 'credit_limit_change': \"Can I request a change in my credit card's limit?\",\n 'international_fees': \"What are the international transaction fees on my credit card?\",\n 'credit_limit': \"What is my current credit card limit?\"\n }\n else:\n raise ValueError(f\"Unknown dataset: {dataset}\")\n for key, value in queries.items():\n queries[key] = [value]\n return queries\n\ndef encode_queries(queries, model, tokenizer, model_name):\n in_scope_topic_features = []\n with torch.no_grad():\n for key, value in tqdm(queries.items(), total=len(queries)):\n if model_name == 'gte':\n batch_dict = tokenizer(queries[key], max_length=512, padding=True, truncation=True, return_tensors='pt')\n outputs = model(**batch_dict)\n cur_occ = average_pool(outputs.last_hidden_state,\n batch_dict['attention_mask']).contiguous().cpu().numpy()\n else:\n batch_dict = tokenizer(queries[key], padding=True, truncation=True, return_tensors='pt')\n outputs = model(**batch_dict)\n cur_occ = mean_pooling(outputs, batch_dict['attention_mask'])\n in_scope_topic_features.append(cur_occ)\n in_scope_topic_features = np.array(in_scope_topic_features)\n return in_scope_topic_features\n\ndef prepare_class_assignments(I, cur_trainset, in_scope_topic_features):\n each_class_assignments = []\n for q in range(len(in_scope_topic_features)):\n each_class_assignments.append([in_scope_topic_features[q][None]])\n for q in range(len(I)):\n each_class_assignments[I[q]].append(cur_trainset[q][None])\n for q in range(len(in_scope_topic_features)):\n each_class_assignments[q] = np.median(each_class_assignments[q], axis=0)\n adapted_class_embeddings = np.concatenate(each_class_assignments, axis=0)\n return adapted_class_embeddings\n\ndef assign_observations_to_classes(cur_trainset, in_scope_topic_features):\n index = faiss.IndexFlatL2(cur_trainset.shape[1])\n index.add(in_scope_topic_features)\n _, I = index.search(cur_trainset, 1)\n I = I[:, 0]\n return I\n\ndef calculate_auroc_scores(testset, labels, cur_trainset, in_scope_topic_features, adapted_class_embeddings):\n k = 1\n index = faiss.IndexFlatL2(cur_trainset.shape[1])\n index.add(in_scope_topic_features)\n D, _ = index.search(testset, k)\n distances_zero = np.mean(D, axis=1)\n auc_zero = roc_auc_score(labels, distances_zero)\n index = faiss.IndexFlatL2(cur_trainset.shape[1])\n index.add(cur_trainset)\n D, _ = index.search(testset, k)\n distances = np.mean(D, axis=1)\n auc_dn2 = roc_auc_score(labels, distances)\n index = faiss.IndexFlatL2(cur_trainset.shape[1])\n index.add(adapted_class_embeddings)\n D, _ = index.search(testset, k)\n distances_coldfusion = np.mean(D, axis=1)\n auc_coldfusion = roc_auc_score(labels, distances_coldfusion)\n return auc_zero, auc_dn2, auc_coldfusion\n\ndef main(args):\n np.random.seed(0)\n model_name = args.model\n dataset = args.dataset\n train_normal = np.load(f'./features/{dataset}/{model_name}/train.npy')\n train_id_oos = np.load(f'./features/{dataset}/{model_name}/id-oos-valid.npy')\n test_normal = np.load(f'./features/{dataset}/{model_name}/test.npy')\n test_id_oos = np.load(f'./features/{dataset}/{model_name}/id-oos-test.npy')\n model, tokenizer = get_model(model_name)\n queries = get_in_scope_queries(dataset)\n in_scope_topic_features = encode_queries(queries, model, tokenizer, model_name)\n anom_prec = args.anom_prec\n number_of_in_scope_topics = len(in_scope_topic_features)\n topk_perc = args.topk_prec\n trainset_1 = train_normal\n num_of_anom = np.round(len(trainset_1) * anom_prec).astype(np.int32)\n indices = np.random.permutation(len(train_id_oos))[:num_of_anom]\n trainset_2 = train_id_oos[indices]\n trainset = np.concatenate((trainset_1, trainset_2), 0)\n shuffle = np.random.permutation(len(trainset))\n trainset = trainset[shuffle]\n testset = np.concatenate((test_normal, test_id_oos), 0)\n labels = np.zeros(len(testset))\n labels[len(test_normal):] = 1\n in_scope_topic_features = np.concatenate(in_scope_topic_features, 0)\n all_aucs_zero = []\n all_aucs_occ = []\n all_aucs_coldfusion = []\n for i in range(0, len(trainset)):\n cur_trainset = trainset[:i + 1]\n if i >= 1 and anom_prec > 0:\n index = faiss.IndexFlatL2(cur_trainset.shape[1])\n index.add(in_scope_topic_features)\n D, _ = index.search(cur_trainset, 1)\n distances = np.mean(D, axis=1)\n indices = np.argsort(distances)\n topk = np.round(len(cur_trainset) * topk_perc).astype(np.int32)\n cur_trainset = cur_trainset[indices[:topk]].astype(np.float32)\n I = assign_observations_to_classes(cur_trainset, in_scope_topic_features)\n adapted_class_embeddings = prepare_class_assignments(I, cur_trainset, in_scope_topic_features)\n auc_zero, auc_dn2, auc_coldfusion = calculate_auroc_scores(\n testset, labels, cur_trainset, in_scope_topic_features, adapted_class_embeddings\n )\n all_aucs_zero.append(auc_zero * 100)\n all_aucs_occ.append(auc_dn2 * 100)\n all_aucs_coldfusion.append(auc_coldfusion * 100)\n if args.TestCode:\n if i == 10:\n return\n output_path = f'./figures/{dataset}/{model_name}/{anom_prec}/'\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n final_output_path = os.path.join(output_path, 'output.png')\n sns.set_style(\"whitegrid\")\n num_of_steps = np.arange(len(trainset))\n plt.figure()\n plt.plot(num_of_steps, all_aucs_zero, label=f'ZS', color='tab:red')\n plt.plot(num_of_steps, all_aucs_occ, label=f'DN2', color='tab:purple')\n plt.plot(num_of_steps, all_aucs_coldfusion, label=f'ColdFusion', color='tab:blue')\n plt.xlabel('Number of queries', fontsize='xx-large')\n plt.ylabel('AUROC (%)', fontsize='xx-large')\n plt.legend(fontsize='xx-large')\n plt.savefig(final_output_path, dpi=600)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--dataset', default='banking77', choices=['banking77', 'clinc_banking', 'clinc_credit_cards'])\n parser.add_argument('--model', default='gte', choices=['gte', 'mpnet'])\n parser.add_argument('--anom_prec', type=float, default=0.05)\n parser.add_argument('--topk_prec', type=float, default=0.9)\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n if os.path.exists('SavedOutputRun'):\n shutil.rmtree('SavedOutputRun')\n main(args)" }, { "task_id": 2, "indent": 1, "completion_path": "./coldfusion.py", "script": "\npython coldfusion.py --dataset clinc_banking\n", "latex_code": "\n\\textbf{Anomaly scoring.} ColdFusion uses the same anomaly scoring as ZS except that the class codes are the adapted $\\{z_k\\}_{k=1}^K$ instead of the encoding of the original description i.e., $S_{adapt}(x) = \\min_k \\{d(\\phi(x_{t+1}),z_k)\\}_{k=1}^K$.\n", "namespace": "coldfusion.calculate_auroc_scores", "type": "function", "signature_position": [ 183, 183 ], "body_position": [ 184, 200 ], "test_case_code": { "insert_pos": -2, "indent": 1, "code": "\noutputDirTask = 'SavedOutputRun/task3'\ntask = {'auc_zero': auc_zero, 'auc_dn2': auc_dn2, 'auc_coldfusion': auc_coldfusion}\nif os.path.exists(outputDirTask) == False:\n os.makedirs(outputDirTask)\nfiles = [f for f in os.listdir(outputDirTask) if os.path.isfile(os.path.join(outputDirTask, f))]\nnum_file = len(files)\nif num_file < 10:\n id = num_file\n if os.path.exists(outputDirTask) == False:\n os.makedirs(outputDirTask)\n filepathTask = os.path.join(outputDirTask, 'output_' + str(id) + '.pickle')\n with open(filepathTask, 'wb') as f:\n pickle.dump(task, f)\n" }, "Description": "\nDescription: Calculate AUROC scores for different methods (Zero-shot, DN2, ColdFusion).\n This function evaluates three anomaly detection approaches:\n (1) Zero-shot approach (ZS),\n (2) DN2 (an observation-based method),\n (3) ColdFusion adaptation approach.\n It measures performance using the ROC-AUC metric.\n", "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Zero-Shot (ZS) scoring.\n# Using the original class embeddings \\(\\{\\phi(c_k)\\}\\) as described in the LaTeX \n# method, computing S_{zs}(x) = min_k d(\\phi(x), \\phi(c_k)).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nk = 1\nindex = faiss.IndexFlatL2(cur_trainset.shape[1])\nindex.add(in_scope_topic_features)\nD, _ = index.search(testset, k)\ndistances_zero = np.mean(D, axis=1)\nauc_zero = roc_auc_score(labels, distances_zero)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: DN2 scoring.\n# Instead of using class embeddings, the training set observations themselves \n# serve as references, aligning with an instance-based nearest-neighbor approach.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nindex = faiss.IndexFlatL2(cur_trainset.shape[1])\nindex.add(cur_trainset)\nD, _ = index.search(testset, k)\ndistances = np.mean(D, axis=1)\nauc_dn2 = roc_auc_score(labels, distances)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: ColdFusion scoring.\n# Uses the adapted class embeddings \\(\\{z_k\\}\\), reflecting the description \n# \\( S_{adapt}(x) = \\min_k d(\\phi(x), z_k)\\). This matches the LaTeX snippet's \n# notion of replacing the original description embeddings with their adapted \n# counterparts for anomaly scoring.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nindex = faiss.IndexFlatL2(cur_trainset.shape[1])\nindex.add(adapted_class_embeddings)\nD, _ = index.search(testset, k)\ndistances_coldfusion = np.mean(D, axis=1)\nauc_coldfusion = roc_auc_score(labels, distances_coldfusion)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Return the AUROC scores for each scoring method,\n# providing a comparative evaluation of ZS, DN2, and ColdFusion.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nreturn auc_zero, auc_dn2, auc_coldfusion\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - Explicit mention of L2 distance as the metric.\n - k=1 nearest neighbor search configuration.\n\n Mismatched Details:\n - None\n", "Missing_details": [ "\n- Explicit mention of L2 distance as the metric.\n", "\n- k=1 nearest neighbor search configuration.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - testset (ndarray, shape=[num_test_samples, num_features]): The feature representations of the test samples.\n - labels (ndarray, shape=[num_test_samples]): Ground truth labels (e.g., 0 for in-distribution or 1 for out-of-distribution/anomalous samples).\n - cur_trainset (ndarray, shape=[num_observations, num_features]): Represents the feature vectors of the current training observations.\n - in_scope_topic_features (ndarray, shape=[num_classes, num_features]): Represents the class feature vectors (e.g., centroids or some representative embeddings.\n - adapted_class_embeddings (ndarray, shape=[num_adapted_classes, num_features]): Adapted class embeddings for the ColdFusion approach. \n", "Arguments_list": [ { "name": "testset", "string": "- testset (ndarray, shape=[num_test_samples, num_features]): The feature representations of the test samples.", "dependency": null }, { "name": "labels", "string": "- labels (ndarray, shape=[num_test_samples]): Ground truth labels (e.g., 0 for in-distribution or 1 for out-of-distribution/anomalous samples).", "dependency": null }, { "name": "cur_trainset", "string": "- cur_trainset (ndarray, shape=[num_observations, num_features]): Represents the feature vectors of the current training observations.", "dependency": null }, { "name": "in_scope_topic_features", "string": "- in_scope_topic_features (ndarray, shape=[num_classes, num_features]): Represents the class feature vectors (e.g., centroids or some representative embeddings.", "dependency": null }, { "name": "adapted_class_embeddings", "string": "adapted_class_embeddings (ndarray, shape=[num_classes, num_features]): Contains the adapted class embeddings after adjusting each class embedding based on the median of its assigned observations.", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra File Dependencies: \n - None\n\n Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - faiss.IndexFlatL2\n - sklearn.metrics.roc_auc_score\n - numpy.mean\n", "list": [ "faiss.IndexFlatL2", "sklearn.metrics.roc_auc_score", "numpy.mean" ] }, "Return": { "Return_String": "\nOutput Variables:\n - auc_zero (float): AUROC score for the Zero-shot approach.\n - auc_dn2 (float): AUROC score for the DN2 approach.\n - auc_coldfusion (float): AUROC score for the ColdFusion approach.\n", "Return_list": [ { "name": "auc_zero", "string": "- auc_zero (float): AUROC score for the Zero-shot approach.", "dependency": null }, { "name": "auc_dn2", "string": "- auc_dn2 (float): AUROC score for the DN2 approach.", "dependency": null }, { "name": "auc_coldfusion", "string": "- auc_coldfusion (float): AUROC score for the ColdFusion approach.", "dependency": null } ] }, "ori_python_file": "import torch\nfrom torch import Tensor\nfrom transformers import AutoTokenizer, AutoModel\nfrom tqdm import tqdm\nfrom sklearn.metrics import roc_auc_score\nimport faiss\nimport numpy as np\nimport argparse\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nimport seaborn as sns\nimport os, pickle, shutil\nimport pickle\n\ndef average_pool(last_hidden_states: Tensor, attention_mask: Tensor) -> Tensor:\n last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0)\n return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]\n\ndef mean_pooling(model_output, attention_mask):\n token_embeddings = model_output[0]\n input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()\n return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)\n\ndef get_model(model_name):\n if model_name == 'mpnet':\n tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-mpnet-base-v2')\n model = AutoModel.from_pretrained('sentence-transformers/all-mpnet-base-v2')\n elif model_name == 'gte':\n tokenizer = AutoTokenizer.from_pretrained(\"thenlper/gte-large\")\n model = AutoModel.from_pretrained(\"thenlper/gte-large\")\n else:\n raise ValueError(f\"Unknown model: {model_name}\")\n return model, tokenizer\n\ndef get_in_scope_queries(dataset):\n if dataset == 'banking77':\n queries = {\n 'activate my card': 'How can I activate my new card?',\n 'age limit': 'Is there an age limit to open a bank account with your service?',\n 'apple pay or google pay': 'Do you support Apple Pay or Google Pay for transactions?',\n 'atm support': 'Which ATMs can I use for withdrawals with your bank card?',\n 'automatic top up': 'How can I set up automatic top-up for my account?',\n 'balance not updated after bank transfer': 'My balance hasn\u2019t updated after a bank transfer. What should I do?',\n 'balance not updated after cheque or cash deposit': 'I deposited a cheque/cash, but my balance hasn\u2019t updated. Why?',\n 'beneficiary not allowed': 'Why am I unable to add a particular beneficiary to my account?',\n 'cancel transfer': 'Can I cancel a transfer I initiated recently?',\n 'card about to expire': 'How can I check when my card is about to expire?',\n 'card acceptance': 'Which merchants or services accept your bank cards?',\n 'card arrival': 'When can I expect the arrival of my new bank card?',\n 'card delivery estimate': 'What is the estimated delivery time for a new bank card?',\n 'card linking': 'How do I link my card to other accounts or services?',\n 'card not working': 'My card is not working. What troubleshooting steps should I follow?',\n 'card payment fee charged': 'Why was I charged a fee for a card payment?',\n 'card payment not recognised': 'I made a card payment, but it\\'s not recognized in my account. What should I do?',\n 'card payment wrong exchange rate': 'I noticed a wrong exchange rate for a recent card payment. How can I address this?',\n 'card swallowed': 'My card got swallowed by an ATM. What should I do now?',\n 'cash withdrawal charge': 'Is there a charge for cash withdrawals using your bank card?',\n 'cash withdrawal not recognised': 'I withdrew cash, but the transaction is not recognized in my account. What\\'s the issue?',\n 'change pin': 'How can I change the PIN for my bank card?',\n 'compromised card': 'I suspect my card details are compromised. What should I do to secure my account?',\n 'contactless not working': 'My contactless payment is not working. How can I fix this issue?',\n 'country support': 'Which countries does your bank service support?',\n 'declined card payment': 'My card payment was declined. What could be the reasons for this?',\n 'declined cash withdrawal': 'Why was my cash withdrawal declined at the ATM?',\n 'declined transfer': 'A transfer I attempted was declined. What steps should I take?',\n 'direct debit payment not recognised': 'I have a direct debit payment not recognized in my account. What\\'s the reason?',\n 'disposable card limits': 'What are the limits for transactions with disposable virtual cards?',\n 'edit personal details': 'How can I edit or update my personal details on the account?',\n 'exchange charge': 'Is there a charge for currency exchange using your bank card?',\n 'exchange rate': 'How can I check the current exchange rates for currencies?',\n 'exchange via app': 'Can I perform currency exchange directly through the mobile app?',\n 'extra charge on statement': 'I noticed an extra charge on my statement. Can you explain this?',\n 'failed transfer': 'A transfer I initiated has failed. What could be the reasons?',\n 'fiat currency support': 'Which fiat currencies are supported by your bank?',\n 'get disposable virtual card': 'How can I obtain a disposable virtual card?',\n 'get physical card': 'What is the process for obtaining a physical bank card?',\n 'getting spare card': 'Can I get a spare or backup bank card?',\n 'getting virtual card': 'How can I get a virtual bank card?',\n 'lost or stolen card': 'My card is lost or stolen. What immediate steps should I take?',\n 'lost or stolen phone': 'If I lose my phone, how can I secure my bank account?',\n 'order physical card': 'How can I order a new physical bank card?',\n 'passcode forgotten': 'I forgot my passcode. How can I recover or reset it?',\n 'pending card payment': 'Why is a card payment showing as pending in my account?',\n 'pending cash withdrawal': 'I have a pending cash withdrawal. When will it be processed?',\n 'pending top up': 'My top-up is pending. When will it reflect in my account balance?',\n 'pending transfer': 'How long does it take for a transfer to move from pending to completed status?',\n 'pin blocked': 'My PIN got blocked. How can I unblock it?',\n 'receiving money': 'How can I receive money into my account?',\n 'Refund not showing up': 'I initiated a refund, but it\\'s not showing up in my account. What should I do?',\n 'request refund': 'How can I request a refund for a transaction?',\n 'reverted card payment?': 'A card payment was reverted. What could be the reason for this?',\n 'supported cards and currencies': 'Which types of cards and currencies does your bank support?',\n 'terminate account': 'What is the process for terminating or closing my bank account?',\n 'top up by bank transfer charge': 'Is there a charge for topping up my account via bank transfer?',\n 'top up by card charge': 'Are there any charges for topping up my account using a bank card?',\n 'top up by cash or cheque': 'Can I top up my account using cash or a cheque?',\n 'top up failed': 'My top-up attempt failed. What could be the reasons for this?',\n 'top up limits': 'Are there any limits on the amount I can top up into my account?',\n 'top up reverted': 'Why was my top-up amount reverted? What should I do?',\n 'topping up by card': 'How can I top up my account using a bank card?',\n 'transaction charged twice': 'I noticed a transaction charged twice. How can I rectify this?',\n 'transfer fee charged': 'Why was I charged a fee for a transfer?',\n 'transfer into account': 'How can I transfer funds into my account from another bank?',\n 'transfer not received by recipient': 'The recipient didn\u2019t receive the funds I transferred. What should I do?',\n 'transfer timing': 'What are the processing times for fund transfers?',\n 'unable to verify identity': 'I am unable to verify my identity. What should I do?',\n 'verify my identity': 'How can I verify my identity with your bank?',\n 'verify source of funds': 'Why do I need to verify the source of funds in my account?',\n 'verify top up': 'Why do I need to verify my top-up transactions?',\n 'virtual card not working': 'My virtual card is not working. What steps should I take?',\n 'visa or mastercard': 'Do you issue Visa or Mastercard for your bank cards?',\n 'why verify identity': 'Why is identity verification necessary for using your bank services?',\n 'wrong amount of cash received': 'I received the wrong amount of cash after a withdrawal. How can this be corrected?',\n 'wrong exchange rate for cash withdrawal': 'The exchange rate for my recent cash withdrawal seems incorrect. What should I do?'\n }\n elif dataset == 'clinc_banking':\n queries = {\n 'transactions': \"Can you provide a list of my recent transactions?\",\n 'report_fraud': \"I suspect fraudulent activity on my account, how can I report it?\",\n 'routing': \"What is the bank's routing number for wire transfers?\",\n 'interest_rate': \"What is the current interest rate on savings accounts?\",\n 'bill_balance': \"What is the outstanding balance on my credit card bill?\",\n 'order_checks': \"How can I order a new set of checks for my checking account?\",\n 'pin_change': \"I need to change my PIN, how can I do that?\",\n 'pay_bill': \"How do I set up automatic bill payments from my account?\",\n 'spending_history': \"Can you provide a summary of my spending history for the last month?\",\n 'account_blocked': \"Why is my account blocked, and how can I resolve this issue?\"\n }\n elif dataset == 'clinc_credit_cards':\n queries = {\n 'expiration_date': \"Can you remind me of my credit card's expiration date?\",\n 'apr': \"What is the current APR on my credit card?\",\n 'new_card': \"How can I apply for a new credit card?\",\n 'redeem_rewards': \"What are the options to redeem my credit card rewards?\",\n 'credit_score': \"Could you provide information about my current credit score?\",\n 'card_declined': \"Why was my credit card declined during the recent transaction?\",\n 'damaged_card': \"My credit card got damaged, what should I do to get a replacement?\",\n 'credit_limit_change': \"Can I request a change in my credit card's limit?\",\n 'international_fees': \"What are the international transaction fees on my credit card?\",\n 'credit_limit': \"What is my current credit card limit?\"\n }\n else:\n raise ValueError(f\"Unknown dataset: {dataset}\")\n for key, value in queries.items():\n queries[key] = [value]\n return queries\n\ndef encode_queries(queries, model, tokenizer, model_name):\n in_scope_topic_features = []\n with torch.no_grad():\n for key, value in tqdm(queries.items(), total=len(queries)):\n if model_name == 'gte':\n batch_dict = tokenizer(queries[key], max_length=512, padding=True, truncation=True, return_tensors='pt')\n outputs = model(**batch_dict)\n cur_occ = average_pool(outputs.last_hidden_state,\n batch_dict['attention_mask']).contiguous().cpu().numpy()\n else:\n batch_dict = tokenizer(queries[key], padding=True, truncation=True, return_tensors='pt')\n outputs = model(**batch_dict)\n cur_occ = mean_pooling(outputs, batch_dict['attention_mask'])\n in_scope_topic_features.append(cur_occ)\n in_scope_topic_features = np.array(in_scope_topic_features)\n return in_scope_topic_features\n\ndef prepare_class_assignments(I, cur_trainset, in_scope_topic_features):\n each_class_assignments = []\n for q in range(len(in_scope_topic_features)):\n each_class_assignments.append([in_scope_topic_features[q][None]])\n for q in range(len(I)):\n each_class_assignments[I[q]].append(cur_trainset[q][None])\n for q in range(len(in_scope_topic_features)):\n each_class_assignments[q] = np.median(each_class_assignments[q], axis=0)\n adapted_class_embeddings = np.concatenate(each_class_assignments, axis=0)\n return adapted_class_embeddings\n\ndef assign_observations_to_classes(cur_trainset, in_scope_topic_features):\n index = faiss.IndexFlatL2(cur_trainset.shape[1])\n index.add(in_scope_topic_features)\n _, I = index.search(cur_trainset, 1)\n I = I[:, 0]\n return I\n\ndef calculate_auroc_scores(testset, labels, cur_trainset, in_scope_topic_features, adapted_class_embeddings):\n k = 1\n index = faiss.IndexFlatL2(cur_trainset.shape[1])\n index.add(in_scope_topic_features)\n D, _ = index.search(testset, k)\n distances_zero = np.mean(D, axis=1)\n auc_zero = roc_auc_score(labels, distances_zero)\n index = faiss.IndexFlatL2(cur_trainset.shape[1])\n index.add(cur_trainset)\n D, _ = index.search(testset, k)\n distances = np.mean(D, axis=1)\n auc_dn2 = roc_auc_score(labels, distances)\n index = faiss.IndexFlatL2(cur_trainset.shape[1])\n index.add(adapted_class_embeddings)\n D, _ = index.search(testset, k)\n distances_coldfusion = np.mean(D, axis=1)\n auc_coldfusion = roc_auc_score(labels, distances_coldfusion)\n return auc_zero, auc_dn2, auc_coldfusion\n\ndef main(args):\n np.random.seed(0)\n model_name = args.model\n dataset = args.dataset\n train_normal = np.load(f'./features/{dataset}/{model_name}/train.npy')\n train_id_oos = np.load(f'./features/{dataset}/{model_name}/id-oos-valid.npy')\n test_normal = np.load(f'./features/{dataset}/{model_name}/test.npy')\n test_id_oos = np.load(f'./features/{dataset}/{model_name}/id-oos-test.npy')\n model, tokenizer = get_model(model_name)\n queries = get_in_scope_queries(dataset)\n in_scope_topic_features = encode_queries(queries, model, tokenizer, model_name)\n anom_prec = args.anom_prec\n number_of_in_scope_topics = len(in_scope_topic_features)\n topk_perc = args.topk_prec\n trainset_1 = train_normal\n num_of_anom = np.round(len(trainset_1) * anom_prec).astype(np.int32)\n indices = np.random.permutation(len(train_id_oos))[:num_of_anom]\n trainset_2 = train_id_oos[indices]\n trainset = np.concatenate((trainset_1, trainset_2), 0)\n shuffle = np.random.permutation(len(trainset))\n trainset = trainset[shuffle]\n testset = np.concatenate((test_normal, test_id_oos), 0)\n labels = np.zeros(len(testset))\n labels[len(test_normal):] = 1\n in_scope_topic_features = np.concatenate(in_scope_topic_features, 0)\n all_aucs_zero = []\n all_aucs_occ = []\n all_aucs_coldfusion = []\n for i in range(0, len(trainset)):\n cur_trainset = trainset[:i + 1]\n if i >= 1 and anom_prec > 0:\n index = faiss.IndexFlatL2(cur_trainset.shape[1])\n index.add(in_scope_topic_features)\n D, _ = index.search(cur_trainset, 1)\n distances = np.mean(D, axis=1)\n indices = np.argsort(distances)\n topk = np.round(len(cur_trainset) * topk_perc).astype(np.int32)\n cur_trainset = cur_trainset[indices[:topk]].astype(np.float32)\n I = assign_observations_to_classes(cur_trainset, in_scope_topic_features)\n adapted_class_embeddings = prepare_class_assignments(I, cur_trainset, in_scope_topic_features)\n auc_zero, auc_dn2, auc_coldfusion = calculate_auroc_scores(\n testset, labels, cur_trainset, in_scope_topic_features, adapted_class_embeddings\n )\n all_aucs_zero.append(auc_zero * 100)\n all_aucs_occ.append(auc_dn2 * 100)\n all_aucs_coldfusion.append(auc_coldfusion * 100)\n if args.TestCode:\n if i == 10:\n return\n output_path = f'./figures/{dataset}/{model_name}/{anom_prec}/'\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n final_output_path = os.path.join(output_path, 'output.png')\n sns.set_style(\"whitegrid\")\n num_of_steps = np.arange(len(trainset))\n plt.figure()\n plt.plot(num_of_steps, all_aucs_zero, label=f'ZS', color='tab:red')\n plt.plot(num_of_steps, all_aucs_occ, label=f'DN2', color='tab:purple')\n plt.plot(num_of_steps, all_aucs_coldfusion, label=f'ColdFusion', color='tab:blue')\n plt.xlabel('Number of queries', fontsize='xx-large')\n plt.ylabel('AUROC (%)', fontsize='xx-large')\n plt.legend(fontsize='xx-large')\n plt.savefig(final_output_path, dpi=600)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--dataset', default='banking77', choices=['banking77', 'clinc_banking', 'clinc_credit_cards'])\n parser.add_argument('--model', default='gte', choices=['gte', 'mpnet'])\n parser.add_argument('--anom_prec', type=float, default=0.05)\n parser.add_argument('--topk_prec', type=float, default=0.9)\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n if os.path.exists('SavedOutputRun'):\n shutil.rmtree('SavedOutputRun')\n main(args)" } ] }, { "paper_id": 1, "paper_details": { "title": "addressing order sensitivity of in-context demonstration examples in causal language models", "url": "https://arxiv.org/abs/2402.15637" }, "enviorment_name": "order", "repo_original_url": "https://github.com/xyzCS/InfoAC", "project_path": "Benchmark/1-InfoAC/InfoAC", "file_organization": "\nInfoAC/\n concatenator.py\n Evaluation.py\n LLama.py\n main.py\n MyDataset/\n IncontextData.py\n SST-5/\n SST5-LLama-Pool100-Len10-Gold.pickle\n SST5-LLama-Pool100-Len10-Test.pickle\n SST5-LLama-Pool100-Len10-Train.pickle\n SST5-Vicuna-Pool100-Len10-Gold.pickle\n SST5-Vicuna-Pool100-Len10-Test.pickle\n SST5-Vicuna-Pool100-Len10-Train.pickle\n README.md\n requirements.txt\n sampler.py\n trainingconfig.py\n", "latex_code_path": "Benchmark/1-InfoAC/arXiv-2402.15637v2", "task_details": [ { "task_id": 0, "indent": 1, "script": "\npython main.py --use_peft --quantization --NumTrain 1000 --Model='LLama-7B' --Dataset='SST5'\n", "latex_code": "\n\\subsubsection{Information Augmentation}\nRecall that our objective is to align the representations from different positions with those at the end of the demonstration. \nTo achieve this, we employ an original version of the model as a reference model $M_r$ to derive the reference representation.\nNotably, $M_r$ is fixed and doesn't require gradient update during the fine-tuning process.\nBy feeding $I$ and $I_r$ into $M$ and $M_r$, we obtain the token-level outputs of the last self-attention layer, denoted as $\\bm{H} \\in \\mathbb{R}^{m \\times n \\times d}$ and $\\bm{H_r} \\in \\mathbb{R}^{m \\times n \\times d}$, respectively:\n\\begin{equation}\n\t\\bm{H} = M(I), \\bm{H_r} = M_r(I_r),\n\\end{equation}\nHere, $m$ is the number of sampled permutations and also corresponds to the batch size, $n$ indicates the length of the input sequence, and $d$ refers to the dimension of the output representation.\nThen we obtain reference representations $\\mathbb{R}= \\{\\bm{r_1}, \\bm{r_2},...,\\bm{r_m}\\}$ for those in-context examples $\\mathbb{S} = \\{s_1, s_2,..., s_m\\}$ that are placed at the last position of the demonstration according to Eq~(\\ref{eq:avg_reference}):\n\\begin{equation}\n\t\\bm{r_i} = \\bm{H_r}[i,\\text{Start}_{i}^{i}:\\text{End}_{i}^{i}],\n\\label{eq:avg_reference}\n\\end{equation}\nwhere $\\text{Start}_{i}^{i}$ and $\\text{End}_{i}^{i}$ denote the start and the end index of $s_i$ within the input $I_i$.\nWe introduce a token-level contrastive learning objective $\\mathcal{L}_{cl}$ to integrate the information from the reference representation into the learning process of the model $M$:\n\\begin{equation} \\small\n\\mathcal{L}_{cl} = -\\text{log}\\sum_{i=1}^{m}\\sum_{j}^{s_j \\in \\mathbb{S}} \n\t \\sum_{o=1}^{n_j} \\frac{\\text{Pos}(i,j,o)}{\\text{Pos}(i,j,o) + \\text{Neg}(i,j,o)},\n\\end{equation}\n\\begin{equation} \\small\n\\text{Pos}(i,j,o) = \\text{exp}\\big(\\text{cos}(\\bm{H}[i,\\text{Start}_{i}^{j}+o],\n\t\t\t\t\t \\bm{r}_j[i,o])\\big)/\\tau, \\\\\n\\end{equation}\n\n\\begin{equation} \\small\n\\text{Neg}(i,j,o) = \\text{exp}\\big(\\text{cos}(\\bm{H}[i,\\text{Start}_{i}^{j}+o], \n\t\t\t\t\t \\bm{Q})\\big)/\\tau.\n\\end{equation}\nHere, $n_j$ is the number of tokens within the in-context example $s_j$, $\\text{Start}_{i}^{j}$ represents the start index of $s_j$ within the input $I_i$ and $\\text{cos}(.)$ denotes the cosine similarity function.\nThe positive sample $\\bm{r}_j[i,o]$ is the reference representation of the token, while the negative sample $\\bm{Q}$ is an independent copy of $\\bm{H}[i,\\text{Start}_{i}^{j}+o]$, detached from the computational graph.\n\nThis loss mechanism aims to align the self-attention output of each token more closely with the reference output, thereby increasing the distance from its original representation.\nWith this approach, the model integrates information from the reference representation into the LoRA parameters of self-attention layers while fine-tuning.\nConsequently, it allows a token to access information from subsequent tokens, regardless of the limitations imposed by the attention masks.\n", "completion_path": "./main.py", "namespace": "main.calculate_information_augmentation_loss", "type": "function", "signature_position": [ 112, 112 ], "signature": "\ndef calculate_information_augmentation_loss(Attn_States, Attn_States_gold, permutaion_batch, permutaion_gold, index_batch, index_gold, batch_size, Temperature=0.1):\n", "body_position": [ 113, 157 ], "ReferenceCode_With_Comments": "\nloss_contrast = 0\n\nnumPerSam = batch_size\n\nfor i in range(0, batch_size, numPerSam):\n senGold = dict()\n senOri = dict()\n\n senGold['0'] = dict()\n senOri['0'] = dict()\n\n for m in range(10):\n senGold[str(m)] = dict()\n senOri[str(m)] = dict()\n\n for j in range(numPerSam):\n permutationTmp = permutaion_batch[i + j]\n for m in range(permutationTmp.shape[0] - 1):\n # ---------------------------------------------------------------------------\n # Snippet 1: The original token representations \\( \\mathbf{H} \\) are grouped\n # based on their corresponding positions in the permutation batch. This step\n # maps to the selection of token-level outputs from \\( M(I) \\) described\n # in Equation (1) of the LaTeX snippet.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 1]\n if str(int(permutationTmp[m])) in senOri.keys():\n if str(m) not in senOri[str(int(permutationTmp[m]))].keys():\n senOri[str(int(permutationTmp[m]))][str(m)] = list()\n senOri[str(int(permutationTmp[m]))][str(m)].append(\n Attn_States[i + j, -1, index_batch[i + j][m][0] : index_batch[i + j][m][1], :].reshape(-1, Attn_States.shape[-1])\n )\n # [End Snippet 1]\n\n for j in range(numPerSam):\n permutationTmp = permutaion_gold[i + j]\n # ---------------------------------------------------------------------------\n # Snippet 2: Reference representations \\( \\mathbf{H_r} \\) are extracted for the\n # tokens at specific positions according to the permutation gold. This corresponds\n # to obtaining \\( \\mathbf{r}_i \\) as defined in Equation (2) in the LaTeX snippet.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 2]\n senGold[str(int(permutationTmp[-2]))] = (\n Attn_States_gold[i + j, -1, index_gold[i + j][-2][0] : index_gold[i + j][-2][1], :]\n .reshape(-1, Attn_States.shape[-1])\n )\n # [End Snippet 2]\n\n cos = nn.CosineSimilarity(dim=1)\n\n num = 0\n\n for j in senOri.keys():\n if senGold[j] != {}:\n for m in senOri[j].keys():\n for k in range(len(senOri[j][m])):\n query = senOri[j][m][k]\n key = senGold[j]\n # -------------------------------------------------------------------\n # Snippet 3: Cosine similarity between the token representations \\( \\mathbf{H} \\)\n # and reference representations \\( \\mathbf{H_r} \\) is calculated. This\n # mirrors the computation of \\( \\text{cos}(\\mathbf{H}, \\mathbf{r}) \\) in\n # Equation (4) from the LaTeX snippet.\n # -------------------------------------------------------------------\n # [Begin Snippet 3]\n multi = cos(query, key)\n multi /= Temperature\n positive = torch.exp(multi)\n # [End Snippet 3]\n\n # -------------------------------------------------------------------\n # Snippet 4: Negative samples \\( \\mathbf{Q} \\) are compared against the\n # tokens to compute \\( \\text{Neg}(i,j,o) \\), as per Equation (5) in the\n # LaTeX description. The contrastive loss is then computed based on the\n # log-ratio of positive and negative similarities.\n # -------------------------------------------------------------------\n # [Begin Snippet 4]\n multiNeg = cos(query, query.clone().detach())\n multiNeg /= Temperature\n negative = torch.exp(multiNeg)\n loss_tmp = -torch.log(positive / (positive + negative))\n loss_tmp = torch.mean(loss_tmp)\n loss_contrast += loss_tmp\n num += 1\n # [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: The average loss \\( \\mathcal{L}_{cl} \\) is computed over all tokens,\n# aligning with the final contrastive loss objective defined in Equation (3)\n# in the LaTeX snippet.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nloss_contrast /= num\n\nreturn loss_contrast\n# [End Snippet 5]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - None\n\n Mismatched Details:\n - LaTeX uses sum over all tokens while averages loss per token.\n", "Missing_details": [], "Mismatched_details": [ "\n- LaTeX uses sum over all tokens while averages loss per token.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - Attn_States (torch.Tensor, dtype=torch.float32, shape=[batch_size, Num of Layers, Num of tokens, hidden size]): Tensor of attention states from the model.\n - Attn_States_reference (torch.Tensor, dtype=torch.float32, shape=[batch_size, Num of Layers, Num of tokens, hidden size]): Tensor of attention states from the reference model.\n - permutaion_batch (torch.Tensor, dtype=torch.int, shape=[batch size, Number of samples]): Permutation indices for the input batch, the number of samples corresponds to the total of in-context examples plus one test case.\n For instance, if permutaion_batch[0] = [4, 3, 2, 5, 1, 0, 6, 7, 8]. Here for the first input within the batch, sample 4 occupies the first position, sample 3 occupies the second position and sample 2 occupies the third position and etc. \n - permutaion_reference (torch.Tensor, dtype=torch.int, shape = [batch size, Number of samples]): Permutation indices for the reference data, each number denote a sample.\n - index_batch (torch.Tensor, dtype=torch.int, shape = [batch size, Number of samples, 2]): This tensor specifies the start and end indices for each example within input batch.\n For instance, index_batch[0][0][0] and index_batch[0][0][1] represents the start and end index of the sample 0 within the first input.\n - index_reference (torch.Tensor, dtype=torch.int, shape = [batch size, Number of samples, 2]): This tensor specifies the start and end indices for each example within reference batch.\n - batch_size (int): Number of samples in the batch.\n - Temperature (float): Temperature scaling parameter for the contrastive loss. Default is 0.1.\n", "Arguments_list": [ { "name": "Attn_States", "string": "- Attn_States (torch.Tensor, dtype=torch.float32, shape=[batch_size, Num of Layers, Num of tokens, hidden size]): Tensor of attention states from the model.", "dependency": null }, { "name": "Attn_States_reference", "string": "- Attn_States_reference (torch.Tensor, dtype=torch.float32, shape=[batch_size, Num of Layers, Num of tokens, hidden size]): Tensor of attention states from the reference model.", "dependency": null }, { "name": "permutaion_batch", "string": "\n- permutaion_batch (torch.Tensor, dtype=torch.int, shape=[batch size, Number of samples]): Permutation indices for the input batch, the number of samples corresponds to the total of in-context examples plus one test case.\n For instance, if permutaion_batch[0] = [4, 3, 2, 5, 1, 0, 6, 7, 8]. Here for the first input within the batch, sample 4 occupies the first position, sample 3 occupies the second position and sample 2 occupies the third position and etc.\n", "dependency": null }, { "name": "permutaion_reference", "string": "- permutaion_reference (torch.Tensor, dtype=torch.int, shape = [batch size, Number of samples]): Permutation indices for the reference data, each number denote a sample.", "dependency": null }, { "name": "index_batch", "string": "\n- index_batch (torch.Tensor, dtype=torch.int, shape = [batch size, Number of samples, 2]): This tensor specifies the start and end indices for each example within input batch.\n For instance, index_batch[0][0][0] and index_batch[0][0][1] represents the start and end index of the sample 0 within the first input.\n", "dependency": null }, { "name": "index_reference", "string": "- index_reference (torch.Tensor, dtype=torch.int, shape = [batch size, Number of samples, 2]): This tensor specifies the start and end indices for each example within reference batch.", "dependency": null }, { "name": "batch_size", "string": "- batch_size (int): Number of samples in the batch.", "dependency": null }, { "name": "Temperature", "string": "- Temperature (float): Temperature scaling parameter for the contrastive loss. Default is 0.1.", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n Intra File Dependencies: \n - None\n \n Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.nn.CosineSimilarity\n - torch.exp\n - torch.log\n - torch.mean\n", "list": [ "torch.nn.CosineSimilarity", "torch.exp", "torch.log", "torch.mean" ] }, "Return": { "Return_String": "\nOutput Variables: \n - loss_contrast (float): Averaged information augmentation loss across all samples.\n", "Return_list": [ { "name": "loss_contrast", "string": "- loss_contrast (float): Averaged information augmentation loss across all samples.", "dependency": null } ] }, "ori_python_file": "import fire\nimport random\nimport torch\nimport torch.optim as optim\nimport torch.nn as nn\nfrom peft import get_peft_model, prepare_model_for_int8_training\nfrom torch.optim.lr_scheduler import StepLR\nfrom transformers import LlamaTokenizer\nfrom LLama import (\n LlamaForCausalLM,\n)\nimport os\nfrom llama_recipes.configs import fsdp_config as FSDP_CONFIG\nfrom trainingconfig import train_config as TRAIN_CONFIG\nfrom llama_recipes.utils.config_utils import (\n update_config,\n generate_peft_config,\n)\nfrom concatenator import get_dataloader_kwargs\nfrom llama_recipes.utils.train_utils import (\n print_model_size,\n setup,\n)\nimport shutil\nfrom MyDataset.IncontextData import InContextDataTrain\nimport time\nimport torch.distributed as dist\nfrom torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler\nfrom tqdm import tqdm\nfrom transformers import LlamaTokenizer\nfrom llama_recipes.utils.memory_utils import MemoryTrace\n\ndef load_model(kwargs, train_config):\n if kwargs['Model'] == \"LLama-7B\":\n train_config.model_name = 'meta-llama/Llama-2-7b-chat-hf'\n elif kwargs['Model'] == \"LLama-13B\":\n train_config.model_name = 'meta-llama/Llama-2-13b-chat-hf'\n elif kwargs['Model'] == \"Vicuna-7B\":\n train_config.model_name = 'lmsys/vicuna-7b-v1.5'\n elif kwargs['Model'] == \"Vicuna-13B\":\n train_config.model_name = 'lmsys/vicuna-13b-v1.5'\n if kwargs['Model'] == \"LLama-7B\":\n model = LlamaForCausalLM.from_pretrained(\n train_config.model_name,\n load_in_4bit=True if train_config.quantization else None,\n device_map=\"auto\" if train_config.quantization else None,\n use_cache = False,\n )\n elif kwargs['Model'] == \"LLama-13B\":\n model = LlamaForCausalLM.from_pretrained(\n train_config.model_name,\n load_in_4bit=True if train_config.quantization else None,\n device_map=\"auto\" if train_config.quantization else None,\n use_cache = False,\n )\n elif kwargs['Model'] == \"Vicuna-7B\":\n model = LlamaForCausalLM.from_pretrained(\n train_config.model_name,\n load_in_4bit=True if train_config.quantization else None,\n device_map=\"auto\" if train_config.quantization else None,\n use_cache = False,\n )\n elif kwargs['Model'] == \"Vicuna-13B\":\n model = LlamaForCausalLM.from_pretrained(\n train_config.model_name,\n load_in_4bit=True if train_config.quantization else None,\n device_map=\"auto\" if train_config.quantization else None,\n use_cache = False,\n )\n if kwargs['Model'] == \"LLama-7B\":\n model_gold = LlamaForCausalLM.from_pretrained(\n train_config.model_name,\n load_in_4bit=True if train_config.quantization else None,\n device_map=\"auto\" if train_config.quantization else None,\n use_cache = False,\n )\n elif kwargs['Model'] == \"LLama-13B\":\n model_gold = LlamaForCausalLM.from_pretrained(\n train_config.model_name,\n load_in_4bit=True if train_config.quantization else None,\n device_map=\"auto\" if train_config.quantization else None,\n use_cache = False,\n )\n elif kwargs['Model'] == \"Vicuna-7B\":\n model_gold = LlamaForCausalLM.from_pretrained(\n train_config.model_name,\n load_in_4bit=True if train_config.quantization else None,\n device_map=\"auto\" if train_config.quantization else None,\n use_cache = False,\n )\n elif kwargs['Model'] == \"Vicuna-13B\":\n model_gold = LlamaForCausalLM.from_pretrained(\n train_config.model_name,\n load_in_4bit=True if train_config.quantization else None,\n device_map=\"auto\" if train_config.quantization else None,\n use_cache = False,\n )\n if kwargs['Model'] == \"LLama-7B\":\n tokenizer = LlamaTokenizer.from_pretrained(train_config.model_name)\n tokenizer.pad_token_id = tokenizer.eos_token_id\n elif kwargs['Model'] == \"LLama-13B\":\n tokenizer = LlamaTokenizer.from_pretrained(train_config.model_name)\n tokenizer.pad_token_id = tokenizer.eos_token_id\n elif kwargs['Model'] == \"Vicuna-7B\":\n tokenizer = LlamaTokenizer.from_pretrained(train_config.model_name)\n tokenizer.pad_token_id = tokenizer.eos_token_id\n elif kwargs['Model'] == \"Vicuna-13B\":\n tokenizer = LlamaTokenizer.from_pretrained(train_config.model_name)\n tokenizer.pad_token_id = tokenizer.eos_token_id\n return model, model_gold, tokenizer\n\ndef calculate_information_augmentation_loss(Attn_States, Attn_States_gold, permutaion_batch, permutaion_gold, index_batch, index_gold, batch_size, Temperature=0.1):\n loss_contrast = 0\n numPerSam = batch_size\n for i in range(0, batch_size, numPerSam):\n senGold = dict()\n senOri = dict()\n senGold['0'] = dict()\n senOri['0'] = dict()\n for m in range(10):\n senGold[str(m)] = dict()\n senOri[str(m)] = dict()\n for j in range(numPerSam):\n permutationTmp = permutaion_batch[i + j]\n for m in range(permutationTmp.shape[0] - 1):\n if str(int(permutationTmp[m])) in senOri.keys():\n if str(m) not in senOri[str(int(permutationTmp[m]))].keys():\n senOri[str(int(permutationTmp[m]))][str(m)] = list()\n senOri[str(int(permutationTmp[m]))][str(m)].append(\n Attn_States[i + j, -1, index_batch[i + j][m][0] : index_batch[i + j][m][1], :].reshape(-1, Attn_States.shape[-1])\n )\n for j in range(numPerSam):\n permutationTmp = permutaion_gold[i + j]\n senGold[str(int(permutationTmp[-2]))] = (\n Attn_States_gold[i + j, -1, index_gold[i + j][-2][0] : index_gold[i + j][-2][1], :]\n .reshape(-1, Attn_States.shape[-1])\n )\n cos = nn.CosineSimilarity(dim=1)\n num = 0\n for j in senOri.keys():\n if senGold[j] != {}:\n for m in senOri[j].keys():\n for k in range(len(senOri[j][m])):\n query = senOri[j][m][k]\n key = senGold[j]\n multi = cos(query, key)\n multi /= Temperature\n positive = torch.exp(multi)\n multiNeg = cos(query, query.clone().detach())\n multiNeg /= Temperature\n negative = torch.exp(multiNeg)\n loss_tmp = -torch.log(positive / (positive + negative))\n loss_tmp = torch.mean(loss_tmp)\n loss_contrast += loss_tmp\n num += 1\n loss_contrast /= num\n return loss_contrast\n\ndef calculate_consistency_enhancement_loss(Hidden_states, batch_size, index):\n Loss_Consistency = 0\n Hidden1 = list()\n Hidden2 = list()\n Hiddenstates = list()\n for i in range(0, batch_size):\n Hiddenstates.append(Hidden_states[i][index[i]])\n gold = torch.stack(Hiddenstates, dim=0).mean(dim=0)\n for m in range(batch_size):\n Hidden1.append(Hiddenstates[m])\n Hidden2.append(gold)\n Hidden1 = torch.cat(Hidden1, dim=0)\n Hidden2 = torch.cat(Hidden2, dim=0)\n Target = torch.ones(Hidden1.shape[0]).to(Hidden1.device)\n Hidden2 = Hidden2.to(Hidden1.device)\n loss_fn_consistency = torch.nn.CosineEmbeddingLoss()\n Loss_Consistency = loss_fn_consistency(Hidden1, Hidden2, Target)\n return Loss_Consistency\n\ndef train(model, model_gold, train_dataloader, gold_dataloader, optimizer, lr_scheduler, gradient_accumulation_steps, train_config, TestCode):\n if train_config.use_fp16 and train_config.enable_fsdp:\n scaler = ShardedGradScaler()\n elif train_config.use_fp16 and not train_config.enable_fsdp:\n scaler = torch.cuda.amp.GradScaler()\n train_prep = []\n train_loss = []\n epoch_times = []\n Count = 0\n for epoch in range(train_config.num_epochs):\n epoch_start_time = time.perf_counter()\n with MemoryTrace() as memtrace:\n model.train()\n total_loss = 0.0\n total_length = len(gold_dataloader)//gradient_accumulation_steps\n pbar = tqdm(colour=\"blue\", desc=f\"Training Epoch: {epoch}\", total=total_length)\n for (step, (batch, batch_gold)) in enumerate(zip(train_dataloader, gold_dataloader)):\n for key in batch_gold.keys():\n batch_gold[key] = batch_gold[key].to(\"cuda\")\n batch[key] = batch[key].to(\"cuda\")\n output = model(**batch)\n with torch.no_grad():\n outputgold = model_gold(**batch_gold)\n Attn_States = output.Attn_states\n Attn_States_gold = outputgold.Attn_states\n Attn_States = torch.stack(Attn_States, dim=1)\n Attn_States_gold = torch.stack(Attn_States_gold, dim=1)\n batch_size = int(batch_gold.data['input_ids'].shape[0])\n index = list()\n for i in range(0, batch_size):\n index.append(batch.data['prompt_len'][i] - batch.data['label_len'][i] - 1)\n loss_contrast = calculate_information_augmentation_loss(Attn_States, Attn_States_gold, batch.data['permutation'], batch_gold.data['permutation'], batch.data['Index_Sample'], batch_gold.data['Index_Sample'], batch_size)\n Loss_Consistency = calculate_consistency_enhancement_loss(output.Hidden_states, batch_size, index)\n loss_main = output.loss\n loss = loss_contrast + Loss_Consistency\n loss = loss / gradient_accumulation_steps\n if total_loss != 0:\n total_loss = total_loss.to(loss.device)\n total_loss += loss.detach().float()\n if train_config.use_fp16:\n scaler.scale(loss).backward()\n if (step + 1) % gradient_accumulation_steps == 0 or step == len(gold_dataloader) - 1:\n scaler.step(optimizer)\n scaler.update()\n optimizer.zero_grad()\n pbar.update(step//gradient_accumulation_steps)\n else:\n loss.backward()\n if (step + 1) % gradient_accumulation_steps == 0 or step == len(gold_dataloader) - 1:\n optimizer.step()\n optimizer.zero_grad()\n pbar.update(step//gradient_accumulation_steps)\n pbar.set_description(f\"Training Epoch: {epoch}/{train_config.num_epochs}, step {step}/{len(gold_dataloader)}completed (loss_main: {loss_main.detach().float()}) loss_constrast: {loss_contrast.detach().float()} Loss_Consistency: {Loss_Consistency.detach().float()}\")\n if TestCode:\n if Count == 10:\n return\n Count += 1\n epoch_end_time = time.perf_counter()-epoch_start_time\n epoch_times.append(epoch_end_time)\n if torch.cuda.device_count() > 1:\n dist.all_reduce(total_loss, op=dist.ReduceOp.SUM)\n train_epoch_loss = total_loss / len(gold_dataloader)\n train_perplexity = torch.exp(train_epoch_loss)\n train_prep.append(train_perplexity)\n train_loss.append(train_epoch_loss)\n print(f\"Max CUDA memory allocated was {memtrace.peak} GB\")\n print(f\"Max CUDA memory reserved was {memtrace.max_reserved} GB\")\n print(f\"Peak active CUDA memory was {memtrace.peak_active_gb} GB\")\n print(f\"Cuda Malloc retires : {memtrace.cuda_malloc_retires}\")\n print(f\"CPU Total Peak Memory consumed during the train (max): {memtrace.cpu_peaked + memtrace.cpu_begin} GB\")\n lr_scheduler.step()\n model.save_pretrained(train_config.output_dir, save_adapter=True, save_config=True)\n train_config.run_validation = False\n print(f\"Epoch {epoch+1}: train_perplexity={train_perplexity:.4f}, train_epoch_loss={train_epoch_loss:.4f}, epoch time {epoch_end_time}s\")\n\ndef main(**kwargs):\n train_config, fsdp_config = TRAIN_CONFIG(), FSDP_CONFIG()\n update_config((train_config, fsdp_config), **kwargs)\n num_sample = int(kwargs['NumTrain'])\n if kwargs['Dataset'] == 'SST5':\n train_config.output_dir = 'savedmodel/SST-5/SST5_' + str(num_sample) + '_'+kwargs['Model'] + '_Lora8_InfoAC'\n elif kwargs['Dataset'] == 'SST2':\n train_config.output_dir = 'savedmodel/SST-2/SST2_' + str(num_sample) + '_'+kwargs['Model'] + '_Lora8_InfoAC'\n elif kwargs['Dataset'] == 'Round':\n train_config.output_dir = 'savedmodel/Round/Round_' + str(num_sample) + '_'+kwargs['Model'] + '_Lora8_InfoAC'\n elif kwargs['Dataset'] == 'Next':\n train_config.output_dir = 'savedmodel/Next/Next_' + str(num_sample) + '_'+kwargs['Model'] + '_Lora8_InfoAC'\n elif kwargs['Dataset'] == 'qqp':\n train_config.output_dir = 'savedmodel/qqp/qqp_' + str(num_sample) + '_'+kwargs['Model'] + '_Lora8_InfoAC'\n print(train_config.output_dir)\n torch.cuda.manual_seed(train_config.seed)\n torch.manual_seed(train_config.seed)\n random.seed(train_config.seed)\n model, model_gold, tokenizer = load_model(kwargs, train_config)\n print_model_size(model, train_config, 0)\n if train_config.quantization:\n model = prepare_model_for_int8_training(model)\n if train_config.use_peft:\n peft_config = generate_peft_config(train_config, kwargs)\n peft_config.target_modules = [\"q_proj\", \"v_proj\"]\n peft_config.r = 8\n peft_config.lora_alpha = 16\n print(peft_config.r)\n print(peft_config.target_modules)\n model = get_peft_model(model, peft_config)\n model.print_trainable_parameters()\n if kwargs['Model'] == \"LLama-7B\":\n model_dataset = \"LLama\"\n elif kwargs['Model'] == \"LLama-13B\":\n model_dataset = \"LLama\"\n elif kwargs['Model'] == \"Vicuna-7B\" or kwargs['Model'] == \"Vicuna-13B\":\n model_dataset = \"Vicuna\"\n else:\n model_dataset = kwargs['Model']\n if kwargs['Dataset'] == 'SST5':\n OutputTrain = \"MyDataset/SST-5/SST5-\" + model_dataset + \"-Pool100-Len10-Train.pickle\"\n OutputGoldTraincase = \"MyDataset/SST-5/SST5-\" + model_dataset + \"-Pool100-Len10-Gold.pickle\"\n elif kwargs['Dataset'] == 'SST2':\n OutputTrain = \"MyDataset/sst-2/SST2-\" + model_dataset + \"-Pool100-Len10-Train.pickle\"\n OutputGoldTraincase = \"MyDataset/sst-2/SST2-\" + model_dataset + \"-Pool100-Len10-Gold.pickle\"\n elif kwargs['Dataset'] == 'Round':\n OutputTrain = \"MyDataset/Round/Round-\" + model_dataset + \"-Pool10-Len10-Train.pickle\"\n OutputGoldTraincase = \"MyDataset/Round/Round-\" + model_dataset + \"-Pool10-Len10-Gold.pickle\"\n elif kwargs['Dataset'] == 'Next':\n OutputTrain = \"MyDataset/Next/Next-\" + model_dataset + \"-Pool10-Len10-Train.pickle\"\n OutputGoldTraincase = \"MyDataset/Next/Next-\" + model_dataset + \"-Pool10-Len10-Gold.pickle\"\n elif kwargs['Dataset'] == 'qqp':\n OutputTrain = \"MyDataset/qqp/qqp-\" + model_dataset + \"-Pool100-Len10-Train.pickle\"\n OutputGoldTraincase = \"MyDataset/qqp/qqp-\" + model_dataset + \"-Pool100-Len10-Gold.pickle\"\n Num = num_sample*train_config.batch_size_training\n dataset_train = InContextDataTrain(OutputTrain, Num, partition=\"train\")\n dataset_gold = InContextDataTrain(OutputGoldTraincase, Num, partition=\"train\")\n train_dl_kwargs = get_dataloader_kwargs(train_config, dataset_train, tokenizer, \"val\")\n train_dl_kwargs['batch_sampler'].shuffle = False\n train_dl_kwargs['batch_sampler'].batch_size = train_config.batch_size_training\n train_dataloader = torch.utils.data.DataLoader(\n dataset_train,\n num_workers=train_config.num_workers_dataloader,\n pin_memory=True,\n **train_dl_kwargs,\n )\n gold_dl_kwargs = get_dataloader_kwargs(train_config, dataset_gold, tokenizer, \"val\")\n gold_dl_kwargs['batch_sampler'].shuffle = False\n gold_dl_kwargs['batch_sampler'].batch_size = train_config.batch_size_training\n gold_dataloader = torch.utils.data.DataLoader(\n dataset_gold,\n num_workers=train_config.num_workers_dataloader,\n pin_memory=True,\n **gold_dl_kwargs,\n )\n optimizer = optim.AdamW(\n model.parameters(),\n lr=train_config.lr,\n weight_decay=train_config.weight_decay,\n )\n scheduler = StepLR(optimizer, step_size=1, gamma=train_config.gamma)\n if os.path.exists('SavedOutputRun'):\n shutil.rmtree('SavedOutputRun')\n train(\n model,\n model_gold,\n train_dataloader,\n gold_dataloader,\n optimizer,\n scheduler,\n train_config.gradient_accumulation_steps,\n train_config,\n kwargs['TestCode']\n )\n\nif __name__ == \"__main__\":\n fire.Fire(main)" }, { "task_id": 1, "indent": 1, "completion_path": "./main.py", "script": "\npython main.py --use_peft --quantization --NumTrain 1000 --Model='LLama-7B' --Dataset='SST5'\n", "latex_code": "\n\\subsubsection{Consistency Enhancement}\nFor all inputs $I$ within a batch, we aim for the model's predicted results to exhibit consistency.\nAs the LoRA adaptation is applied, the parameters of the classification head remain fixed during training.\nThus, we enforce similarity among the hidden representations of the last token across the input batch $I$, which are then input into the classification head to predict the next output tokens.\nThis approach is designed to enhance the consistency of the model's output.\n\\begin{equation}\n\\mathcal{L}_{\\text{con}}=\\sum_{i=1}^{m} (1-\\text{cos}(\\bm{H}[i,-1], \\bm{H_a})),\n\\end{equation}\n\\begin{equation}\n\\bm{H_a}= \\frac{\\sum_{i=1}^{m}{\\bm{H}[i,-1]}}{m}, \n\\end{equation}\n", "namespace": "main.calculate_consistency_enhancement_loss", "type": "function", "signature_position": [ 159, 159 ], "signature": "\ndef calculate_consistency_enhancement_loss(Hidden_states, batch_size, index):\n", "body_position": [ 160, 176 ], "ReferenceCode_With_Comments": "\nLoss_Consistency = 0\nHidden1 = list()\nHidden2 = list()\nHiddenstates = list()\n\n# ---------------------------------------------------------------------------\n# Snippet 1: Extract the representations of the target token for each input in the batch. \n# This corresponds to \\(\\bm{H}[i,-1]\\) in the LaTeX snippet, but is generalized here using the provided indices.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nfor i in range(0, batch_size):\n Hiddenstates.append(Hidden_states[i][index[i]])\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Compute the average representation \\(\\bm{H_a}\\) across all inputs.\n# In the LaTeX, \\(\\bm{H_a}\\) is defined by:\n# \\(\\bm{H_a}= \\frac{1}{m}\\sum_{i=1}^{m}{\\bm{H}[i,-1]}\\).\n# This ensures there is a single \"gold\" vector against which each hidden\n# representation is compared.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\ngold = torch.stack(Hiddenstates, dim=0).mean(dim=0)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Compute the consistency loss for every element in the batch, \n# which conceptually aligns with the LaTeX equation \\(\\mathcal{L}_{\\text{con}}\\). \n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nfor m in range(batch_size):\n Hidden1.append(Hiddenstates[m])\n Hidden2.append(gold)\nHidden1 = torch.cat(Hidden1, dim=0)\nHidden2 = torch.cat(Hidden2, dim=0)\nTarget = torch.ones(Hidden1.shape[0]).to(Hidden1.device)\nHidden2 = Hidden2.to(Hidden1.device)\n\nloss_fn_consistency = torch.nn.CosineEmbeddingLoss()\nLoss_Consistency = loss_fn_consistency(Hidden1, Hidden2, Target)\n\nreturn Loss_Consistency\n# [End Snippet 3]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - the consistency loss should be averaged over the batch.\n \n Mismatched Details:\n - None\n", "Missing_details": [ "\n- the consistency loss should be averaged over the batch.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - Hidden_states (torch.Tensor, dtype=torch.int, shape = [batch size, Number of tokens, Hidden Size ]): Hidden States output from LLM.\n - batch_size (int): Number of samples in the batch.\n - index (list): A list of indices corresponding to the predicted tokens for each sample in the batch.\n", "Arguments_list": [ { "name": "Hidden_states", "string": "- Hidden_states (torch.Tensor, dtype=torch.int, shape = [batch size, Number of tokens, Hidden Size ]): Hidden States output from LLM.", "dependency": null }, { "name": "batch_size", "string": "- batch_size (int): Number of samples in the batch.", "dependency": null }, { "name": "index", "string": "- index (list): A list of indices corresponding to the predicted tokens for each sample in the batch.", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n Intra File Dependencies: \n - None\n \n Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs: \n - torch.nn.CosineEmbeddingLoss\n - torch.stack\n - torch.cat\n - torch.ones\n", "list": [ "torch.nn.CosineEmbeddingLoss", "torch.stack", "torch.cat", "torch.ones" ] }, "Return": { "Return_String": "\nOutput Variables:\n - Loss_Consistency (float): \n - Scalar tensor representing the computed consistency enhancement loss, which encourages the hidden representations of the target tokens to be similar across the batch.\n", "Return_list": [ { "name": "Loss_Consistency", "string": "\n- Loss_Consistency (float): \n - Scalar tensor representing the computed consistency enhancement loss, which encourages the hidden representations of the target tokens to be similar across the batch.\n", "dependency": null } ] }, "ori_python_file": "import fire\nimport random\nimport torch\nimport torch.optim as optim\nimport torch.nn as nn\nfrom peft import get_peft_model, prepare_model_for_int8_training\nfrom torch.optim.lr_scheduler import StepLR\nfrom transformers import LlamaTokenizer\nfrom LLama import (\n LlamaForCausalLM,\n)\nimport os\nfrom llama_recipes.configs import fsdp_config as FSDP_CONFIG\nfrom trainingconfig import train_config as TRAIN_CONFIG\nfrom llama_recipes.utils.config_utils import (\n update_config,\n generate_peft_config,\n)\nfrom concatenator import get_dataloader_kwargs\nfrom llama_recipes.utils.train_utils import (\n print_model_size,\n setup,\n)\nimport shutil\nfrom MyDataset.IncontextData import InContextDataTrain\nimport time\nimport torch.distributed as dist\nfrom torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler\nfrom tqdm import tqdm\nfrom transformers import LlamaTokenizer\nfrom llama_recipes.utils.memory_utils import MemoryTrace\n\ndef load_model(kwargs, train_config):\n if kwargs['Model'] == \"LLama-7B\":\n train_config.model_name = 'meta-llama/Llama-2-7b-chat-hf'\n elif kwargs['Model'] == \"LLama-13B\":\n train_config.model_name = 'meta-llama/Llama-2-13b-chat-hf'\n elif kwargs['Model'] == \"Vicuna-7B\":\n train_config.model_name = 'lmsys/vicuna-7b-v1.5'\n elif kwargs['Model'] == \"Vicuna-13B\":\n train_config.model_name = 'lmsys/vicuna-13b-v1.5'\n if kwargs['Model'] == \"LLama-7B\":\n model = LlamaForCausalLM.from_pretrained(\n train_config.model_name,\n load_in_4bit=True if train_config.quantization else None,\n device_map=\"auto\" if train_config.quantization else None,\n use_cache = False,\n )\n elif kwargs['Model'] == \"LLama-13B\":\n model = LlamaForCausalLM.from_pretrained(\n train_config.model_name,\n load_in_4bit=True if train_config.quantization else None,\n device_map=\"auto\" if train_config.quantization else None,\n use_cache = False,\n )\n elif kwargs['Model'] == \"Vicuna-7B\":\n model = LlamaForCausalLM.from_pretrained(\n train_config.model_name,\n load_in_4bit=True if train_config.quantization else None,\n device_map=\"auto\" if train_config.quantization else None,\n use_cache = False,\n )\n elif kwargs['Model'] == \"Vicuna-13B\":\n model = LlamaForCausalLM.from_pretrained(\n train_config.model_name,\n load_in_4bit=True if train_config.quantization else None,\n device_map=\"auto\" if train_config.quantization else None,\n use_cache = False,\n )\n if kwargs['Model'] == \"LLama-7B\":\n model_gold = LlamaForCausalLM.from_pretrained(\n train_config.model_name,\n load_in_4bit=True if train_config.quantization else None,\n device_map=\"auto\" if train_config.quantization else None,\n use_cache = False,\n )\n elif kwargs['Model'] == \"LLama-13B\":\n model_gold = LlamaForCausalLM.from_pretrained(\n train_config.model_name,\n load_in_4bit=True if train_config.quantization else None,\n device_map=\"auto\" if train_config.quantization else None,\n use_cache = False,\n )\n elif kwargs['Model'] == \"Vicuna-7B\":\n model_gold = LlamaForCausalLM.from_pretrained(\n train_config.model_name,\n load_in_4bit=True if train_config.quantization else None,\n device_map=\"auto\" if train_config.quantization else None,\n use_cache = False,\n )\n elif kwargs['Model'] == \"Vicuna-13B\":\n model_gold = LlamaForCausalLM.from_pretrained(\n train_config.model_name,\n load_in_4bit=True if train_config.quantization else None,\n device_map=\"auto\" if train_config.quantization else None,\n use_cache = False,\n )\n if kwargs['Model'] == \"LLama-7B\":\n tokenizer = LlamaTokenizer.from_pretrained(train_config.model_name)\n tokenizer.pad_token_id = tokenizer.eos_token_id\n elif kwargs['Model'] == \"LLama-13B\":\n tokenizer = LlamaTokenizer.from_pretrained(train_config.model_name)\n tokenizer.pad_token_id = tokenizer.eos_token_id\n elif kwargs['Model'] == \"Vicuna-7B\":\n tokenizer = LlamaTokenizer.from_pretrained(train_config.model_name)\n tokenizer.pad_token_id = tokenizer.eos_token_id\n elif kwargs['Model'] == \"Vicuna-13B\":\n tokenizer = LlamaTokenizer.from_pretrained(train_config.model_name)\n tokenizer.pad_token_id = tokenizer.eos_token_id\n return model, model_gold, tokenizer\n\ndef calculate_information_augmentation_loss(Attn_States, Attn_States_gold, permutaion_batch, permutaion_gold, index_batch, index_gold, batch_size, Temperature=0.1):\n loss_contrast = 0\n numPerSam = batch_size\n for i in range(0, batch_size, numPerSam):\n senGold = dict()\n senOri = dict()\n senGold['0'] = dict()\n senOri['0'] = dict()\n for m in range(10):\n senGold[str(m)] = dict()\n senOri[str(m)] = dict()\n for j in range(numPerSam):\n permutationTmp = permutaion_batch[i + j]\n for m in range(permutationTmp.shape[0] - 1):\n if str(int(permutationTmp[m])) in senOri.keys():\n if str(m) not in senOri[str(int(permutationTmp[m]))].keys():\n senOri[str(int(permutationTmp[m]))][str(m)] = list()\n senOri[str(int(permutationTmp[m]))][str(m)].append(\n Attn_States[i + j, -1, index_batch[i + j][m][0] : index_batch[i + j][m][1], :].reshape(-1, Attn_States.shape[-1])\n )\n for j in range(numPerSam):\n permutationTmp = permutaion_gold[i + j]\n senGold[str(int(permutationTmp[-2]))] = (\n Attn_States_gold[i + j, -1, index_gold[i + j][-2][0] : index_gold[i + j][-2][1], :]\n .reshape(-1, Attn_States.shape[-1])\n )\n cos = nn.CosineSimilarity(dim=1)\n num = 0\n for j in senOri.keys():\n if senGold[j] != {}:\n for m in senOri[j].keys():\n for k in range(len(senOri[j][m])):\n query = senOri[j][m][k]\n key = senGold[j]\n multi = cos(query, key)\n multi /= Temperature\n positive = torch.exp(multi)\n multiNeg = cos(query, query.clone().detach())\n multiNeg /= Temperature\n negative = torch.exp(multiNeg)\n loss_tmp = -torch.log(positive / (positive + negative))\n loss_tmp = torch.mean(loss_tmp)\n loss_contrast += loss_tmp\n num += 1\n loss_contrast /= num\n return loss_contrast\n\ndef calculate_consistency_enhancement_loss(Hidden_states, batch_size, index):\n Loss_Consistency = 0\n Hidden1 = list()\n Hidden2 = list()\n Hiddenstates = list()\n for i in range(0, batch_size):\n Hiddenstates.append(Hidden_states[i][index[i]])\n gold = torch.stack(Hiddenstates, dim=0).mean(dim=0)\n for m in range(batch_size):\n Hidden1.append(Hiddenstates[m])\n Hidden2.append(gold)\n Hidden1 = torch.cat(Hidden1, dim=0)\n Hidden2 = torch.cat(Hidden2, dim=0)\n Target = torch.ones(Hidden1.shape[0]).to(Hidden1.device)\n Hidden2 = Hidden2.to(Hidden1.device)\n loss_fn_consistency = torch.nn.CosineEmbeddingLoss()\n Loss_Consistency = loss_fn_consistency(Hidden1, Hidden2, Target)\n return Loss_Consistency\n\ndef train(model, model_gold, train_dataloader, gold_dataloader, optimizer, lr_scheduler, gradient_accumulation_steps, train_config, TestCode):\n if train_config.use_fp16 and train_config.enable_fsdp:\n scaler = ShardedGradScaler()\n elif train_config.use_fp16 and not train_config.enable_fsdp:\n scaler = torch.cuda.amp.GradScaler()\n train_prep = []\n train_loss = []\n epoch_times = []\n Count = 0\n for epoch in range(train_config.num_epochs):\n epoch_start_time = time.perf_counter()\n with MemoryTrace() as memtrace:\n model.train()\n total_loss = 0.0\n total_length = len(gold_dataloader)//gradient_accumulation_steps\n pbar = tqdm(colour=\"blue\", desc=f\"Training Epoch: {epoch}\", total=total_length)\n for (step, (batch, batch_gold)) in enumerate(zip(train_dataloader, gold_dataloader)):\n for key in batch_gold.keys():\n batch_gold[key] = batch_gold[key].to(\"cuda\")\n batch[key] = batch[key].to(\"cuda\")\n output = model(**batch)\n with torch.no_grad():\n outputgold = model_gold(**batch_gold)\n Attn_States = output.Attn_states\n Attn_States_gold = outputgold.Attn_states\n Attn_States = torch.stack(Attn_States, dim=1)\n Attn_States_gold = torch.stack(Attn_States_gold, dim=1)\n batch_size = int(batch_gold.data['input_ids'].shape[0])\n index = list()\n for i in range(0, batch_size):\n index.append(batch.data['prompt_len'][i] - batch.data['label_len'][i] - 1)\n loss_contrast = calculate_information_augmentation_loss(Attn_States, Attn_States_gold, batch.data['permutation'], batch_gold.data['permutation'], batch.data['Index_Sample'], batch_gold.data['Index_Sample'], batch_size)\n Loss_Consistency = calculate_consistency_enhancement_loss(output.Hidden_states, batch_size, index)\n loss_main = output.loss\n loss = loss_contrast + Loss_Consistency\n loss = loss / gradient_accumulation_steps\n if total_loss != 0:\n total_loss = total_loss.to(loss.device)\n total_loss += loss.detach().float()\n if train_config.use_fp16:\n scaler.scale(loss).backward()\n if (step + 1) % gradient_accumulation_steps == 0 or step == len(gold_dataloader) - 1:\n scaler.step(optimizer)\n scaler.update()\n optimizer.zero_grad()\n pbar.update(step//gradient_accumulation_steps)\n else:\n loss.backward()\n if (step + 1) % gradient_accumulation_steps == 0 or step == len(gold_dataloader) - 1:\n optimizer.step()\n optimizer.zero_grad()\n pbar.update(step//gradient_accumulation_steps)\n pbar.set_description(f\"Training Epoch: {epoch}/{train_config.num_epochs}, step {step}/{len(gold_dataloader)}completed (loss_main: {loss_main.detach().float()}) loss_constrast: {loss_contrast.detach().float()} Loss_Consistency: {Loss_Consistency.detach().float()}\")\n if TestCode:\n if Count == 10:\n return\n Count += 1\n epoch_end_time = time.perf_counter()-epoch_start_time\n epoch_times.append(epoch_end_time)\n if torch.cuda.device_count() > 1:\n dist.all_reduce(total_loss, op=dist.ReduceOp.SUM)\n train_epoch_loss = total_loss / len(gold_dataloader)\n train_perplexity = torch.exp(train_epoch_loss)\n train_prep.append(train_perplexity)\n train_loss.append(train_epoch_loss)\n print(f\"Max CUDA memory allocated was {memtrace.peak} GB\")\n print(f\"Max CUDA memory reserved was {memtrace.max_reserved} GB\")\n print(f\"Peak active CUDA memory was {memtrace.peak_active_gb} GB\")\n print(f\"Cuda Malloc retires : {memtrace.cuda_malloc_retires}\")\n print(f\"CPU Total Peak Memory consumed during the train (max): {memtrace.cpu_peaked + memtrace.cpu_begin} GB\")\n lr_scheduler.step()\n model.save_pretrained(train_config.output_dir, save_adapter=True, save_config=True)\n train_config.run_validation = False\n print(f\"Epoch {epoch+1}: train_perplexity={train_perplexity:.4f}, train_epoch_loss={train_epoch_loss:.4f}, epoch time {epoch_end_time}s\")\n\ndef main(**kwargs):\n train_config, fsdp_config = TRAIN_CONFIG(), FSDP_CONFIG()\n update_config((train_config, fsdp_config), **kwargs)\n num_sample = int(kwargs['NumTrain'])\n if kwargs['Dataset'] == 'SST5':\n train_config.output_dir = 'savedmodel/SST-5/SST5_' + str(num_sample) + '_'+kwargs['Model'] + '_Lora8_InfoAC'\n elif kwargs['Dataset'] == 'SST2':\n train_config.output_dir = 'savedmodel/SST-2/SST2_' + str(num_sample) + '_'+kwargs['Model'] + '_Lora8_InfoAC'\n elif kwargs['Dataset'] == 'Round':\n train_config.output_dir = 'savedmodel/Round/Round_' + str(num_sample) + '_'+kwargs['Model'] + '_Lora8_InfoAC'\n elif kwargs['Dataset'] == 'Next':\n train_config.output_dir = 'savedmodel/Next/Next_' + str(num_sample) + '_'+kwargs['Model'] + '_Lora8_InfoAC'\n elif kwargs['Dataset'] == 'qqp':\n train_config.output_dir = 'savedmodel/qqp/qqp_' + str(num_sample) + '_'+kwargs['Model'] + '_Lora8_InfoAC'\n print(train_config.output_dir)\n torch.cuda.manual_seed(train_config.seed)\n torch.manual_seed(train_config.seed)\n random.seed(train_config.seed)\n model, model_gold, tokenizer = load_model(kwargs, train_config)\n print_model_size(model, train_config, 0)\n if train_config.quantization:\n model = prepare_model_for_int8_training(model)\n if train_config.use_peft:\n peft_config = generate_peft_config(train_config, kwargs)\n peft_config.target_modules = [\"q_proj\", \"v_proj\"]\n peft_config.r = 8\n peft_config.lora_alpha = 16\n print(peft_config.r)\n print(peft_config.target_modules)\n model = get_peft_model(model, peft_config)\n model.print_trainable_parameters()\n if kwargs['Model'] == \"LLama-7B\":\n model_dataset = \"LLama\"\n elif kwargs['Model'] == \"LLama-13B\":\n model_dataset = \"LLama\"\n elif kwargs['Model'] == \"Vicuna-7B\" or kwargs['Model'] == \"Vicuna-13B\":\n model_dataset = \"Vicuna\"\n else:\n model_dataset = kwargs['Model']\n if kwargs['Dataset'] == 'SST5':\n OutputTrain = \"MyDataset/SST-5/SST5-\" + model_dataset + \"-Pool100-Len10-Train.pickle\"\n OutputGoldTraincase = \"MyDataset/SST-5/SST5-\" + model_dataset + \"-Pool100-Len10-Gold.pickle\"\n elif kwargs['Dataset'] == 'SST2':\n OutputTrain = \"MyDataset/sst-2/SST2-\" + model_dataset + \"-Pool100-Len10-Train.pickle\"\n OutputGoldTraincase = \"MyDataset/sst-2/SST2-\" + model_dataset + \"-Pool100-Len10-Gold.pickle\"\n elif kwargs['Dataset'] == 'Round':\n OutputTrain = \"MyDataset/Round/Round-\" + model_dataset + \"-Pool10-Len10-Train.pickle\"\n OutputGoldTraincase = \"MyDataset/Round/Round-\" + model_dataset + \"-Pool10-Len10-Gold.pickle\"\n elif kwargs['Dataset'] == 'Next':\n OutputTrain = \"MyDataset/Next/Next-\" + model_dataset + \"-Pool10-Len10-Train.pickle\"\n OutputGoldTraincase = \"MyDataset/Next/Next-\" + model_dataset + \"-Pool10-Len10-Gold.pickle\"\n elif kwargs['Dataset'] == 'qqp':\n OutputTrain = \"MyDataset/qqp/qqp-\" + model_dataset + \"-Pool100-Len10-Train.pickle\"\n OutputGoldTraincase = \"MyDataset/qqp/qqp-\" + model_dataset + \"-Pool100-Len10-Gold.pickle\"\n Num = num_sample*train_config.batch_size_training\n dataset_train = InContextDataTrain(OutputTrain, Num, partition=\"train\")\n dataset_gold = InContextDataTrain(OutputGoldTraincase, Num, partition=\"train\")\n train_dl_kwargs = get_dataloader_kwargs(train_config, dataset_train, tokenizer, \"val\")\n train_dl_kwargs['batch_sampler'].shuffle = False\n train_dl_kwargs['batch_sampler'].batch_size = train_config.batch_size_training\n train_dataloader = torch.utils.data.DataLoader(\n dataset_train,\n num_workers=train_config.num_workers_dataloader,\n pin_memory=True,\n **train_dl_kwargs,\n )\n gold_dl_kwargs = get_dataloader_kwargs(train_config, dataset_gold, tokenizer, \"val\")\n gold_dl_kwargs['batch_sampler'].shuffle = False\n gold_dl_kwargs['batch_sampler'].batch_size = train_config.batch_size_training\n gold_dataloader = torch.utils.data.DataLoader(\n dataset_gold,\n num_workers=train_config.num_workers_dataloader,\n pin_memory=True,\n **gold_dl_kwargs,\n )\n optimizer = optim.AdamW(\n model.parameters(),\n lr=train_config.lr,\n weight_decay=train_config.weight_decay,\n )\n scheduler = StepLR(optimizer, step_size=1, gamma=train_config.gamma)\n if os.path.exists('SavedOutputRun'):\n shutil.rmtree('SavedOutputRun')\n train(\n model,\n model_gold,\n train_dataloader,\n gold_dataloader,\n optimizer,\n scheduler,\n train_config.gradient_accumulation_steps,\n train_config,\n kwargs['TestCode']\n )\n\nif __name__ == \"__main__\":\n fire.Fire(main)" } ] }, { "paper_id": 2, "paper_details": { "title": "Breaking the Ceiling of the LLM Community by Treating Token Generation as a Classification for Ensembling", "url": "https://arxiv.org/abs/2406.12585" }, "repo_original_url": "https://github.com/yaoching0/gac", "project_path": "Benchmark/2-Breaking/GaC-main", "enviorment_name": "gac_env", "file_organization": "\nGaC-main/\n call.py\n example_configs/\n example_ensemble_every_step.yaml\n example_thresholded_ensemble.yaml\n tested_models.yaml\n gac_api_server.py\n LICENSE\n log/\n logfile.log\n main.py\n pics/\n overview.png\n README.md\n requirements.txt\n utils/\n gac_gen_call.py\n gac_gen_utils.py\n __init__.py\n logger.py\n ray_actor.py\n", "latex_code_path": "Benchmark/2-Breaking/Breaking_the_Ceiling_of_the_LLM_Community_by_Treating_Token_Generation_as_a_Classification_for_Ensembling", "task_details": [ { "task_id": 0, "indent": 1, "latex_code": "\n\\subsection{Creating the Union Mapping}\n\\label{sec3-2}\nGiven \\(\\{\\textit{LLM}_1, \\textit{LLM}_2, \\ldots, \\textit{LLM}_n\\}\\) to ensemble, with their respective vocabularies \\(\\{V^1, V^2, \\ldots,\\allowbreak V^n\\}\\), we first take the union of the vocabularies:\n\\begin{equation}\n\\label{eq1}\nV^{U} = \\bigcup_{i=1}^{n} V^i.\n\\end{equation}\nDuring this process, we record the positions of tokens from \\(V^i\\) in \\(V^{U}\\) and create corresponding mapping matrices \\(\\mathbf{M}^{i} \\in \\{0,1\\}^{|V^i| \\times |V^{U}|}\\).\n", "completion_path": "./utils/gac_gen_utils.py", "namespace": "utils.gac_gen_utils.get_vocab_union_and_mapping", "type": "function", "signature_position": [ 226, 226 ], "body_position": [ 227, 283 ], "script": "\npython main.py\n", "ReferenceCode_With_Comments": "\nvocab_union = set()\ntokenizers_mapping = []\nbyte_mappings_list = []\n\n# ---------------------------------------------------------------------------\n# Snippet 1: Populate V^U with placeholders for all possible byte values <0x00>...<0xFF>.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nfor byte_val in range(256):\n vocab_union.add(f\"<0x{byte_val:02X}>\")\n# [End Snippet 1]\n\nfor tokenizer in tokenizers:\n vocab = tokenizer.get_vocab()\n token_set = set()\n mapping = {}\n\n # -----------------------------------------------------------------------\n # Snippet 2: Within each itertaion, Retrieve the byte-level mappings for this tokenizer and\n # add them to the global list. \n # -----------------------------------------------------------------------\n # [Begin Snippet 2]\n byte_mapping = check_byte_mappings(tokenizer)\n byte_mappings_list.append(byte_mapping)\n # [End Snippet 2]\n\n # -----------------------------------------------------------------------\n # Snippet 3: Within each itertaion, remove tokens from the tokenizer's vocabulary if they duplicate\n # the special byte placeholders, to ensure there are no collisions between\n # these byte placeholders and any internal tokens.\n # -----------------------------------------------------------------------\n # [Begin Snippet 3]\n for hex_token, token_id in byte_mapping.items():\n actual_tokens = [token for token, id in vocab.items() if id == token_id]\n if len(actual_tokens) != 1:\n raise ValueError(\n f\"Multiple tokens/ Zero token found for token ID {token_id} in tokenizer's vocabulary.\"\n )\n del vocab[actual_tokens[0]]\n # [End Snippet 3]\n\n # -----------------------------------------------------------------------\n # Snippet 4: Within each itertaion, detect the proportion of tokens that start with '\u0120' versus '\u2581', then replace these prefixes with spaces or newlines. \n # -----------------------------------------------------------------------\n # [Begin Snippet 4]\n g_prefix_count = sum(token.startswith(\"\u0120\") for token in vocab)\n u_prefix_count = sum(token.startswith(\"\u2581\") for token in vocab)\n\n if g_prefix_count > u_prefix_count:\n for token, token_id in vocab.items():\n processed_token = token.replace(\"\u0120\", \" \").replace(\"\u010a\", \"\\n\")\n token_set.add(processed_token)\n mapping[token_id] = processed_token\n else:\n for token, token_id in vocab.items():\n if token.startswith(\"\u2581\"):\n processed_token = token.replace(\"\u2581\", \" \")\n else:\n processed_token = token\n token_set.add(processed_token)\n mapping[token_id] = processed_token\n # [End Snippet 4]\n\n # -----------------------------------------------------------------------\n # Snippet 5: Combine the newly processed tokens for this tokenizer into the global union (vocab_union) and append the per-tokenizer mapping to tokenizers_mapping for downstream usage.\n # -----------------------------------------------------------------------\n # [Begin Snippet 5]\n vocab_union = vocab_union.union(token_set)\n tokenizers_mapping.append(mapping)\n # [End Snippet 5]\n\n# ---------------------------------------------------------------------------\n# Snippet 6: Incorporate the specialized byte mappings for each tokenizer into the final dictionary, resolving conflicts between placeholders and actual ASCII character tokens when necessary. This step ensures that each tokenizer\u2019s byte tokens are correctly positioned in V^U, fulfilling the \u201crecord the positions\u201d requirement from the LaTeX snippet.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 6]\nvocab_to_index = {token: i for i, token in enumerate(vocab_union)}\nindex_to_vocab = {index: token for token, index in vocab_to_index.items()}\nfor tokenizer, byte_mapping, mapping in zip(\n tokenizers, byte_mappings_list, tokenizers_mapping\n):\n for token_id, token in mapping.items():\n mapping[token_id] = vocab_to_index[token]\n\n bbpe_mapping = {\n **{f\"<0x{hex(i)[2:].upper()}>\": chr(i) for i in range(0x30, 0x3A)}, # '0'-'9'\n **{f\"<0x{hex(i)[2:].upper()}>\": chr(i) for i in range(0x41, 0x5B)}, # 'A'-'Z'\n **{f\"<0x{hex(i)[2:].upper()}>\": chr(i) for i in range(0x61, 0x7B)}, # 'a'-'z'\n }\n\n for hex_token, original_token_id in byte_mapping.items():\n if (\n not all(len(bm) == 128 for bm in byte_mappings_list)\n and len(byte_mapping) == 128\n ):\n if hex_token in bbpe_mapping:\n mapping[original_token_id] = vocab_to_index[bbpe_mapping[hex_token]]\n continue\n mapping[original_token_id] = vocab_to_index[hex_token]\n# [End Snippet 6]\nreturn vocab_union, tokenizers_mapping, index_to_vocab, byte_mappings_list\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - Explicit initialization of byte tokens: The LaTeX description does not mention pre-populating the unified vocabulary with all 256 byte tokens (<0x00> to <0xFF>), which is critical to avoid missing these tokens if they are absent in tokenizers' vocabularies.\n - Token normalization for whitespace prefixes: The LaTeX lacks details about replacing \"\u0120\" with spaces, \"\u010a\" with newlines, or handling \"\u2581\" prefixes, which the code should implement to unify token representations.\n - Conflict resolution for byte-overlapping tokens: The LaTeX does not specify the need to remove tokens from tokenizers' vocabularies that duplicate byte placeholder tokens (e.g., deleting actual tokens mapped to <0x..> IDs).\n - ASCII prioritization logic for byte tokens: The LaTeX omits the step where certain byte tokens (e.g., <0x41> for 'A') are mapped to their ASCII equivalents when tokenizers use BBPE encoding.\n - Ordering of the unified vocabulary: The union\u2019s token ordering should preserve the incremental insertion order with byte tokens first.\n\n Mismatched Details:\n - None\n", "Missing_details": [ "\n- Explicit initialization of byte tokens: The LaTeX description does not mention pre-populating the unified vocabulary with all 256 byte tokens (<0x00> to <0xFF>), which is critical to avoid missing these tokens if they are absent in tokenizers' vocabularies.\n", "\n- Token normalization for whitespace prefixes: The LaTeX lacks details about replacing \"\u0120\" with spaces, \"\u010a\" with newlines, or handling \"\u2581\" prefixes, which the reference code implements to unify token representations.\n", "\n- Conflict resolution for byte-overlapping tokens: The LaTeX does not specify the need to remove tokens from tokenizers' vocabularies that duplicate byte placeholder tokens (e.g., deleting actual tokens mapped to <0x..> IDs).\n", "\n- ASCII prioritization logic for byte tokens: The LaTeX omits the step where certain byte tokens (e.g., <0x41> for 'A') are mapped to their ASCII equivalents when tokenizers use BBPE encoding, as seen in the reference code\u2019s bbpe_mapping logic.\n", "\nOrdering of the unified vocabulary: The union\u2019s token ordering should preserve the incremental insertion order with byte tokens first.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - tokenizers (List[LLamaTokenizerFast]): \n A list of LLamaTokenizerFast objects, each with a 'get_vocab()' method that returns a dictionary of tokens and their corresponding IDs in the tokenizer's vocabulary.\n", "Arguments_list": [ { "name": "tokenizers", "string": "\n- tokenizers (List[LLamaTokenizerFast]): \n A list of LLamaTokenizerFast objects, each with a 'get_vocab()' method that returns a dictionary of tokens and their corresponding IDs in the tokenizer's vocabulary.\n", "dependency": "transformers.LLamaTokenizerFast" } ] }, "dependency": { "string": "\nDependencies:\n Intra File Dependencies: \n - check_byte_mappings\n \n Cross File Dependencies: \n - None\n", "intra_file": [ "check_byte_mappings" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs: \n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - vocab_union (set): \n A set containing the union of all tokens in the vocabularies of the provided tokenizers.\n - tokenizers_mapping (List[Dict]): \n A list of dictionaries, where each dictionary corresponds to a tokenizer from the input list and maps token IDs from the tokenizer to tokens in the vocab_union.\n - index_to_vocab (Dict): The variable index_to_vocab is a dictionary that maps integer indices (as keys) to the corresponding token strings (as values) in the unified vocabulary. Each integer key represents a unique position within the combined vocabulary set, and its associated value is the actual token string (which can be a word, a subword fragment, or a special character token). \n - byte_mappings_list (List[Dict]): \n A list of dictionaries, where each dictionary corresponds to a tokenizer from the input list and provides a mapping of byte value tokens from '<0x00>' to '<0xFF>' to their original token IDs in the tokenizer's vocabulary. This mapping is used to ensure consistency and to facilitate the identification and replacement of these tokens in the unified vocabulary.\n", "Return_list": [ { "name": "vocab_union", "string": "\n- vocab_union (set): \n A set containing the union of all tokens in the vocabularies of the provided tokenizers.\n", "dependency": null }, { "name": "tokenizers_mapping", "string": "\n- tokenizers_mapping (List[Dict]): \n A list of dictionaries, where each dictionary corresponds to a tokenizer from the input list and maps token IDs from the tokenizer to tokens in the vocab_union.\n", "dependency": null }, { "name": "index_to_vocab", "string": "- index_to_vocab (Dict): The variable index_to_vocab is a dictionary that maps integer indices (as keys) to the corresponding token strings (as values) in the unified vocabulary. Each integer key represents a unique position within the combined vocabulary set, and its associated value is the actual token string (which can be a word, a subword fragment, or a special character token). ", "dependency": null }, { "name": "byte_mappings_list", "string": "\n- byte_mappings_list (List[Dict]): \n A list of dictionaries, where each dictionary corresponds to a tokenizer from the input list and provides a mapping of byte value tokens from '<0x00>' to '<0xFF>' to their original token IDs in the tokenizer's vocabulary. This mapping is used to ensure consistency and to facilitate the identification and replacement of these tokens in the unified vocabulary.\n", "dependency": null } ] }, "ori_python_file": "import inspect\nimport warnings\nfrom typing import Callable, List, Optional, Union\nimport os, pickle\nimport torch\nimport torch.distributed as dist\nimport torch.nn.functional as F\nfrom tqdm import tqdm\nfrom transformers.generation import (\n GenerationConfig,\n LogitsProcessorList,\n StoppingCriteriaList,\n validate_stopping_criteria,\n)\nfrom transformers.generation.utils import *\nfrom transformers.generation.utils import GenerateOutput, GreedySearchOutput\nfrom .logger import setup_custom_logger\nlogger = setup_custom_logger(\"TSP\")\n\ndef generate_ensemnble_response(\n model_actors_list,\n tokenizers,\n vocab_union,\n mapping_matrices,\n index_to_vocab,\n special_prefix_tokens_dict,\n byte_mappings_list,\n primary_index,\n threshold,\n until,\n **kwargs,\n):\n refs = []\n ensemble_weight_list = []\n for model_actor in model_actors_list:\n refs.append(model_actor.generate_prepare(**kwargs))\n ensemble_weight_list.append(model_actor.get_ensemble_weight())\n cached_output_ids = [\n [] for _ in model_actors_list[0].get_input_ids()\n ]\n while True:\n tmp_outputs_refs = [\n model_actor.get_one_token() for model_actor in model_actors_list\n ]\n tmp_outputs, tmp_outputs_times, need_ensemble = check_threshold_ensemble(\n tmp_outputs_refs, primary_index, threshold\n )\n merged_token_ids = merge_and_convert_tokens(\n tmp_outputs,\n tokenizers,\n mapping_matrices,\n vocab_union,\n index_to_vocab,\n special_prefix_tokens_dict,\n byte_mappings_list,\n primary_index,\n threshold,\n need_ensemble,\n tmp_outputs_times,\n )\n cached_output_ids, merged_token_ids = check_until(\n until, cached_output_ids, tokenizers, merged_token_ids\n )\n refs = []\n for i, model_actor in enumerate(model_actors_list):\n ref = model_actor.update_input_ids_and_model_kwargs(\n next_tokens_list=merged_token_ids[i]\n )\n refs.append(ref)\n unfinished_sequences_list = [\n model_actor.get_unfinished_sequences()\n for model_actor in model_actors_list\n ]\n synced_unfinished_sequences = synchronize_unfinished_sequences(\n unfinished_sequences_list\n )\n update_refs = [\n model_actor.update_unfinished_sequences(synced_unfinished_sequences)\n for model_actor in model_actors_list\n ]\n finish_refs = [\n model_actor.check_if_stop() for model_actor in model_actors_list\n ]\n finish = any(finish_refs)\n if finish:\n break\n output = model_actors_list[0].get_input_ids()\n return output\n\ndef process_and_log_model_outputs(\n tokenizers, model_name_list, model_outputs, ensemble_weight_list\n):\n for output, tokenizer, model_name, ensemble_weight in zip(\n model_outputs, tokenizers, model_name_list, ensemble_weight_list\n ):\n if output is None:\n logger.info(f\"Token from Model {model_name}: N/A\")\n continue\n max_scores, max_indices = torch.max(output, dim=-1)\n decoded_tokens = [\n tokenizer.decode([idx], skip_special_tokens=False)\n for idx in max_indices.tolist()\n ]\n max_scores_list = [\n round(score.item() / ensemble_weight, 4) for score in max_scores\n ]\n logger.info(\n f\"Token from Model {model_name}: {decoded_tokens} (token id {max_indices.tolist()}) with Conf {max_scores_list}\"\n )\n\ndef synchronize_unfinished_sequences(unfinished_sequences_list):\n device = unfinished_sequences_list[0].device\n first_shape = unfinished_sequences_list[0].shape\n for unfinished_sequences in unfinished_sequences_list:\n if unfinished_sequences.shape != first_shape:\n raise ValueError(\n \"All 'unfinished_sequences' tensors must have the same shape.\"\n )\n sync_tensor = torch.ones_like(unfinished_sequences_list[0]).to(device)\n for unfinished_sequences in unfinished_sequences_list:\n sync_tensor = torch.logical_and(sync_tensor, unfinished_sequences.to(device))\n sync_tensor = sync_tensor.long()\n return sync_tensor\n\ndef update_input_ids_and_model_kwargs(model, state):\n outputs = state[\"outputs\"]\n input_ids = state[\"input_ids\"]\n next_tokens = state[\"next_tokens_list\"]\n model_kwargs = state[\"model_kwargs\"]\n unfinished_sequences = state[\"unfinished_sequences\"]\n pad_token_id = state[\"pad_token_id\"]\n eos_token_id_tensor = state[\"eos_token_id_tensor\"]\n if pad_token_id is None:\n raise ValueError(\"pad_token_id must be defined.\")\n next_tokens = [\n tokens if unfinished else [pad_token_id] * len(tokens)\n for tokens, unfinished in zip(next_tokens, unfinished_sequences)\n ]\n device = input_ids.device\n max_length = max([input_ids.shape[1] + len(tokens) for tokens in next_tokens])\n padded_input_ids = []\n attention_masks = []\n for i, tokens in enumerate(next_tokens):\n input_padding_size = max_length - input_ids.shape[1] - len(tokens)\n padded_input = torch.cat(\n [\n torch.full(\n (1, input_padding_size),\n pad_token_id,\n dtype=torch.long,\n device=device,\n ),\n input_ids[i].unsqueeze(0),\n torch.tensor(tokens, dtype=torch.long, device=device).unsqueeze(0),\n ],\n dim=1,\n )\n padded_input_ids.append(padded_input)\n if \"attention_mask\" in model_kwargs:\n original_attention_mask = model_kwargs[\"attention_mask\"][i]\n updated_attention_mask = torch.cat(\n [\n torch.zeros(input_padding_size, dtype=torch.long, device=device),\n original_attention_mask,\n torch.ones(len(tokens), dtype=torch.long, device=device),\n ]\n )\n attention_masks.append(updated_attention_mask)\n padded_input_ids_tensor = torch.cat(padded_input_ids, dim=0)\n model_kwargs = model._update_model_kwargs_for_generation(\n outputs, model_kwargs, is_encoder_decoder=model.config.is_encoder_decoder\n )\n if attention_masks:\n model_kwargs[\"attention_mask\"] = torch.stack(attention_masks)\n model_kwargs[\"cache_position\"] = torch.tensor(\n [model_kwargs[\"attention_mask\"].shape[1] - 1],\n dtype=torch.int64,\n device=model_kwargs[\"attention_mask\"].device,\n )\n if any(len(tokens) > 1 for tokens in next_tokens):\n model_kwargs[\"past_key_values\"] = None\n first_non_pad_indices = [\n input_id.ne(pad_token_id).nonzero(as_tuple=True)[0][0].item()\n if pad_token_id in input_id\n else 0\n for input_id in padded_input_ids_tensor\n ]\n max_pads_to_remove = min(first_non_pad_indices)\n if max_pads_to_remove > 0:\n padded_input_ids_tensor = padded_input_ids_tensor[:, max_pads_to_remove:]\n if \"attention_mask\" in model_kwargs:\n model_kwargs[\"attention_mask\"] = model_kwargs[\"attention_mask\"][\n :, max_pads_to_remove:\n ]\n if eos_token_id_tensor is not None:\n for i, tokens in enumerate(next_tokens):\n for token in tokens:\n unfinished_sequences[i] = unfinished_sequences[i] & (\n token != eos_token_id_tensor\n )\n return padded_input_ids_tensor, model_kwargs, unfinished_sequences\n\ndef check_byte_mappings(tokenizer):\n vocab = tokenizer.get_vocab()\n g_prefix_count = sum(token.startswith(\"\u0120\") for token in vocab)\n u_prefix_count = sum(token.startswith(\"\u2581\") for token in vocab)\n byte_mapping = {}\n if g_prefix_count > u_prefix_count:\n for byte_val in range(128):\n byte_char = chr(byte_val)\n token_id = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(byte_char))[0]\n hex_token = f\"<0x{byte_val:02X}>\"\n byte_mapping[hex_token] = token_id\n else:\n for byte_val in range(256):\n hex_token = f\"<0x{byte_val:02X}>\"\n if hex_token == \"<0x09>\" and hex_token not in vocab:\n continue\n if hex_token not in vocab:\n raise ValueError(\n f\"Token {hex_token} not found in tokenizer's vocabulary.\"\n )\n byte_mapping[hex_token] = vocab[hex_token]\n return byte_mapping\n\ndef get_vocab_union_and_mapping(tokenizers):\n vocab_union = set()\n tokenizers_mapping = []\n byte_mappings_list = []\n for byte_val in range(256):\n vocab_union.add(f\"<0x{byte_val:02X}>\")\n for tokenizer in tokenizers:\n vocab = tokenizer.get_vocab()\n token_set = set()\n mapping = {}\n byte_mapping = check_byte_mappings(tokenizer)\n byte_mappings_list.append(byte_mapping)\n for hex_token, token_id in byte_mapping.items():\n actual_tokens = [token for token, id in vocab.items() if id == token_id]\n if len(actual_tokens) != 1:\n raise ValueError(\n f\"Multiple tokens/ Zero token found for token ID {token_id} in tokenizer's vocabulary.\"\n )\n del vocab[actual_tokens[0]]\n g_prefix_count = sum(token.startswith(\"\u0120\") for token in vocab)\n u_prefix_count = sum(token.startswith(\"\u2581\") for token in vocab)\n if g_prefix_count > u_prefix_count:\n for token, token_id in vocab.items():\n processed_token = token.replace(\"\u0120\", \" \").replace(\"\u010a\", \"\\n\")\n token_set.add(processed_token)\n mapping[token_id] = processed_token\n else:\n for token, token_id in vocab.items():\n if token.startswith(\"\u2581\"):\n processed_token = token.replace(\"\u2581\", \" \")\n else:\n processed_token = token\n token_set.add(processed_token)\n mapping[token_id] = processed_token\n vocab_union = vocab_union.union(token_set)\n tokenizers_mapping.append(mapping)\n vocab_to_index = {token: i for i, token in enumerate(vocab_union)}\n index_to_vocab = {index: token for token, index in vocab_to_index.items()}\n for tokenizer, byte_mapping, mapping in zip(\n tokenizers, byte_mappings_list, tokenizers_mapping\n ):\n for token_id, token in mapping.items():\n mapping[token_id] = vocab_to_index[token]\n bbpe_mapping = {\n **{f\"<0x{hex(i)[2:].upper()}>\": chr(i) for i in range(0x30, 0x3A)},\n **{f\"<0x{hex(i)[2:].upper()}>\": chr(i) for i in range(0x41, 0x5B)},\n **{f\"<0x{hex(i)[2:].upper()}>\": chr(i) for i in range(0x61, 0x7B)},\n }\n for hex_token, original_token_id in byte_mapping.items():\n if (\n not all(len(bm) == 128 for bm in byte_mappings_list)\n and len(byte_mapping) == 128\n ):\n if hex_token in bbpe_mapping:\n mapping[original_token_id] = vocab_to_index[bbpe_mapping[hex_token]]\n continue\n mapping[original_token_id] = vocab_to_index[hex_token]\n return vocab_union, tokenizers_mapping, index_to_vocab, byte_mappings_list\n\ndef create_mapping_matrix(mapping, union_vocab_size, model_vocab_size):\n if model_vocab_size == 151646:\n logger.warning(\n \"The qwen1.5 series has been detected, where the length of tokenizer.get_vocab() and the vocab_size in the model config are inconsistent. We have forcefully set it to the latter. https://github.com/QwenLM/Qwen1.5/issues/29\"\n )\n model_vocab_size = 151936\n indices = []\n values = []\n for model_token_id, unified_token_index in mapping.items():\n indices.append([model_token_id, unified_token_index])\n values.append(1.0)\n indices = torch.tensor(\n indices, dtype=torch.long\n ).t()\n values = torch.tensor(values, dtype=torch.float)\n size = torch.Size([model_vocab_size, union_vocab_size])\n mapping_matrix = torch.sparse_coo_tensor(indices, values, size, device=\"cuda\")\n return mapping_matrix\n\ndef check_until(until, cached_batch_output_ids, tokenizers, merged_token_ids):\n if len(cached_batch_output_ids) != len(merged_token_ids[0]):\n raise ValueError(\n f\"len(cached_batch_output_ids):{len(cached_batch_output_ids)} != len(merged_token_ids[0]): {len(merged_token_ids[0])}\"\n )\n for i, _ in enumerate(cached_batch_output_ids):\n cached_batch_output_ids[i] = cached_batch_output_ids[i] + merged_token_ids[0][i]\n tmp_text = tokenizers[0].decode(cached_batch_output_ids[i])\n if until:\n for stop_txt in until:\n if stop_txt in tmp_text:\n for j, tokenizer in enumerate(tokenizers):\n merged_token_ids[j][i] = merged_token_ids[j][i] + [\n tokenizer.eos_token_id\n ]\n break\n return cached_batch_output_ids, merged_token_ids\n\ndef check_threshold_ensemble(tmp_outputs_refs, primary_index, threshold):\n if primary_index == -1:\n tmp = tmp_outputs_refs\n outputs = [t[0] for t in tmp]\n outputs_times = [t[1] for t in tmp]\n need_ensemble = True\n else:\n primary_model_outputs, primary_model_outputs_times = tmp_outputs_refs[primary_index]\n if primary_model_outputs.shape[0] != 1:\n raise ValueError(\"For thresholded ensemble, we only support batch size of 1.\")\n max_probs, _ = torch.max(primary_model_outputs, dim=1)\n if max_probs.item() > threshold:\n for i, ref in enumerate(tmp_outputs_refs):\n if i != primary_index:\n continue\n outputs = [None] * len(tmp_outputs_refs)\n outputs[primary_index] = primary_model_outputs\n outputs_times = [primary_model_outputs_times] * len(tmp_outputs_refs)\n need_ensemble = False\n else:\n tmp = tmp_outputs_refs\n outputs = [t[0] for t in tmp]\n outputs_times = [t[1] for t in tmp]\n need_ensemble = True\n return outputs, outputs_times, need_ensemble\n\ndef merge_and_convert_tokens(\n outputs,\n tokenizers,\n mapping_matrices,\n vocab_union,\n index_to_vocab,\n special_prefix_token,\n byte_mappings_list,\n primary_index,\n threshold,\n need_ensemble,\n tmp_outputs_times,\n):\n eos_token_list = [tokenizer.eos_token for tokenizer in tokenizers]\n eos_token_list.extend([\"<|end_of_text|>\", \"<|endoftext|>\", \"<|im_end|>\", \"<|end|>\"])\n for i, output in enumerate(outputs):\n if need_ensemble:\n if output is None:\n raise ValueError(\n \"We detect a probability vector of None, which need to excute ensemble!\"\n )\n else:\n if output is not None and i != primary_index:\n raise ValueError(\n \"We detect a probability vector from non-primary model, but no ensemble excuted!\"\n )\n if primary_index == -1:\n merged_probs = torch.zeros(\n (outputs[0].size(0), len(vocab_union)), device=\"cuda\"\n )\n else:\n merged_probs = torch.zeros(\n (outputs[primary_index].size(0), len(vocab_union)), device=\"cuda\"\n )\n if need_ensemble:\n for output, mapping_matrix in zip(outputs, mapping_matrices):\n transformed_probs = torch.sparse.mm(output, mapping_matrix)\n merged_probs += transformed_probs\n else:\n transformed_probs = torch.sparse.mm(\n outputs[primary_index], mapping_matrices[primary_index]\n )\n merged_probs += transformed_probs\n logger.info(\"GaC do not ensemble in this step.\")\n max_token_indices = torch.argmax(merged_probs, dim=1)\n max_tokens = [index_to_vocab[index.item()] for index in max_token_indices]\n logger.info(f\"Token chosen by GaC: {str(max_tokens)}\\n\")\n batch_token_ids = [\n [] for _ in range(len(tokenizers))\n ]\n for i, tokenizer in enumerate(tokenizers):\n for token in max_tokens:\n if token in eos_token_list:\n token_id = [tokenizer.eos_token_id]\n else:\n token_id = get_token_ids(\n tokenizer,\n token,\n special_prefix_token[tokenizer],\n byte_mappings_list[i],\n )\n batch_token_ids[i].append(token_id)\n return batch_token_ids\n\ndef get_token_ids(tokenizer, token, special_prefix_token, byte_mapping):\n if token in byte_mapping:\n return [byte_mapping[token]]\n if byte_mapping != 128:\n prefix_tokens = [special_prefix_token, \";\"]\n for prefix_token in prefix_tokens:\n token_id_list1 = tokenizer.encode(prefix_token, add_special_tokens=False)\n token_id_list2 = tokenizer.encode(\n prefix_token + token, add_special_tokens=False\n )\n if token_id_list2[: len(token_id_list1)] == token_id_list1:\n result = token_id_list2[len(token_id_list1) :]\n if result:\n return result\n logger.warning(f\"Warning: Token '{token}' may not be tokenized as expected.\")\n return tokenizer.encode(token, add_special_tokens=False)\n\ndef find_special_underscore_token(tokenizer):\n vocab = tokenizer.get_vocab()\n count_prefix_G = sum(1 for token in vocab if token.startswith(\"\u0120\"))\n count_prefix_underscore = sum(1 for token in vocab if token.startswith(\"\u2581\"))\n if count_prefix_G > count_prefix_underscore:\n return \"\"\n underscore_tokens = [\n token for token in vocab if token.startswith(\"\u2581\") and token != \"\u2581\"\n ]\n special_tokens = []\n for token in tqdm(underscore_tokens, desc=\"Analyzing tokens\"):\n cleaned_token = token[1:]\n if (\n not any(\n token in other_token\n for other_token in underscore_tokens\n if other_token != token\n )\n and token.count(\"\u2581\") == 1\n and cleaned_token.strip() != \"\"\n ):\n special_tokens.append(cleaned_token)\n if not special_tokens:\n raise ValueError(\"No special underscore token found that meets the criteria.\")\n return min(special_tokens, key=lambda x: (len(x), x))\n\ndef get_special_prefix_tokens_for_all(tokenizers):\n special_prefix_tokens = {}\n for tokenizer in tokenizers:\n if tokenizer.vocab_size == 256000:\n logger.info(\"gemma-it detected, use '\u00a2' as special_prefix_token\")\n special_prefix_tokens[tokenizer] = \"\u00a2\"\n continue\n token = find_special_underscore_token(tokenizer)\n special_prefix_tokens[tokenizer] = token\n return special_prefix_tokens\n\ndef greedy_search(\n model,\n input_ids: torch.LongTensor,\n logits_processor: Optional[LogitsProcessorList] = None,\n stopping_criteria: Optional[StoppingCriteriaList] = None,\n max_length: Optional[int] = None,\n pad_token_id: Optional[int] = None,\n eos_token_id: Optional[Union[int, List[int]]] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n output_scores: Optional[bool] = None,\n return_dict_in_generate: Optional[bool] = None,\n synced_gpus: bool = False,\n streamer: Optional[\"BaseStreamer\"] = None,\n **model_kwargs,\n) -> Union[GreedySearchOutput, torch.LongTensor]:\n logits_processor = (\n logits_processor if logits_processor is not None else LogitsProcessorList()\n )\n stopping_criteria = (\n stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()\n )\n if max_length is not None:\n warnings.warn(\n \"`max_length` is deprecated in this function, use\"\n \" `stopping_criteria=StoppingCriteriaList([MaxLengthCriteria(max_length=max_length)])` instead.\",\n UserWarning,\n )\n stopping_criteria = validate_stopping_criteria(stopping_criteria, max_length)\n pad_token_id = (\n pad_token_id\n if pad_token_id is not None\n else model.generation_config.pad_token_id\n )\n eos_token_id = (\n eos_token_id\n if eos_token_id is not None\n else model.generation_config.eos_token_id\n )\n if isinstance(eos_token_id, int):\n eos_token_id = [eos_token_id]\n eos_token_id_tensor = (\n torch.tensor(eos_token_id).to(input_ids.device)\n if eos_token_id is not None\n else None\n )\n output_scores = (\n output_scores\n if output_scores is not None\n else model.generation_config.output_scores\n )\n output_attentions = (\n output_attentions\n if output_attentions is not None\n else model.generation_config.output_attentions\n )\n output_hidden_states = (\n output_hidden_states\n if output_hidden_states is not None\n else model.generation_config.output_hidden_states\n )\n return_dict_in_generate = (\n return_dict_in_generate\n if return_dict_in_generate is not None\n else model.generation_config.return_dict_in_generate\n )\n scores = () if (return_dict_in_generate and output_scores) else None\n model_kwargs = model._get_initial_cache_position(input_ids, model_kwargs)\n if model.config.is_encoder_decoder:\n raise Exception(\"We only support decorder arch!\")\n unfinished_sequences = torch.ones(\n input_ids.shape[0], dtype=torch.long, device=input_ids.device\n )\n this_peer_finished = False\n return {\n \"input_ids\": input_ids,\n \"model_kwargs\": model_kwargs,\n \"output_attentions\": output_attentions,\n \"output_hidden_states\": output_hidden_states,\n \"stopping_criteria\": stopping_criteria,\n \"logits_processor\": logits_processor,\n \"scores\": scores,\n \"pad_token_id\": pad_token_id,\n \"eos_token_id_tensor\": eos_token_id_tensor,\n \"unfinished_sequences\": unfinished_sequences,\n \"this_peer_finished\": this_peer_finished,\n }\n\ndef get_one_token(model, state):\n input_ids = state[\"input_ids\"]\n model_kwargs = state[\"model_kwargs\"]\n output_attentions = state[\"output_attentions\"]\n output_hidden_states = state[\"output_hidden_states\"]\n logits_processor = state[\"logits_processor\"]\n model_inputs = model.prepare_inputs_for_generation(input_ids, **model_kwargs)\n with torch.no_grad():\n outputs = model(\n **model_inputs,\n return_dict=True,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n )\n next_token_logits = outputs.logits[:, -1, :]\n next_tokens_scores = logits_processor(input_ids, next_token_logits)\n next_tokens_scores = F.softmax(next_tokens_scores, dim=-1)\n return next_tokens_scores, outputs\n\ndef generate_prepare(\n model,\n inputs: Optional[torch.Tensor] = None,\n generation_config: Optional[GenerationConfig] = None,\n logits_processor: Optional[LogitsProcessorList] = None,\n stopping_criteria: Optional[StoppingCriteriaList] = None,\n prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,\n synced_gpus: Optional[bool] = None,\n assistant_model: Optional[\"PreTrainedModel\"] = None,\n streamer: Optional[\"BaseStreamer\"] = None,\n negative_prompt_ids: Optional[torch.Tensor] = None,\n negative_prompt_attention_mask: Optional[torch.Tensor] = None,\n **kwargs,\n) -> Union[GenerateOutput, torch.LongTensor]:\n model._validate_model_class()\n tokenizer = kwargs.pop(\n \"tokenizer\", None\n )\n generation_config, model_kwargs = model._prepare_generation_config(\n generation_config, **kwargs\n )\n if 'model_name_list' in model_kwargs:\n del model_kwargs['model_name_list']\n model._validate_model_kwargs(model_kwargs.copy())\n model._validate_assistant(assistant_model)\n if synced_gpus is None:\n if is_deepspeed_zero3_enabled() and dist.get_world_size() > 1:\n synced_gpus = True\n else:\n synced_gpus = False\n logits_processor = (\n logits_processor if logits_processor is not None else LogitsProcessorList()\n )\n stopping_criteria = (\n stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()\n )\n accepts_attention_mask = \"attention_mask\" in set(\n inspect.signature(model.forward).parameters.keys()\n )\n requires_attention_mask = \"encoder_outputs\" not in model_kwargs\n kwargs_has_attention_mask = model_kwargs.get(\"attention_mask\", None) is not None\n inputs_tensor, model_input_name, model_kwargs = model._prepare_model_inputs(\n inputs, generation_config.bos_token_id, model_kwargs\n )\n batch_size = inputs_tensor.shape[0]\n device = inputs_tensor.device\n model._prepare_special_tokens(\n generation_config, kwargs_has_attention_mask, device=device\n )\n if not model.config.is_encoder_decoder and not is_torchdynamo_compiling():\n if (\n generation_config._pad_token_tensor is not None\n and batch_size > 1\n and len(inputs_tensor.shape) == 2\n and torch.sum(inputs_tensor[:, -1] == generation_config._pad_token_tensor)\n > 0\n ):\n logger.warning(\n \"A decoder-only architecture is being used, but right-padding was detected! For correct \"\n \"generation results, please set `padding_side='left'` when initializing the tokenizer.\"\n )\n if not model.config.is_encoder_decoder and model_input_name == \"inputs_embeds\":\n model_kwargs[\"use_cache\"] = True\n else:\n model_kwargs[\"use_cache\"] = generation_config.use_cache\n if (\n not kwargs_has_attention_mask\n and requires_attention_mask\n and accepts_attention_mask\n ):\n model_kwargs[\"attention_mask\"] = model._prepare_attention_mask_for_generation(\n inputs_tensor,\n generation_config._pad_token_tensor,\n generation_config._eos_token_tensor,\n )\n if model.config.is_encoder_decoder and \"encoder_outputs\" not in model_kwargs:\n model_kwargs = model._prepare_encoder_decoder_kwargs_for_generation(\n inputs_tensor, model_kwargs, model_input_name, generation_config\n )\n if model.config.is_encoder_decoder:\n input_ids, model_kwargs = model._prepare_decoder_input_ids_for_generation(\n batch_size=batch_size,\n model_input_name=model_input_name,\n model_kwargs=model_kwargs,\n decoder_start_token_id=generation_config._decoder_start_token_tensor,\n device=inputs_tensor.device,\n )\n else:\n input_ids = (\n inputs_tensor\n if model_input_name == \"input_ids\"\n else model_kwargs.pop(\"input_ids\")\n )\n if generation_config.token_healing:\n input_ids = model.heal_tokens(input_ids, tokenizer)\n if streamer is not None:\n streamer.put(input_ids.cpu())\n input_ids_length = input_ids.shape[-1]\n has_default_max_length = (\n kwargs.get(\"max_length\") is None and generation_config.max_length is not None\n )\n has_default_min_length = (\n kwargs.get(\"min_length\") is None and generation_config.min_length is not None\n )\n generation_config = model._prepare_generated_length(\n generation_config=generation_config,\n has_default_max_length=has_default_max_length,\n has_default_min_length=has_default_min_length,\n model_input_name=model_input_name,\n inputs_tensor=inputs_tensor,\n input_ids_length=input_ids_length,\n )\n use_dynamic_cache_by_default = False\n if \"mamba\" in model.__class__.__name__.lower():\n cache_name = \"cache_params\"\n else:\n cache_name = \"past_key_values\"\n if (\n assistant_model is not None\n and generation_config.cache_implementation is not None\n and model._supports_default_dynamic_cache()\n ):\n logger.warning_once(\n \"An assistant model is provided, using a dynamic cache instead of a cache of type=\"\n f\"'{generation_config.cache_implementation}'.\"\n )\n generation_config.cache_implementation = None\n if (model_kwargs.get(cache_name) is not None) and is_torchdynamo_compiling():\n raise ValueError(\n \"Passing `past_key_values` is not supported when compiling `model.generate` with torch.compile -- you \"\n \"may get incorrect outputs. Please compile `model.forward` only or use the `cache_implementation` \"\n \"input argument.\"\n )\n if generation_config.cache_implementation is not None and (\n model_kwargs.get(cache_name) is not None\n ):\n raise ValueError(\n f\"Passing both `cache_implementation` (used to initialize certain caches) and `{cache_name}` (a \"\n \"Cache object) is unsupported. Please use only one of the two.\"\n )\n elif generation_config.cache_implementation is not None:\n if generation_config.cache_implementation in NEED_SETUP_CACHE_CLASSES_MAPPING:\n if (\n generation_config.cache_implementation == \"static\"\n and not model._supports_static_cache\n ):\n raise ValueError(\n \"This model does not support `cache_implementation='static'`. Please check the following \"\n \"issue: https://github.com/huggingface/transformers/issues/28981\"\n )\n model_kwargs[cache_name] = model._get_cache(\n cache_implementation=generation_config.cache_implementation,\n max_batch_size=generation_config.num_beams\n * generation_config.num_return_sequences\n * batch_size,\n max_cache_len=generation_config.max_length,\n device=device,\n model_kwargs=model_kwargs,\n )\n elif generation_config.cache_implementation == \"quantized\":\n if not model._supports_quantized_cache:\n raise ValueError(\n \"This model does not support the quantized cache. If you want your model to support quantized \"\n \"cache, please open an issue.\"\n )\n cache_config = (\n generation_config.cache_config\n if generation_config.cache_config is not None\n else QuantizedCacheConfig()\n )\n cache_class = QUANT_BACKEND_CLASSES_MAPPING[cache_config.backend]\n if cache_config.backend == \"quanto\" and not is_quanto_available():\n raise ImportError(\n \"You need to install `quanto` in order to use KV cache quantization with quanto backend. \"\n \"Please install it via with `pip install quanto`\"\n )\n elif cache_config.backend == \"HQQ\" and not is_hqq_available():\n raise ImportError(\n \"You need to install `HQQ` in order to use KV cache quantization with HQQ backend. \"\n \"Please install it via with `pip install hqq`\"\n )\n model_kwargs[cache_name] = cache_class(cache_config)\n elif generation_config.cache_implementation == \"offloaded\":\n model_kwargs[cache_name] = OffloadedCache()\n elif (\n generation_config.cache_implementation is None\n and model._supports_default_dynamic_cache()\n ):\n past = model_kwargs.get(cache_name, None)\n requires_cross_attention_cache = (\n model.config.is_encoder_decoder\n or model_kwargs.get(\"encoder_outputs\") is not None\n )\n if past is None:\n model_kwargs[cache_name] = (\n DynamicCache()\n if not requires_cross_attention_cache\n else EncoderDecoderCache(DynamicCache(), DynamicCache())\n )\n use_dynamic_cache_by_default = True\n elif isinstance(past, tuple):\n model_kwargs[cache_name] = (\n DynamicCache.from_legacy_cache(past)\n if not requires_cross_attention_cache\n else EncoderDecoderCache.from_legacy_cache(past)\n )\n use_dynamic_cache_by_default = True\n model._validate_generated_length(\n generation_config, input_ids_length, has_default_max_length\n )\n generation_mode = generation_config.get_generation_mode(assistant_model)\n if streamer is not None and (generation_config.num_beams > 1):\n raise ValueError(\n \"`streamer` cannot be used with beam search (yet!). Make sure that `num_beams` is set to 1.\"\n )\n if not is_torchdynamo_compiling() and model.device.type != input_ids.device.type:\n warnings.warn(\n \"You are calling .generate() with the `input_ids` being on a device type different\"\n f\" than your model's device. `input_ids` is on {input_ids.device.type}, whereas the model\"\n f\" is on {model.device.type}. You may experience unexpected behaviors or slower generation.\"\n \" Please make sure that you have put `input_ids` to the\"\n f\" correct device by calling for example input_ids = input_ids.to('{model.device.type}') before\"\n \" running `.generate()`.\",\n UserWarning,\n )\n prepared_logits_processor = model._get_logits_processor(\n generation_config=generation_config,\n input_ids_seq_length=input_ids_length,\n encoder_input_ids=inputs_tensor,\n prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,\n logits_processor=logits_processor,\n device=inputs_tensor.device,\n model_kwargs=model_kwargs,\n negative_prompt_ids=negative_prompt_ids,\n negative_prompt_attention_mask=negative_prompt_attention_mask,\n )\n prepared_stopping_criteria = model._get_stopping_criteria(\n generation_config=generation_config,\n stopping_criteria=stopping_criteria,\n tokenizer=tokenizer,\n **kwargs,\n )\n return greedy_search(\n model,\n input_ids,\n logits_processor=prepared_logits_processor,\n stopping_criteria=prepared_stopping_criteria,\n pad_token_id=generation_config.pad_token_id,\n eos_token_id=generation_config.eos_token_id,\n output_scores=generation_config.output_scores,\n return_dict_in_generate=generation_config.return_dict_in_generate,\n synced_gpus=synced_gpus,\n streamer=streamer,\n **model_kwargs,\n )" }, { "task_id": 1, "indent": 1, "completion_path": "./utils/gac_gen_utils.py", "script": "\npython main.py\n", "latex_code": "\n\\subsection{Ensembling Key Tokens with Threshold}\n\\label{sec3-4}\nAs mentioned in the last part of Sec.\\ref{ensemble-with-t}, most tokens do not significantly affect the correctness of the response. From Tab.\\ref{tab1}, we can see that LLMs and CV models have similar ECE levels, suggesting that the confidence scores of LLMs may reflect accuracy to some extent. Therefore, we also experiment with ensembling only the steps with confidence below a threshold \\( t \\). We choose a model as the gate, denoted \\(\\textit{LLM}_g\\), and use its maximum probability at each step as the confidence score. During the ensemble, we replace the original (\\ref{eq3}) with:\n\\begin{equation}\n\\label{eq5}\n\\resizebox{.93\\hsize}{!}{$\nq(\\cdot) =\n\\begin{cases}\n\\frac{1}{n} \\sum_{i} p^i(\\cdot\\,|\\,\\mathcal{I}^{\\,i}) \\cdot \\mathbf{M}^{i} & \\textit{if } \\max(p^g(\\cdot\\,|\\,\\mathcal{I}^{\\,g})) \\leq t \\\\\np^g(\\cdot\\,|\\,\\mathcal{I}^{\\,g}) \\cdot \\mathbf{M}^{g} & \\textit{otherwise}.\n\\end{cases}\n$}\n\\end{equation}\n", "namespace": "utils.gac_gen_utils.check_threshold_ensemble", "type": "function", "signature_position": [ 322, 322 ], "body_position": [ 323, 346 ], "ReferenceCode_With_Comments": "\n# ----------------------------------------------------------------------------\n# Snippet 1: If no specific gate model is selected (primary_index == -1), we default to always ensemble all model outputs, akin to directly applying the multi-model summation without threshold gating.\n# ----------------------------------------------------------------------------\n# [Begin Snippet 1]\nif primary_index == -1:\n tmp = tmp_outputs_refs\n outputs = [t[0] for t in tmp]\n outputs_times = [t[1] for t in tmp]\n need_ensemble = True\n\n# [End Snippet 1]\nelse:\n # ----------------------------------------------------------------------------\n # Snippet 2: If specific gate model is selected, Retrieve the gate model outputs from the designated primary_index, referencing p^g(\u00b7|\u00b7). Verify that the batch size is 1, consistent with the paper\u2019s example of threshold gating on a single-step basis.\n # ----------------------------------------------------------------------------\n # [Begin Snippet 2]\n primary_model_outputs, primary_model_outputs_times = tmp_outputs_refs[primary_index]\n \n if primary_model_outputs.shape[0] != 1:\n raise ValueError(\"For thresholded ensemble, we only support batch size of 1.\")\n # [End Snippet 2]\n\n # ----------------------------------------------------------------------------\n # Snippet 3: Compute the maximum probability from the gate model. This value serves as the confidence score (max(p^g(\u00b7|\u00b7))) compared to threshold t.\n # ----------------------------------------------------------------------------\n # [Begin Snippet 3]\n max_probs, _ = torch.max(primary_model_outputs, dim=1)\n # [End Snippet 3]\n\n # ----------------------------------------------------------------------------\n # Snippet 4: If the gate model\u2019s maximum probability exceeds threshold t, skip ensembling by setting other model outputs to None, corresponding to the \u201cotherwise\u201d case, i.e., q(\u00b7) = p^g(\u00b7|\u00b7) * M^g.\n # ----------------------------------------------------------------------------\n # [Begin Snippet 4]\n if max_probs.item() > threshold:\n for i, ref in enumerate(tmp_outputs_refs):\n if i != primary_index:\n continue\n outputs = [None] * len(tmp_outputs_refs)\n outputs[primary_index] = primary_model_outputs\n outputs_times = [primary_model_outputs_times] * len(tmp_outputs_refs)\n need_ensemble = False\n\n # [End Snippet 4]\n else:\n # ----------------------------------------------------------------------------\n # Snippet 5: If the gate model\u2019s maximum probability is <= threshold t, ensemble the distributions from all models, corresponding to the first case in Eq. (5): q(\u00b7) = (1/n)*\u03a3 p^i(\u00b7|\u00b7) * M^i.\n # ----------------------------------------------------------------------------\n # [Begin Snippet 5]\n tmp = tmp_outputs_refs\n outputs = [t[0] for t in tmp]\n outputs_times = [t[1] for t in tmp]\n need_ensemble = True\n # [End Snippet 5]\n\n# ----------------------------------------------------------------------------\n# Snippet 6: Return the final decision on whether to ensemble, the chosen outputs, and each model's associated times. \n# ----------------------------------------------------------------------------\n# [Begin Snippet 6]\nreturn outputs, outputs_times, need_ensemble\n# [End Snippet 6]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - Ensuring `outputs_times` correctly aligns across all models when `primary_index == -1`. The original description assumes all models contribute equally, but we should ensure that their processing times are correctly structured and indexed.\n\n - Mismatched Details:\n - None\n", "Missing_details": [ "\n- Ensuring `outputs_times` correctly aligns across all models when `primary_index == -1`. The original description assumes all models contribute equally, but we should ensure that their processing times are correctly structured and indexed.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - tmp_outputs_refs (List[Tuple(outputs, output_times)]): Contains references to the output distributions (e.g., token probabilities) and their corresponding timestamps (or step indices). \n - Expected Data Types:\n A list of tuples/lists with each element structured like (tensor, list or tensor).\n Example: \n [\n (model_output_tensor_A, time_steps_A),\n (model_output_tensor_B, time_steps_B),\n ...\n ]\n Where:\n model_output_tensor_X: a PyTorch tensor of shape [batch_size, vocab_size] \n holding the distribution over possible tokens.\n time_steps_X: a list or tensor indicating the positions in the sequence.\n - primary_index (int): \n The index of the primary model in the model list.\n - threshold (float): \n The confidence threshold for the primary model. If the model's highest probability exceeds this value, ensemble is not performed.\n ", "Arguments_list": [ { "name": "tmp_outputs_refs", "string": "\n- tmp_outputs_refs (List[Tuple(outputs, output_times)]): Contains references to the output distributions (e.g., token probabilities) and their corresponding timestamps (or step indices). \n - Expected Data Types:\n A list of tuples/lists with each element structured like (tensor, list or tensor).\n Example: \n [\n (model_output_tensor_A, time_steps_A),\n (model_output_tensor_B, time_steps_B),\n ...\n ]\n Where:\n model_output_tensor_X: a PyTorch tensor of shape [batch_size, vocab_size] \n holding the distribution over possible tokens.\n time_steps_X: a list or tensor indicating the positions in the sequence.\n", "dependency": null }, { "name": "primary_index", "string": "\n- primary_index (int): \n The index of the primary model in the model list.", "dependency": null }, { "name": "threshold", "string": "\n- threshold (float): \n The confidence threshold for the primary model. If the model's highest probability exceeds this value, ensemble is not performed.", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n Intra File Dependencies: \n - None\n \n Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.max \n", "list": [ "torch.max" ] }, "Return": { "Return_String": "\nOutput Variables:\n - outputs (List[Torch.FloatTensor]): The resulting distributions (for each model) after checking the threshold. If we decide to ensemble, outputs contains distributions for all models; if not, it primarily holds the distribution of the primary model (and 'None' for others in the list, indicating those are ignored).\n - outputs_times (List[float]): The time steps corresponding to each distribution in the 'outputs'. If the threshold is exceeded by the primary model, the times are replicated for the primary model alone.\n - need_ensemble (bool): Indicates whether the function decided to perform an ensemble of all distributions (True) or to rely solely on the primary model (False).\n", "Return_list": [ { "name": "outputs", "string": "- outputs (List[Torch.FloatTensor]): The resulting distributions (for each model) after checking the threshold. If we decide to ensemble, outputs contains distributions for all models; if not, it primarily holds the distribution of the primary model (and 'None' for others in the list, indicating those are ignored).", "dependency": null }, { "name": "outputs_times", "string": "- outputs_times (List[float]): The time steps corresponding to each distribution in the 'outputs'. If the threshold is exceeded by the primary model, the times are replicated for the primary model alone.", "dependency": null }, { "name": "need_ensemble", "string": "- need_ensemble (bool): Indicates whether the function decided to perform an ensemble of all distributions (True) or to rely solely on the primary model (False).", "dependency": null } ] }, "ori_python_file": "import inspect\nimport warnings\nfrom typing import Callable, List, Optional, Union\nimport os, pickle\nimport torch\nimport torch.distributed as dist\nimport torch.nn.functional as F\nfrom tqdm import tqdm\nfrom transformers.generation import (\n GenerationConfig,\n LogitsProcessorList,\n StoppingCriteriaList,\n validate_stopping_criteria,\n)\nfrom transformers.generation.utils import *\nfrom transformers.generation.utils import GenerateOutput, GreedySearchOutput\nfrom .logger import setup_custom_logger\nlogger = setup_custom_logger(\"TSP\")\n\ndef generate_ensemnble_response(\n model_actors_list,\n tokenizers,\n vocab_union,\n mapping_matrices,\n index_to_vocab,\n special_prefix_tokens_dict,\n byte_mappings_list,\n primary_index,\n threshold,\n until,\n **kwargs,\n):\n refs = []\n ensemble_weight_list = []\n for model_actor in model_actors_list:\n refs.append(model_actor.generate_prepare(**kwargs))\n ensemble_weight_list.append(model_actor.get_ensemble_weight())\n cached_output_ids = [\n [] for _ in model_actors_list[0].get_input_ids()\n ]\n while True:\n tmp_outputs_refs = [\n model_actor.get_one_token() for model_actor in model_actors_list\n ]\n tmp_outputs, tmp_outputs_times, need_ensemble = check_threshold_ensemble(\n tmp_outputs_refs, primary_index, threshold\n )\n merged_token_ids = merge_and_convert_tokens(\n tmp_outputs,\n tokenizers,\n mapping_matrices,\n vocab_union,\n index_to_vocab,\n special_prefix_tokens_dict,\n byte_mappings_list,\n primary_index,\n threshold,\n need_ensemble,\n tmp_outputs_times,\n )\n cached_output_ids, merged_token_ids = check_until(\n until, cached_output_ids, tokenizers, merged_token_ids\n )\n refs = []\n for i, model_actor in enumerate(model_actors_list):\n ref = model_actor.update_input_ids_and_model_kwargs(\n next_tokens_list=merged_token_ids[i]\n )\n refs.append(ref)\n unfinished_sequences_list = [\n model_actor.get_unfinished_sequences()\n for model_actor in model_actors_list\n ]\n synced_unfinished_sequences = synchronize_unfinished_sequences(\n unfinished_sequences_list\n )\n update_refs = [\n model_actor.update_unfinished_sequences(synced_unfinished_sequences)\n for model_actor in model_actors_list\n ]\n finish_refs = [\n model_actor.check_if_stop() for model_actor in model_actors_list\n ]\n finish = any(finish_refs)\n if finish:\n break\n output = model_actors_list[0].get_input_ids()\n return output\n\ndef process_and_log_model_outputs(\n tokenizers, model_name_list, model_outputs, ensemble_weight_list\n):\n for output, tokenizer, model_name, ensemble_weight in zip(\n model_outputs, tokenizers, model_name_list, ensemble_weight_list\n ):\n if output is None:\n logger.info(f\"Token from Model {model_name}: N/A\")\n continue\n max_scores, max_indices = torch.max(output, dim=-1)\n decoded_tokens = [\n tokenizer.decode([idx], skip_special_tokens=False)\n for idx in max_indices.tolist()\n ]\n max_scores_list = [\n round(score.item() / ensemble_weight, 4) for score in max_scores\n ]\n logger.info(\n f\"Token from Model {model_name}: {decoded_tokens} (token id {max_indices.tolist()}) with Conf {max_scores_list}\"\n )\n\ndef synchronize_unfinished_sequences(unfinished_sequences_list):\n device = unfinished_sequences_list[0].device\n first_shape = unfinished_sequences_list[0].shape\n for unfinished_sequences in unfinished_sequences_list:\n if unfinished_sequences.shape != first_shape:\n raise ValueError(\n \"All 'unfinished_sequences' tensors must have the same shape.\"\n )\n sync_tensor = torch.ones_like(unfinished_sequences_list[0]).to(device)\n for unfinished_sequences in unfinished_sequences_list:\n sync_tensor = torch.logical_and(sync_tensor, unfinished_sequences.to(device))\n sync_tensor = sync_tensor.long()\n return sync_tensor\n\ndef update_input_ids_and_model_kwargs(model, state):\n outputs = state[\"outputs\"]\n input_ids = state[\"input_ids\"]\n next_tokens = state[\"next_tokens_list\"]\n model_kwargs = state[\"model_kwargs\"]\n unfinished_sequences = state[\"unfinished_sequences\"]\n pad_token_id = state[\"pad_token_id\"]\n eos_token_id_tensor = state[\"eos_token_id_tensor\"]\n if pad_token_id is None:\n raise ValueError(\"pad_token_id must be defined.\")\n next_tokens = [\n tokens if unfinished else [pad_token_id] * len(tokens)\n for tokens, unfinished in zip(next_tokens, unfinished_sequences)\n ]\n device = input_ids.device\n max_length = max([input_ids.shape[1] + len(tokens) for tokens in next_tokens])\n padded_input_ids = []\n attention_masks = []\n for i, tokens in enumerate(next_tokens):\n input_padding_size = max_length - input_ids.shape[1] - len(tokens)\n padded_input = torch.cat(\n [\n torch.full(\n (1, input_padding_size),\n pad_token_id,\n dtype=torch.long,\n device=device,\n ),\n input_ids[i].unsqueeze(0),\n torch.tensor(tokens, dtype=torch.long, device=device).unsqueeze(0),\n ],\n dim=1,\n )\n padded_input_ids.append(padded_input)\n if \"attention_mask\" in model_kwargs:\n original_attention_mask = model_kwargs[\"attention_mask\"][i]\n updated_attention_mask = torch.cat(\n [\n torch.zeros(input_padding_size, dtype=torch.long, device=device),\n original_attention_mask,\n torch.ones(len(tokens), dtype=torch.long, device=device),\n ]\n )\n attention_masks.append(updated_attention_mask)\n padded_input_ids_tensor = torch.cat(padded_input_ids, dim=0)\n model_kwargs = model._update_model_kwargs_for_generation(\n outputs, model_kwargs, is_encoder_decoder=model.config.is_encoder_decoder\n )\n if attention_masks:\n model_kwargs[\"attention_mask\"] = torch.stack(attention_masks)\n model_kwargs[\"cache_position\"] = torch.tensor(\n [model_kwargs[\"attention_mask\"].shape[1] - 1],\n dtype=torch.int64,\n device=model_kwargs[\"attention_mask\"].device,\n )\n if any(len(tokens) > 1 for tokens in next_tokens):\n model_kwargs[\"past_key_values\"] = None\n first_non_pad_indices = [\n input_id.ne(pad_token_id).nonzero(as_tuple=True)[0][0].item()\n if pad_token_id in input_id\n else 0\n for input_id in padded_input_ids_tensor\n ]\n max_pads_to_remove = min(first_non_pad_indices)\n if max_pads_to_remove > 0:\n padded_input_ids_tensor = padded_input_ids_tensor[:, max_pads_to_remove:]\n if \"attention_mask\" in model_kwargs:\n model_kwargs[\"attention_mask\"] = model_kwargs[\"attention_mask\"][\n :, max_pads_to_remove:\n ]\n if eos_token_id_tensor is not None:\n for i, tokens in enumerate(next_tokens):\n for token in tokens:\n unfinished_sequences[i] = unfinished_sequences[i] & (\n token != eos_token_id_tensor\n )\n return padded_input_ids_tensor, model_kwargs, unfinished_sequences\n\ndef check_byte_mappings(tokenizer):\n vocab = tokenizer.get_vocab()\n g_prefix_count = sum(token.startswith(\"\u0120\") for token in vocab)\n u_prefix_count = sum(token.startswith(\"\u2581\") for token in vocab)\n byte_mapping = {}\n if g_prefix_count > u_prefix_count:\n for byte_val in range(128):\n byte_char = chr(byte_val)\n token_id = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(byte_char))[0]\n hex_token = f\"<0x{byte_val:02X}>\"\n byte_mapping[hex_token] = token_id\n else:\n for byte_val in range(256):\n hex_token = f\"<0x{byte_val:02X}>\"\n if hex_token == \"<0x09>\" and hex_token not in vocab:\n continue\n if hex_token not in vocab:\n raise ValueError(\n f\"Token {hex_token} not found in tokenizer's vocabulary.\"\n )\n byte_mapping[hex_token] = vocab[hex_token]\n return byte_mapping\n\ndef get_vocab_union_and_mapping(tokenizers):\n vocab_union = set()\n tokenizers_mapping = []\n byte_mappings_list = []\n for byte_val in range(256):\n vocab_union.add(f\"<0x{byte_val:02X}>\")\n for tokenizer in tokenizers:\n vocab = tokenizer.get_vocab()\n token_set = set()\n mapping = {}\n byte_mapping = check_byte_mappings(tokenizer)\n byte_mappings_list.append(byte_mapping)\n for hex_token, token_id in byte_mapping.items():\n actual_tokens = [token for token, id in vocab.items() if id == token_id]\n if len(actual_tokens) != 1:\n raise ValueError(\n f\"Multiple tokens/ Zero token found for token ID {token_id} in tokenizer's vocabulary.\"\n )\n del vocab[actual_tokens[0]]\n g_prefix_count = sum(token.startswith(\"\u0120\") for token in vocab)\n u_prefix_count = sum(token.startswith(\"\u2581\") for token in vocab)\n if g_prefix_count > u_prefix_count:\n for token, token_id in vocab.items():\n processed_token = token.replace(\"\u0120\", \" \").replace(\"\u010a\", \"\\n\")\n token_set.add(processed_token)\n mapping[token_id] = processed_token\n else:\n for token, token_id in vocab.items():\n if token.startswith(\"\u2581\"):\n processed_token = token.replace(\"\u2581\", \" \")\n else:\n processed_token = token\n token_set.add(processed_token)\n mapping[token_id] = processed_token\n vocab_union = vocab_union.union(token_set)\n tokenizers_mapping.append(mapping)\n vocab_to_index = {token: i for i, token in enumerate(vocab_union)}\n index_to_vocab = {index: token for token, index in vocab_to_index.items()}\n for tokenizer, byte_mapping, mapping in zip(\n tokenizers, byte_mappings_list, tokenizers_mapping\n ):\n for token_id, token in mapping.items():\n mapping[token_id] = vocab_to_index[token]\n bbpe_mapping = {\n **{f\"<0x{hex(i)[2:].upper()}>\": chr(i) for i in range(0x30, 0x3A)},\n **{f\"<0x{hex(i)[2:].upper()}>\": chr(i) for i in range(0x41, 0x5B)},\n **{f\"<0x{hex(i)[2:].upper()}>\": chr(i) for i in range(0x61, 0x7B)},\n }\n for hex_token, original_token_id in byte_mapping.items():\n if (\n not all(len(bm) == 128 for bm in byte_mappings_list)\n and len(byte_mapping) == 128\n ):\n if hex_token in bbpe_mapping:\n mapping[original_token_id] = vocab_to_index[bbpe_mapping[hex_token]]\n continue\n mapping[original_token_id] = vocab_to_index[hex_token]\n return vocab_union, tokenizers_mapping, index_to_vocab, byte_mappings_list\n\ndef create_mapping_matrix(mapping, union_vocab_size, model_vocab_size):\n if model_vocab_size == 151646:\n logger.warning(\n \"The qwen1.5 series has been detected, where the length of tokenizer.get_vocab() and the vocab_size in the model config are inconsistent. We have forcefully set it to the latter. https://github.com/QwenLM/Qwen1.5/issues/29\"\n )\n model_vocab_size = 151936\n indices = []\n values = []\n for model_token_id, unified_token_index in mapping.items():\n indices.append([model_token_id, unified_token_index])\n values.append(1.0)\n indices = torch.tensor(\n indices, dtype=torch.long\n ).t()\n values = torch.tensor(values, dtype=torch.float)\n size = torch.Size([model_vocab_size, union_vocab_size])\n mapping_matrix = torch.sparse_coo_tensor(indices, values, size, device=\"cuda\")\n return mapping_matrix\n\ndef check_until(until, cached_batch_output_ids, tokenizers, merged_token_ids):\n if len(cached_batch_output_ids) != len(merged_token_ids[0]):\n raise ValueError(\n f\"len(cached_batch_output_ids):{len(cached_batch_output_ids)} != len(merged_token_ids[0]): {len(merged_token_ids[0])}\"\n )\n for i, _ in enumerate(cached_batch_output_ids):\n cached_batch_output_ids[i] = cached_batch_output_ids[i] + merged_token_ids[0][i]\n tmp_text = tokenizers[0].decode(cached_batch_output_ids[i])\n if until:\n for stop_txt in until:\n if stop_txt in tmp_text:\n for j, tokenizer in enumerate(tokenizers):\n merged_token_ids[j][i] = merged_token_ids[j][i] + [\n tokenizer.eos_token_id\n ]\n break\n return cached_batch_output_ids, merged_token_ids\n\ndef check_threshold_ensemble(tmp_outputs_refs, primary_index, threshold):\n if primary_index == -1:\n tmp = tmp_outputs_refs\n outputs = [t[0] for t in tmp]\n outputs_times = [t[1] for t in tmp]\n need_ensemble = True\n else:\n primary_model_outputs, primary_model_outputs_times = tmp_outputs_refs[primary_index]\n if primary_model_outputs.shape[0] != 1:\n raise ValueError(\"For thresholded ensemble, we only support batch size of 1.\")\n max_probs, _ = torch.max(primary_model_outputs, dim=1)\n if max_probs.item() > threshold:\n for i, ref in enumerate(tmp_outputs_refs):\n if i != primary_index:\n continue\n outputs = [None] * len(tmp_outputs_refs)\n outputs[primary_index] = primary_model_outputs\n outputs_times = [primary_model_outputs_times] * len(tmp_outputs_refs)\n need_ensemble = False\n else:\n tmp = tmp_outputs_refs\n outputs = [t[0] for t in tmp]\n outputs_times = [t[1] for t in tmp]\n need_ensemble = True\n return outputs, outputs_times, need_ensemble\n\ndef merge_and_convert_tokens(\n outputs,\n tokenizers,\n mapping_matrices,\n vocab_union,\n index_to_vocab,\n special_prefix_token,\n byte_mappings_list,\n primary_index,\n threshold,\n need_ensemble,\n tmp_outputs_times,\n):\n eos_token_list = [tokenizer.eos_token for tokenizer in tokenizers]\n eos_token_list.extend([\"<|end_of_text|>\", \"<|endoftext|>\", \"<|im_end|>\", \"<|end|>\"])\n for i, output in enumerate(outputs):\n if need_ensemble:\n if output is None:\n raise ValueError(\n \"We detect a probability vector of None, which need to excute ensemble!\"\n )\n else:\n if output is not None and i != primary_index:\n raise ValueError(\n \"We detect a probability vector from non-primary model, but no ensemble excuted!\"\n )\n if primary_index == -1:\n merged_probs = torch.zeros(\n (outputs[0].size(0), len(vocab_union)), device=\"cuda\"\n )\n else:\n merged_probs = torch.zeros(\n (outputs[primary_index].size(0), len(vocab_union)), device=\"cuda\"\n )\n if need_ensemble:\n for output, mapping_matrix in zip(outputs, mapping_matrices):\n transformed_probs = torch.sparse.mm(output, mapping_matrix)\n merged_probs += transformed_probs\n else:\n transformed_probs = torch.sparse.mm(\n outputs[primary_index], mapping_matrices[primary_index]\n )\n merged_probs += transformed_probs\n logger.info(\"GaC do not ensemble in this step.\")\n max_token_indices = torch.argmax(merged_probs, dim=1)\n max_tokens = [index_to_vocab[index.item()] for index in max_token_indices]\n logger.info(f\"Token chosen by GaC: {str(max_tokens)}\\n\")\n batch_token_ids = [\n [] for _ in range(len(tokenizers))\n ]\n for i, tokenizer in enumerate(tokenizers):\n for token in max_tokens:\n if token in eos_token_list:\n token_id = [tokenizer.eos_token_id]\n else:\n token_id = get_token_ids(\n tokenizer,\n token,\n special_prefix_token[tokenizer],\n byte_mappings_list[i],\n )\n batch_token_ids[i].append(token_id)\n return batch_token_ids\n\ndef get_token_ids(tokenizer, token, special_prefix_token, byte_mapping):\n if token in byte_mapping:\n return [byte_mapping[token]]\n if byte_mapping != 128:\n prefix_tokens = [special_prefix_token, \";\"]\n for prefix_token in prefix_tokens:\n token_id_list1 = tokenizer.encode(prefix_token, add_special_tokens=False)\n token_id_list2 = tokenizer.encode(\n prefix_token + token, add_special_tokens=False\n )\n if token_id_list2[: len(token_id_list1)] == token_id_list1:\n result = token_id_list2[len(token_id_list1) :]\n if result:\n return result\n logger.warning(f\"Warning: Token '{token}' may not be tokenized as expected.\")\n return tokenizer.encode(token, add_special_tokens=False)\n\ndef find_special_underscore_token(tokenizer):\n vocab = tokenizer.get_vocab()\n count_prefix_G = sum(1 for token in vocab if token.startswith(\"\u0120\"))\n count_prefix_underscore = sum(1 for token in vocab if token.startswith(\"\u2581\"))\n if count_prefix_G > count_prefix_underscore:\n return \"\"\n underscore_tokens = [\n token for token in vocab if token.startswith(\"\u2581\") and token != \"\u2581\"\n ]\n special_tokens = []\n for token in tqdm(underscore_tokens, desc=\"Analyzing tokens\"):\n cleaned_token = token[1:]\n if (\n not any(\n token in other_token\n for other_token in underscore_tokens\n if other_token != token\n )\n and token.count(\"\u2581\") == 1\n and cleaned_token.strip() != \"\"\n ):\n special_tokens.append(cleaned_token)\n if not special_tokens:\n raise ValueError(\"No special underscore token found that meets the criteria.\")\n return min(special_tokens, key=lambda x: (len(x), x))\n\ndef get_special_prefix_tokens_for_all(tokenizers):\n special_prefix_tokens = {}\n for tokenizer in tokenizers:\n if tokenizer.vocab_size == 256000:\n logger.info(\"gemma-it detected, use '\u00a2' as special_prefix_token\")\n special_prefix_tokens[tokenizer] = \"\u00a2\"\n continue\n token = find_special_underscore_token(tokenizer)\n special_prefix_tokens[tokenizer] = token\n return special_prefix_tokens\n\ndef greedy_search(\n model,\n input_ids: torch.LongTensor,\n logits_processor: Optional[LogitsProcessorList] = None,\n stopping_criteria: Optional[StoppingCriteriaList] = None,\n max_length: Optional[int] = None,\n pad_token_id: Optional[int] = None,\n eos_token_id: Optional[Union[int, List[int]]] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n output_scores: Optional[bool] = None,\n return_dict_in_generate: Optional[bool] = None,\n synced_gpus: bool = False,\n streamer: Optional[\"BaseStreamer\"] = None,\n **model_kwargs,\n) -> Union[GreedySearchOutput, torch.LongTensor]:\n logits_processor = (\n logits_processor if logits_processor is not None else LogitsProcessorList()\n )\n stopping_criteria = (\n stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()\n )\n if max_length is not None:\n warnings.warn(\n \"`max_length` is deprecated in this function, use\"\n \" `stopping_criteria=StoppingCriteriaList([MaxLengthCriteria(max_length=max_length)])` instead.\",\n UserWarning,\n )\n stopping_criteria = validate_stopping_criteria(stopping_criteria, max_length)\n pad_token_id = (\n pad_token_id\n if pad_token_id is not None\n else model.generation_config.pad_token_id\n )\n eos_token_id = (\n eos_token_id\n if eos_token_id is not None\n else model.generation_config.eos_token_id\n )\n if isinstance(eos_token_id, int):\n eos_token_id = [eos_token_id]\n eos_token_id_tensor = (\n torch.tensor(eos_token_id).to(input_ids.device)\n if eos_token_id is not None\n else None\n )\n output_scores = (\n output_scores\n if output_scores is not None\n else model.generation_config.output_scores\n )\n output_attentions = (\n output_attentions\n if output_attentions is not None\n else model.generation_config.output_attentions\n )\n output_hidden_states = (\n output_hidden_states\n if output_hidden_states is not None\n else model.generation_config.output_hidden_states\n )\n return_dict_in_generate = (\n return_dict_in_generate\n if return_dict_in_generate is not None\n else model.generation_config.return_dict_in_generate\n )\n scores = () if (return_dict_in_generate and output_scores) else None\n model_kwargs = model._get_initial_cache_position(input_ids, model_kwargs)\n if model.config.is_encoder_decoder:\n raise Exception(\"We only support decorder arch!\")\n unfinished_sequences = torch.ones(\n input_ids.shape[0], dtype=torch.long, device=input_ids.device\n )\n this_peer_finished = False\n return {\n \"input_ids\": input_ids,\n \"model_kwargs\": model_kwargs,\n \"output_attentions\": output_attentions,\n \"output_hidden_states\": output_hidden_states,\n \"stopping_criteria\": stopping_criteria,\n \"logits_processor\": logits_processor,\n \"scores\": scores,\n \"pad_token_id\": pad_token_id,\n \"eos_token_id_tensor\": eos_token_id_tensor,\n \"unfinished_sequences\": unfinished_sequences,\n \"this_peer_finished\": this_peer_finished,\n }\n\ndef get_one_token(model, state):\n input_ids = state[\"input_ids\"]\n model_kwargs = state[\"model_kwargs\"]\n output_attentions = state[\"output_attentions\"]\n output_hidden_states = state[\"output_hidden_states\"]\n logits_processor = state[\"logits_processor\"]\n model_inputs = model.prepare_inputs_for_generation(input_ids, **model_kwargs)\n with torch.no_grad():\n outputs = model(\n **model_inputs,\n return_dict=True,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n )\n next_token_logits = outputs.logits[:, -1, :]\n next_tokens_scores = logits_processor(input_ids, next_token_logits)\n next_tokens_scores = F.softmax(next_tokens_scores, dim=-1)\n return next_tokens_scores, outputs\n\ndef generate_prepare(\n model,\n inputs: Optional[torch.Tensor] = None,\n generation_config: Optional[GenerationConfig] = None,\n logits_processor: Optional[LogitsProcessorList] = None,\n stopping_criteria: Optional[StoppingCriteriaList] = None,\n prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,\n synced_gpus: Optional[bool] = None,\n assistant_model: Optional[\"PreTrainedModel\"] = None,\n streamer: Optional[\"BaseStreamer\"] = None,\n negative_prompt_ids: Optional[torch.Tensor] = None,\n negative_prompt_attention_mask: Optional[torch.Tensor] = None,\n **kwargs,\n) -> Union[GenerateOutput, torch.LongTensor]:\n model._validate_model_class()\n tokenizer = kwargs.pop(\n \"tokenizer\", None\n )\n generation_config, model_kwargs = model._prepare_generation_config(\n generation_config, **kwargs\n )\n if 'model_name_list' in model_kwargs:\n del model_kwargs['model_name_list']\n model._validate_model_kwargs(model_kwargs.copy())\n model._validate_assistant(assistant_model)\n if synced_gpus is None:\n if is_deepspeed_zero3_enabled() and dist.get_world_size() > 1:\n synced_gpus = True\n else:\n synced_gpus = False\n logits_processor = (\n logits_processor if logits_processor is not None else LogitsProcessorList()\n )\n stopping_criteria = (\n stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()\n )\n accepts_attention_mask = \"attention_mask\" in set(\n inspect.signature(model.forward).parameters.keys()\n )\n requires_attention_mask = \"encoder_outputs\" not in model_kwargs\n kwargs_has_attention_mask = model_kwargs.get(\"attention_mask\", None) is not None\n inputs_tensor, model_input_name, model_kwargs = model._prepare_model_inputs(\n inputs, generation_config.bos_token_id, model_kwargs\n )\n batch_size = inputs_tensor.shape[0]\n device = inputs_tensor.device\n model._prepare_special_tokens(\n generation_config, kwargs_has_attention_mask, device=device\n )\n if not model.config.is_encoder_decoder and not is_torchdynamo_compiling():\n if (\n generation_config._pad_token_tensor is not None\n and batch_size > 1\n and len(inputs_tensor.shape) == 2\n and torch.sum(inputs_tensor[:, -1] == generation_config._pad_token_tensor)\n > 0\n ):\n logger.warning(\n \"A decoder-only architecture is being used, but right-padding was detected! For correct \"\n \"generation results, please set `padding_side='left'` when initializing the tokenizer.\"\n )\n if not model.config.is_encoder_decoder and model_input_name == \"inputs_embeds\":\n model_kwargs[\"use_cache\"] = True\n else:\n model_kwargs[\"use_cache\"] = generation_config.use_cache\n if (\n not kwargs_has_attention_mask\n and requires_attention_mask\n and accepts_attention_mask\n ):\n model_kwargs[\"attention_mask\"] = model._prepare_attention_mask_for_generation(\n inputs_tensor,\n generation_config._pad_token_tensor,\n generation_config._eos_token_tensor,\n )\n if model.config.is_encoder_decoder and \"encoder_outputs\" not in model_kwargs:\n model_kwargs = model._prepare_encoder_decoder_kwargs_for_generation(\n inputs_tensor, model_kwargs, model_input_name, generation_config\n )\n if model.config.is_encoder_decoder:\n input_ids, model_kwargs = model._prepare_decoder_input_ids_for_generation(\n batch_size=batch_size,\n model_input_name=model_input_name,\n model_kwargs=model_kwargs,\n decoder_start_token_id=generation_config._decoder_start_token_tensor,\n device=inputs_tensor.device,\n )\n else:\n input_ids = (\n inputs_tensor\n if model_input_name == \"input_ids\"\n else model_kwargs.pop(\"input_ids\")\n )\n if generation_config.token_healing:\n input_ids = model.heal_tokens(input_ids, tokenizer)\n if streamer is not None:\n streamer.put(input_ids.cpu())\n input_ids_length = input_ids.shape[-1]\n has_default_max_length = (\n kwargs.get(\"max_length\") is None and generation_config.max_length is not None\n )\n has_default_min_length = (\n kwargs.get(\"min_length\") is None and generation_config.min_length is not None\n )\n generation_config = model._prepare_generated_length(\n generation_config=generation_config,\n has_default_max_length=has_default_max_length,\n has_default_min_length=has_default_min_length,\n model_input_name=model_input_name,\n inputs_tensor=inputs_tensor,\n input_ids_length=input_ids_length,\n )\n use_dynamic_cache_by_default = False\n if \"mamba\" in model.__class__.__name__.lower():\n cache_name = \"cache_params\"\n else:\n cache_name = \"past_key_values\"\n if (\n assistant_model is not None\n and generation_config.cache_implementation is not None\n and model._supports_default_dynamic_cache()\n ):\n logger.warning_once(\n \"An assistant model is provided, using a dynamic cache instead of a cache of type=\"\n f\"'{generation_config.cache_implementation}'.\"\n )\n generation_config.cache_implementation = None\n if (model_kwargs.get(cache_name) is not None) and is_torchdynamo_compiling():\n raise ValueError(\n \"Passing `past_key_values` is not supported when compiling `model.generate` with torch.compile -- you \"\n \"may get incorrect outputs. Please compile `model.forward` only or use the `cache_implementation` \"\n \"input argument.\"\n )\n if generation_config.cache_implementation is not None and (\n model_kwargs.get(cache_name) is not None\n ):\n raise ValueError(\n f\"Passing both `cache_implementation` (used to initialize certain caches) and `{cache_name}` (a \"\n \"Cache object) is unsupported. Please use only one of the two.\"\n )\n elif generation_config.cache_implementation is not None:\n if generation_config.cache_implementation in NEED_SETUP_CACHE_CLASSES_MAPPING:\n if (\n generation_config.cache_implementation == \"static\"\n and not model._supports_static_cache\n ):\n raise ValueError(\n \"This model does not support `cache_implementation='static'`. Please check the following \"\n \"issue: https://github.com/huggingface/transformers/issues/28981\"\n )\n model_kwargs[cache_name] = model._get_cache(\n cache_implementation=generation_config.cache_implementation,\n max_batch_size=generation_config.num_beams\n * generation_config.num_return_sequences\n * batch_size,\n max_cache_len=generation_config.max_length,\n device=device,\n model_kwargs=model_kwargs,\n )\n elif generation_config.cache_implementation == \"quantized\":\n if not model._supports_quantized_cache:\n raise ValueError(\n \"This model does not support the quantized cache. If you want your model to support quantized \"\n \"cache, please open an issue.\"\n )\n cache_config = (\n generation_config.cache_config\n if generation_config.cache_config is not None\n else QuantizedCacheConfig()\n )\n cache_class = QUANT_BACKEND_CLASSES_MAPPING[cache_config.backend]\n if cache_config.backend == \"quanto\" and not is_quanto_available():\n raise ImportError(\n \"You need to install `quanto` in order to use KV cache quantization with quanto backend. \"\n \"Please install it via with `pip install quanto`\"\n )\n elif cache_config.backend == \"HQQ\" and not is_hqq_available():\n raise ImportError(\n \"You need to install `HQQ` in order to use KV cache quantization with HQQ backend. \"\n \"Please install it via with `pip install hqq`\"\n )\n model_kwargs[cache_name] = cache_class(cache_config)\n elif generation_config.cache_implementation == \"offloaded\":\n model_kwargs[cache_name] = OffloadedCache()\n elif (\n generation_config.cache_implementation is None\n and model._supports_default_dynamic_cache()\n ):\n past = model_kwargs.get(cache_name, None)\n requires_cross_attention_cache = (\n model.config.is_encoder_decoder\n or model_kwargs.get(\"encoder_outputs\") is not None\n )\n if past is None:\n model_kwargs[cache_name] = (\n DynamicCache()\n if not requires_cross_attention_cache\n else EncoderDecoderCache(DynamicCache(), DynamicCache())\n )\n use_dynamic_cache_by_default = True\n elif isinstance(past, tuple):\n model_kwargs[cache_name] = (\n DynamicCache.from_legacy_cache(past)\n if not requires_cross_attention_cache\n else EncoderDecoderCache.from_legacy_cache(past)\n )\n use_dynamic_cache_by_default = True\n model._validate_generated_length(\n generation_config, input_ids_length, has_default_max_length\n )\n generation_mode = generation_config.get_generation_mode(assistant_model)\n if streamer is not None and (generation_config.num_beams > 1):\n raise ValueError(\n \"`streamer` cannot be used with beam search (yet!). Make sure that `num_beams` is set to 1.\"\n )\n if not is_torchdynamo_compiling() and model.device.type != input_ids.device.type:\n warnings.warn(\n \"You are calling .generate() with the `input_ids` being on a device type different\"\n f\" than your model's device. `input_ids` is on {input_ids.device.type}, whereas the model\"\n f\" is on {model.device.type}. You may experience unexpected behaviors or slower generation.\"\n \" Please make sure that you have put `input_ids` to the\"\n f\" correct device by calling for example input_ids = input_ids.to('{model.device.type}') before\"\n \" running `.generate()`.\",\n UserWarning,\n )\n prepared_logits_processor = model._get_logits_processor(\n generation_config=generation_config,\n input_ids_seq_length=input_ids_length,\n encoder_input_ids=inputs_tensor,\n prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,\n logits_processor=logits_processor,\n device=inputs_tensor.device,\n model_kwargs=model_kwargs,\n negative_prompt_ids=negative_prompt_ids,\n negative_prompt_attention_mask=negative_prompt_attention_mask,\n )\n prepared_stopping_criteria = model._get_stopping_criteria(\n generation_config=generation_config,\n stopping_criteria=stopping_criteria,\n tokenizer=tokenizer,\n **kwargs,\n )\n return greedy_search(\n model,\n input_ids,\n logits_processor=prepared_logits_processor,\n stopping_criteria=prepared_stopping_criteria,\n pad_token_id=generation_config.pad_token_id,\n eos_token_id=generation_config.eos_token_id,\n output_scores=generation_config.output_scores,\n return_dict_in_generate=generation_config.return_dict_in_generate,\n synced_gpus=synced_gpus,\n streamer=streamer,\n **model_kwargs,\n )" }, { "task_id": 2, "indent": 1, "completion_path": "./utils/gac_gen_utils.py", "script": "\npython main.py\n", "latex_code": "\n\\subsection{\\textsc{GaC} Ensembling}\n\\label{sec3-3}\nAt the start of text generation, we convert the input \\textit{prompt} into token ID sequences for each LLM. We denote the tokenizer of \\(\\textit{LLM}_i\\) as \\(\\mathcal{T}^{\\,i} : \\textit{text} \\rightarrow (\\tau_1, \\tau_2, \\ldots, \\tau_m)\\), which converts the input text into a sequence of token IDs. We calculate:\n\\begin{equation}\n\\label{eq2}\n\\mathcal{I}^{\\,i} = \\mathcal{T}^{\\,i}(\\textit{prompt}) \\quad \\text{for } i = 1, \\ldots, n\n\\end{equation}\nwhere \\(\\mathcal{I}^{\\,i}\\) is the input token ID sequence for \\(\\textit{LLM}_i\\).\n\nFor each generation step, we input \\(\\mathcal{I}^{\\,i}\\) into \\(\\textit{LLM}_i\\) to obtain \\(p^i(\\cdot\\,|\\,\\mathcal{I}^{\\,i}) \\in \\mathbb{R}^{|V^i|}\\), which represents the probability vector for the next token. These vectors are then mapped to the union vocabulary dimensions and averaged:\n\\begin{equation}\n\\label{eq3}\nq(\\cdot) = \\frac{1}{n} \\sum_{i=1}^{n} p^i(\\cdot\\,|\\,\\mathcal{I}^{\\,i}) \\cdot \\mathbf{M}^{i},\n\\end{equation}\nwhere \\(q(\\cdot)\\) is the ensemble probability vector. In Sec.\\ref{sec4-3}, we experimented with different ensemble weights and decided to use the average. We then sample a token \\(x \\sim q(\\cdot)\\) as the result of this step. Finally, the sampled token is converted back into token IDs for each LLM and appended to \\(\\mathcal{I}^{\\,i}\\):\n\\begin{equation}\n\\label{eq4}\n\\mathcal{I}^{\\,i} \\leftarrow \\mathcal{I}^{\\,i}{}^{\\frown} \\mathcal{T}^{\\,i}(x) \\quad \\text{for } i = 1, \\ldots, n\n\\end{equation}\n\nWe repeat (\\ref{eq3}) and (\\ref{eq4}) until the stopping criteria are met, such as outputting an end-of-sentence token or reaching the maximum length, as shown in Fig.\\ref{fig_3}.\\footnote{\\footnotesize We provide step-by-step examples in Appx.\\ref{sec:appendix-example}.} In our implementation, different LLMs run in parallel on different GPUs, so the duration of each step is equal to the time taken by the slowest LLM. Since we have not modified a complete forward pass, our approach is compatible with techniques such as vLLM, DeepSpeed, quantization, and hardware optimizations \\citep{kwon2023efficient, rasley2020deepspeed}.\n\n\\subsection{Ensembling Key Tokens with Threshold}\n\\label{sec3-4}\nAs mentioned in the last part of Sec.\\ref{ensemble-with-t}, most tokens do not significantly affect the correctness of the response. From Tab.\\ref{tab1}, we can see that LLMs and CV models have similar ECE levels, suggesting that the confidence scores of LLMs may reflect accuracy to some extent. Therefore, we also experiment with ensembling only the steps with confidence below a threshold \\( t \\). We choose a model as the gate, denoted \\(\\textit{LLM}_g\\), and use its maximum probability at each step as the confidence score. During the ensemble, we replace the original (\\ref{eq3}) with:\n\\begin{equation}\n\\label{eq5}\n\\resizebox{.93\\hsize}{!}{$\nq(\\cdot) =\n\\begin{cases}\n\\frac{1}{n} \\sum_{i} p^i(\\cdot\\,|\\,\\mathcal{I}^{\\,i}) \\cdot \\mathbf{M}^{i} & \\textit{if } \\max(p^g(\\cdot\\,|\\,\\mathcal{I}^{\\,g})) \\leq t \\\\\np^g(\\cdot\\,|\\,\\mathcal{I}^{\\,g}) \\cdot \\mathbf{M}^{g} & \\textit{otherwise}.\n\\end{cases}\n$}\n\\end{equation}\n\nNote that apart from \\(\\textit{LLM}_g\\), the other LLMs are not computed at every step, so their KV caches become stale. While there has been research using partial KV caches \\citep{barad2023leveraging}, for simplicity our work disables the KV caches of all LLMs except \\(\\textit{LLM}_g\\). This is an area for improvement and is listed in our future work.\n\n", "namespace": "utils.gac_gen_utils.generate_ensemble_response", "type": "function", "signature_position": [ 20, 32 ], "body_position": [ 33, 88 ], "ReferenceCode_With_Comments": "\nrefs = []\nensemble_weight_list = []\nfor model_actor in model_actors_list:\n refs.append(model_actor.generate_prepare(**kwargs))\n ensemble_weight_list.append(model_actor.get_ensemble_weight())\n\ncached_output_ids = [\n [] for _ in model_actors_list[0].get_input_ids()\n]\n\nwhile True:\n tmp_outputs_refs = [\n model_actor.get_one_token() for model_actor in model_actors_list\n ]\n\n # -----------------------------------------------------------------------\n # Snippet 1: Within the iterative generation process, the first step is performing threshold gating to decide whether to ensemble or use only the gate model\u2019s output. \n # -----------------------------------------------------------------------\n # [Begin Snippet 1]\n tmp_outputs, tmp_outputs_times, need_ensemble = check_threshold_ensemble(\n tmp_outputs_refs, primary_index, threshold\n )\n # [End Snippet 1]\n\n # -----------------------------------------------------------------------\n # Snippet 2: Within the iterative generation process, the second step is merging models' top token distribution into a single distribution (Eq. (3)) if needed, then sample and decode that next token for each model.\n # -----------------------------------------------------------------------\n # [Begin Snippet 2]\n merged_token_ids = merge_and_convert_tokens(\n tmp_outputs,\n tokenizers,\n mapping_matrices,\n vocab_union,\n index_to_vocab,\n special_prefix_tokens_dict,\n byte_mappings_list,\n primary_index,\n threshold,\n need_ensemble,\n tmp_outputs_times,\n )\n # [End Snippet 2]\n\n # -----------------------------------------------------------------------\n # Snippet 3: Within the iterative generation process, the third step is checking if an \u201cuntil\u201d phrase has been triggered. If so, insert an end-of-sequence token. Also update each model\u2019s input IDs with the newly chosen token.\n # -----------------------------------------------------------------------\n # [Begin Snippet 3]\n cached_output_ids, merged_token_ids = check_until(\n until, cached_output_ids, tokenizers, merged_token_ids\n )\n\n refs = []\n for i, model_actor in enumerate(model_actors_list):\n ref = model_actor.update_input_ids_and_model_kwargs(\n next_tokens_list=merged_token_ids[i]\n )\n refs.append(ref)\n # [End Snippet 3]\n\n # -----------------------------------------------------------------------\n # Snippet 4: Within the iterative generation process, the fourth step is synchronizing the \u201cunfinished\u201d states across models, check if any model signals completion, and if so, terminate the loop.\n # -----------------------------------------------------------------------\n # [Begin Snippet 4]\n unfinished_sequences_list = [\n model_actor.get_unfinished_sequences()\n for model_actor in model_actors_list\n ]\n synced_unfinished_sequences = synchronize_unfinished_sequences(\n unfinished_sequences_list\n )\n update_refs = [\n model_actor.update_unfinished_sequences(synced_unfinished_sequences)\n for model_actor in model_actors_list\n ]\n\n finish_refs = [\n model_actor.check_if_stop() for model_actor in model_actors_list\n ]\n finish = any(finish_refs)\n if finish:\n break\n # [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Once the generation loop ends, retrieve the final token IDs from the first model and return them. This completes the generation process until the stopping criteria is met.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\noutput = model_actors_list[0].get_input_ids()\nreturn output\n# [End Snippet 5]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - Special token conversion workflow: After sampling a token \\( x \\sim q(\\cdot) \\), the token must be mapped back to each model\u2019s token ID space using tokenizer-specific rules. This includes handling byte tokens (e.g., converting \"<0xNN>\" strings to actual byte values) and resolving special prefix tokens (e.g., prepending \",\" to align tokenizer behaviors).\n - Sequence synchronization logic: After appending tokens to \\(\\mathcal{I}^{\\,i}\\), all models must synchronize their completion status (e.g., whether they have generated an end-of-sequence token).\n - KV cache management protocol: When the confidence threshold is exceeded, non-primary models must have their KV caches permanently disabled (not just cleared once) for subsequent steps.\n - Sparse matrix operations: The mapping matrices \\(\\mathbf{M}^{i}\\) are implemented as sparse tensors, requiring specialized sparse-dense matrix multiplication (e.g., `torch.sparse.mm`) for efficient computation.\n \n Mismatched Details:\n - Ensemble weight definition: In the LaTeX code, it assumes uniform averaging (\\(1/n\\)). but for code implementation, it supports model-specific ensemble weights (via `ensemble_weight_list`). This creates a discrepancy when non-uniform weights are used, as the code computes \\( q(\\cdot) = \\sum_{i=1}^{n} w_i \\cdot p^i(\\cdot) \\cdot \\mathbf{M}^{i} \\) where \\(w_i\\) are learnable/scalar weights.\n", "Missing_details": [], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - model_actors_list (List[utils.ray_actor.ModelGenerator]): A list of model actors, where each item within the list is a ModelGenerator object defined in the utils.ray_actor.ModelGenerator.\n - model_name_list (List[str]): A list of model names corresponding to each model actor. Used for tracking or logging which model contributed to the ensemble output.\n - tokenizers (List[transformers.LLamaTokenizerFast]): A list of tokenizers corresponding to each language model, where each item within the list is a LLamaTokenizerFast object.\n - vocab_union (Set): A set containing the union of all tokens from the tokenizers' vocabularies.\n - mapping_matrices (List[torch.sparse_coo_tensor]): A list of sparse COO tensors, each representing a mapping matrix from a model's tokenizer token IDs to the token IDs in the unified vocabulary. Each matrix corresponds to a tokenizer and maps its original token IDs to new token IDs in the unified vocabulary. The shape of each matrix is [model_vocab_size, len(vocab_union)], where model_vocab_size is the size of the tokenizer's vocabulary.\n - index_to_vocab (Dict): A dictionary mapping indices in the unified vocabulary to the actual string tokens. This is used for converting combined distribution indices back into tokens for logging or final output.\n - special_prefix_tokens_dict (Dict): serves as a simple, user-defined mapping that ties each tokenizer to a custom prefix marker\u2014in this case, ','. Depending on the broader codebase, this prefix might get prepended to the prompt, appended before certain tokens, or used to separate distinct conversation turns.\n - Dictionary Keys:\n Each key is a LlamaTokenizerFast instance. Notice how the dictionary is using actual Python objects (the tokenizer instances) as keys instead of strings or integers.\n - Dictionary Value:\n For both tokenizers, the dictionary value is the same\u2014the string ','.\n - byte_mappings_list (List[Dict]): A list of dictionaries, where each dictionary corresponds to a tokenizer from the input list and provides a mapping of byte value tokens from '<0x00>' to '<0xFF>' to their original token IDs in the tokenizer's vocabulary. This mapping is used to ensure consistency and to facilitate the identification and replacement of these tokens in the unified vocabulary.\n - primary_index (int): The index of the primary model in the model list.\n - threshold (float): The confidence threshold for the primary model. If the model's highest probability exceeds this value, ensemble is not performed.\n - until (List[str]): A list of stopping tokens. If any of these tokens appear in a generated sequence, that sequence should stop.\n - kwargs (Dict): Additional keyword arguments that might be required by the underlying model actors, including \"max_new_tokens\".\n", "Arguments_list": [ { "name": "model_actors_list", "string": "- model_actors_list (List[utils.ray_actor.ModelGenerator]): A list of model actors, where each item within the list is a ModelGenerator object defined in the utils.ray_actor.ModelGenerator.", "dependency": "utils.ray_actor.ModelGenerator" }, { "name": "model_name_list", "string": "- model_name_list (List[str]): A list of model names corresponding to each model actor. Used for tracking or logging which model contributed to the ensemble output.", "dependency": null }, { "name": "tokenizers", "string": "- tokenizers (List[transformers.LLamaTokenizerFast]): A list of tokenizers corresponding to each language model, where each item within the list is a LLamaTokenizerFast object.", "dependency": "transformers.LLamaTokenizerFast" }, { "name": "vocab_union", "string": "- vocab_union (Set): A set containing the union of all tokens from the tokenizers' vocabularies.", "dependency": null }, { "name": "mapping_matrices", "string": "- mapping_matrices (List[torch.sparse_coo_tensor]): A list of sparse COO tensors, each representing a mapping matrix from a model's tokenizer token IDs to the token IDs in the unified vocabulary. Each matrix corresponds to a tokenizer and maps its original token IDs to new token IDs in the unified vocabulary. The shape of each matrix is [model_vocab_size, len(vocab_union)], where model_vocab_size is the size of the tokenizer's vocabulary.", "dependency": "torch.sparse_coo_tensor" }, { "name": "index_to_vocab", "string": "- index_to_vocab (Dict): A dictionary mapping indices in the unified vocabulary to the actual string tokens. This is used for converting combined distribution indices back into tokens for logging or final output.", "dependency": null }, { "name": "special_prefix_tokens_dict", "string": "\n- special_prefix_tokens_dict (Dict): serves as a simple, user-defined mapping that ties each tokenizer to a custom prefix marker\u2014in this case, ','. Depending on the broader codebase, this prefix might get prepended to the prompt, appended before certain tokens, or used to separate distinct conversation turns.\n - Dictionary Keys:\n Each key is a LlamaTokenizerFast instance. Notice how the dictionary is using actual Python objects (the tokenizer instances) as keys instead of strings or integers.\n - Dictionary Value:\n For both tokenizers, the dictionary value is the same\u2014the string ','.\n", "dependency": null }, { "name": "byte_mappings_list", "string": "- byte_mappings_list (List[Dict]): A list of dictionaries, where each dictionary corresponds to a tokenizer from the input list and provides a mapping of byte value tokens from '<0x00>' to '<0xFF>' to their original token IDs in the tokenizer's vocabulary. This mapping is used to ensure consistency and to facilitate the identification and replacement of these tokens in the unified vocabulary.", "dependency": null }, { "name": "primary_index", "string": "- primary_index (int): The index of the primary model in the model list.", "dependency": null }, { "name": "threshold", "string": "- threshold (float): The confidence threshold for the primary model. If the model's highest probability exceeds this value, ensemble is not performed.", "dependency": null }, { "name": "until", "string": "- until (List[str]): A list of stopping tokens. If any of these tokens appear in a generated sequence, that sequence should stop.", "dependency": null }, { "name": "kwargs", "string": "- kwargs (Dict): Additional keyword arguments that might be required by the underlying model actors, including 'max_new_tokens'.", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n Intra File Dependencies:\n - check_threshold_ensemble\n - merge_and_convert_tokens\n - check_until\n - synchronize_unfinished_sequences\n \n Cross File Dependencies:\n - None\n", "intra_file": [ "check_threshold_ensemble", "merge_and_convert_tokens", "check_until", "synchronize_unfinished_sequences" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs: \n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - output (torch.Tensor, shape=[number of models, sequence length]): This tensor is a batched output of token IDs produced by a language model (or set of models) as a result of text generation. \n", "Return_list": [ { "name": "output", "string": "- output (torch.Tensor, shape=[number of models, sequence length]): This tensor is a batched output of token IDs produced by a language model (or set of models) as a result of text generation.", "dependency": null } ] }, "ori_python_file": "import inspect\nimport warnings\nfrom typing import Callable, List, Optional, Union\nimport os, pickle\nimport torch\nimport torch.distributed as dist\nimport torch.nn.functional as F\nfrom tqdm import tqdm\nfrom transformers.generation import (\n GenerationConfig,\n LogitsProcessorList,\n StoppingCriteriaList,\n validate_stopping_criteria,\n)\nfrom transformers.generation.utils import *\nfrom transformers.generation.utils import GenerateOutput, GreedySearchOutput\nfrom .logger import setup_custom_logger\nlogger = setup_custom_logger(\"TSP\")\n\ndef generate_ensemnble_response(\n model_actors_list,\n tokenizers,\n vocab_union,\n mapping_matrices,\n index_to_vocab,\n special_prefix_tokens_dict,\n byte_mappings_list,\n primary_index,\n threshold,\n until,\n **kwargs,\n):\n refs = []\n ensemble_weight_list = []\n for model_actor in model_actors_list:\n refs.append(model_actor.generate_prepare(**kwargs))\n ensemble_weight_list.append(model_actor.get_ensemble_weight())\n cached_output_ids = [\n [] for _ in model_actors_list[0].get_input_ids()\n ]\n while True:\n tmp_outputs_refs = [\n model_actor.get_one_token() for model_actor in model_actors_list\n ]\n tmp_outputs, tmp_outputs_times, need_ensemble = check_threshold_ensemble(\n tmp_outputs_refs, primary_index, threshold\n )\n merged_token_ids = merge_and_convert_tokens(\n tmp_outputs,\n tokenizers,\n mapping_matrices,\n vocab_union,\n index_to_vocab,\n special_prefix_tokens_dict,\n byte_mappings_list,\n primary_index,\n threshold,\n need_ensemble,\n tmp_outputs_times,\n )\n cached_output_ids, merged_token_ids = check_until(\n until, cached_output_ids, tokenizers, merged_token_ids\n )\n refs = []\n for i, model_actor in enumerate(model_actors_list):\n ref = model_actor.update_input_ids_and_model_kwargs(\n next_tokens_list=merged_token_ids[i]\n )\n refs.append(ref)\n unfinished_sequences_list = [\n model_actor.get_unfinished_sequences()\n for model_actor in model_actors_list\n ]\n synced_unfinished_sequences = synchronize_unfinished_sequences(\n unfinished_sequences_list\n )\n update_refs = [\n model_actor.update_unfinished_sequences(synced_unfinished_sequences)\n for model_actor in model_actors_list\n ]\n finish_refs = [\n model_actor.check_if_stop() for model_actor in model_actors_list\n ]\n finish = any(finish_refs)\n if finish:\n break\n output = model_actors_list[0].get_input_ids()\n return output\n\ndef process_and_log_model_outputs(\n tokenizers, model_name_list, model_outputs, ensemble_weight_list\n):\n for output, tokenizer, model_name, ensemble_weight in zip(\n model_outputs, tokenizers, model_name_list, ensemble_weight_list\n ):\n if output is None:\n logger.info(f\"Token from Model {model_name}: N/A\")\n continue\n max_scores, max_indices = torch.max(output, dim=-1)\n decoded_tokens = [\n tokenizer.decode([idx], skip_special_tokens=False)\n for idx in max_indices.tolist()\n ]\n max_scores_list = [\n round(score.item() / ensemble_weight, 4) for score in max_scores\n ]\n logger.info(\n f\"Token from Model {model_name}: {decoded_tokens} (token id {max_indices.tolist()}) with Conf {max_scores_list}\"\n )\n\ndef synchronize_unfinished_sequences(unfinished_sequences_list):\n device = unfinished_sequences_list[0].device\n first_shape = unfinished_sequences_list[0].shape\n for unfinished_sequences in unfinished_sequences_list:\n if unfinished_sequences.shape != first_shape:\n raise ValueError(\n \"All 'unfinished_sequences' tensors must have the same shape.\"\n )\n sync_tensor = torch.ones_like(unfinished_sequences_list[0]).to(device)\n for unfinished_sequences in unfinished_sequences_list:\n sync_tensor = torch.logical_and(sync_tensor, unfinished_sequences.to(device))\n sync_tensor = sync_tensor.long()\n return sync_tensor\n\ndef update_input_ids_and_model_kwargs(model, state):\n outputs = state[\"outputs\"]\n input_ids = state[\"input_ids\"]\n next_tokens = state[\"next_tokens_list\"]\n model_kwargs = state[\"model_kwargs\"]\n unfinished_sequences = state[\"unfinished_sequences\"]\n pad_token_id = state[\"pad_token_id\"]\n eos_token_id_tensor = state[\"eos_token_id_tensor\"]\n if pad_token_id is None:\n raise ValueError(\"pad_token_id must be defined.\")\n next_tokens = [\n tokens if unfinished else [pad_token_id] * len(tokens)\n for tokens, unfinished in zip(next_tokens, unfinished_sequences)\n ]\n device = input_ids.device\n max_length = max([input_ids.shape[1] + len(tokens) for tokens in next_tokens])\n padded_input_ids = []\n attention_masks = []\n for i, tokens in enumerate(next_tokens):\n input_padding_size = max_length - input_ids.shape[1] - len(tokens)\n padded_input = torch.cat(\n [\n torch.full(\n (1, input_padding_size),\n pad_token_id,\n dtype=torch.long,\n device=device,\n ),\n input_ids[i].unsqueeze(0),\n torch.tensor(tokens, dtype=torch.long, device=device).unsqueeze(0),\n ],\n dim=1,\n )\n padded_input_ids.append(padded_input)\n if \"attention_mask\" in model_kwargs:\n original_attention_mask = model_kwargs[\"attention_mask\"][i]\n updated_attention_mask = torch.cat(\n [\n torch.zeros(input_padding_size, dtype=torch.long, device=device),\n original_attention_mask,\n torch.ones(len(tokens), dtype=torch.long, device=device),\n ]\n )\n attention_masks.append(updated_attention_mask)\n padded_input_ids_tensor = torch.cat(padded_input_ids, dim=0)\n model_kwargs = model._update_model_kwargs_for_generation(\n outputs, model_kwargs, is_encoder_decoder=model.config.is_encoder_decoder\n )\n if attention_masks:\n model_kwargs[\"attention_mask\"] = torch.stack(attention_masks)\n model_kwargs[\"cache_position\"] = torch.tensor(\n [model_kwargs[\"attention_mask\"].shape[1] - 1],\n dtype=torch.int64,\n device=model_kwargs[\"attention_mask\"].device,\n )\n if any(len(tokens) > 1 for tokens in next_tokens):\n model_kwargs[\"past_key_values\"] = None\n first_non_pad_indices = [\n input_id.ne(pad_token_id).nonzero(as_tuple=True)[0][0].item()\n if pad_token_id in input_id\n else 0\n for input_id in padded_input_ids_tensor\n ]\n max_pads_to_remove = min(first_non_pad_indices)\n if max_pads_to_remove > 0:\n padded_input_ids_tensor = padded_input_ids_tensor[:, max_pads_to_remove:]\n if \"attention_mask\" in model_kwargs:\n model_kwargs[\"attention_mask\"] = model_kwargs[\"attention_mask\"][\n :, max_pads_to_remove:\n ]\n if eos_token_id_tensor is not None:\n for i, tokens in enumerate(next_tokens):\n for token in tokens:\n unfinished_sequences[i] = unfinished_sequences[i] & (\n token != eos_token_id_tensor\n )\n return padded_input_ids_tensor, model_kwargs, unfinished_sequences\n\ndef check_byte_mappings(tokenizer):\n vocab = tokenizer.get_vocab()\n g_prefix_count = sum(token.startswith(\"\u0120\") for token in vocab)\n u_prefix_count = sum(token.startswith(\"\u2581\") for token in vocab)\n byte_mapping = {}\n if g_prefix_count > u_prefix_count:\n for byte_val in range(128):\n byte_char = chr(byte_val)\n token_id = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(byte_char))[0]\n hex_token = f\"<0x{byte_val:02X}>\"\n byte_mapping[hex_token] = token_id\n else:\n for byte_val in range(256):\n hex_token = f\"<0x{byte_val:02X}>\"\n if hex_token == \"<0x09>\" and hex_token not in vocab:\n continue\n if hex_token not in vocab:\n raise ValueError(\n f\"Token {hex_token} not found in tokenizer's vocabulary.\"\n )\n byte_mapping[hex_token] = vocab[hex_token]\n return byte_mapping\n\ndef get_vocab_union_and_mapping(tokenizers):\n vocab_union = set()\n tokenizers_mapping = []\n byte_mappings_list = []\n for byte_val in range(256):\n vocab_union.add(f\"<0x{byte_val:02X}>\")\n for tokenizer in tokenizers:\n vocab = tokenizer.get_vocab()\n token_set = set()\n mapping = {}\n byte_mapping = check_byte_mappings(tokenizer)\n byte_mappings_list.append(byte_mapping)\n for hex_token, token_id in byte_mapping.items():\n actual_tokens = [token for token, id in vocab.items() if id == token_id]\n if len(actual_tokens) != 1:\n raise ValueError(\n f\"Multiple tokens/ Zero token found for token ID {token_id} in tokenizer's vocabulary.\"\n )\n del vocab[actual_tokens[0]]\n g_prefix_count = sum(token.startswith(\"\u0120\") for token in vocab)\n u_prefix_count = sum(token.startswith(\"\u2581\") for token in vocab)\n if g_prefix_count > u_prefix_count:\n for token, token_id in vocab.items():\n processed_token = token.replace(\"\u0120\", \" \").replace(\"\u010a\", \"\\n\")\n token_set.add(processed_token)\n mapping[token_id] = processed_token\n else:\n for token, token_id in vocab.items():\n if token.startswith(\"\u2581\"):\n processed_token = token.replace(\"\u2581\", \" \")\n else:\n processed_token = token\n token_set.add(processed_token)\n mapping[token_id] = processed_token\n vocab_union = vocab_union.union(token_set)\n tokenizers_mapping.append(mapping)\n vocab_to_index = {token: i for i, token in enumerate(vocab_union)}\n index_to_vocab = {index: token for token, index in vocab_to_index.items()}\n for tokenizer, byte_mapping, mapping in zip(\n tokenizers, byte_mappings_list, tokenizers_mapping\n ):\n for token_id, token in mapping.items():\n mapping[token_id] = vocab_to_index[token]\n bbpe_mapping = {\n **{f\"<0x{hex(i)[2:].upper()}>\": chr(i) for i in range(0x30, 0x3A)},\n **{f\"<0x{hex(i)[2:].upper()}>\": chr(i) for i in range(0x41, 0x5B)},\n **{f\"<0x{hex(i)[2:].upper()}>\": chr(i) for i in range(0x61, 0x7B)},\n }\n for hex_token, original_token_id in byte_mapping.items():\n if (\n not all(len(bm) == 128 for bm in byte_mappings_list)\n and len(byte_mapping) == 128\n ):\n if hex_token in bbpe_mapping:\n mapping[original_token_id] = vocab_to_index[bbpe_mapping[hex_token]]\n continue\n mapping[original_token_id] = vocab_to_index[hex_token]\n return vocab_union, tokenizers_mapping, index_to_vocab, byte_mappings_list\n\ndef create_mapping_matrix(mapping, union_vocab_size, model_vocab_size):\n if model_vocab_size == 151646:\n logger.warning(\n \"The qwen1.5 series has been detected, where the length of tokenizer.get_vocab() and the vocab_size in the model config are inconsistent. We have forcefully set it to the latter. https://github.com/QwenLM/Qwen1.5/issues/29\"\n )\n model_vocab_size = 151936\n indices = []\n values = []\n for model_token_id, unified_token_index in mapping.items():\n indices.append([model_token_id, unified_token_index])\n values.append(1.0)\n indices = torch.tensor(\n indices, dtype=torch.long\n ).t()\n values = torch.tensor(values, dtype=torch.float)\n size = torch.Size([model_vocab_size, union_vocab_size])\n mapping_matrix = torch.sparse_coo_tensor(indices, values, size, device=\"cuda\")\n return mapping_matrix\n\ndef check_until(until, cached_batch_output_ids, tokenizers, merged_token_ids):\n if len(cached_batch_output_ids) != len(merged_token_ids[0]):\n raise ValueError(\n f\"len(cached_batch_output_ids):{len(cached_batch_output_ids)} != len(merged_token_ids[0]): {len(merged_token_ids[0])}\"\n )\n for i, _ in enumerate(cached_batch_output_ids):\n cached_batch_output_ids[i] = cached_batch_output_ids[i] + merged_token_ids[0][i]\n tmp_text = tokenizers[0].decode(cached_batch_output_ids[i])\n if until:\n for stop_txt in until:\n if stop_txt in tmp_text:\n for j, tokenizer in enumerate(tokenizers):\n merged_token_ids[j][i] = merged_token_ids[j][i] + [\n tokenizer.eos_token_id\n ]\n break\n return cached_batch_output_ids, merged_token_ids\n\ndef check_threshold_ensemble(tmp_outputs_refs, primary_index, threshold):\n if primary_index == -1:\n tmp = tmp_outputs_refs\n outputs = [t[0] for t in tmp]\n outputs_times = [t[1] for t in tmp]\n need_ensemble = True\n else:\n primary_model_outputs, primary_model_outputs_times = tmp_outputs_refs[primary_index]\n if primary_model_outputs.shape[0] != 1:\n raise ValueError(\"For thresholded ensemble, we only support batch size of 1.\")\n max_probs, _ = torch.max(primary_model_outputs, dim=1)\n if max_probs.item() > threshold:\n for i, ref in enumerate(tmp_outputs_refs):\n if i != primary_index:\n continue\n outputs = [None] * len(tmp_outputs_refs)\n outputs[primary_index] = primary_model_outputs\n outputs_times = [primary_model_outputs_times] * len(tmp_outputs_refs)\n need_ensemble = False\n else:\n tmp = tmp_outputs_refs\n outputs = [t[0] for t in tmp]\n outputs_times = [t[1] for t in tmp]\n need_ensemble = True\n return outputs, outputs_times, need_ensemble\n\ndef merge_and_convert_tokens(\n outputs,\n tokenizers,\n mapping_matrices,\n vocab_union,\n index_to_vocab,\n special_prefix_token,\n byte_mappings_list,\n primary_index,\n threshold,\n need_ensemble,\n tmp_outputs_times,\n):\n eos_token_list = [tokenizer.eos_token for tokenizer in tokenizers]\n eos_token_list.extend([\"<|end_of_text|>\", \"<|endoftext|>\", \"<|im_end|>\", \"<|end|>\"])\n for i, output in enumerate(outputs):\n if need_ensemble:\n if output is None:\n raise ValueError(\n \"We detect a probability vector of None, which need to excute ensemble!\"\n )\n else:\n if output is not None and i != primary_index:\n raise ValueError(\n \"We detect a probability vector from non-primary model, but no ensemble excuted!\"\n )\n if primary_index == -1:\n merged_probs = torch.zeros(\n (outputs[0].size(0), len(vocab_union)), device=\"cuda\"\n )\n else:\n merged_probs = torch.zeros(\n (outputs[primary_index].size(0), len(vocab_union)), device=\"cuda\"\n )\n if need_ensemble:\n for output, mapping_matrix in zip(outputs, mapping_matrices):\n transformed_probs = torch.sparse.mm(output, mapping_matrix)\n merged_probs += transformed_probs\n else:\n transformed_probs = torch.sparse.mm(\n outputs[primary_index], mapping_matrices[primary_index]\n )\n merged_probs += transformed_probs\n logger.info(\"GaC do not ensemble in this step.\")\n max_token_indices = torch.argmax(merged_probs, dim=1)\n max_tokens = [index_to_vocab[index.item()] for index in max_token_indices]\n logger.info(f\"Token chosen by GaC: {str(max_tokens)}\\n\")\n batch_token_ids = [\n [] for _ in range(len(tokenizers))\n ]\n for i, tokenizer in enumerate(tokenizers):\n for token in max_tokens:\n if token in eos_token_list:\n token_id = [tokenizer.eos_token_id]\n else:\n token_id = get_token_ids(\n tokenizer,\n token,\n special_prefix_token[tokenizer],\n byte_mappings_list[i],\n )\n batch_token_ids[i].append(token_id)\n return batch_token_ids\n\ndef get_token_ids(tokenizer, token, special_prefix_token, byte_mapping):\n if token in byte_mapping:\n return [byte_mapping[token]]\n if byte_mapping != 128:\n prefix_tokens = [special_prefix_token, \";\"]\n for prefix_token in prefix_tokens:\n token_id_list1 = tokenizer.encode(prefix_token, add_special_tokens=False)\n token_id_list2 = tokenizer.encode(\n prefix_token + token, add_special_tokens=False\n )\n if token_id_list2[: len(token_id_list1)] == token_id_list1:\n result = token_id_list2[len(token_id_list1) :]\n if result:\n return result\n logger.warning(f\"Warning: Token '{token}' may not be tokenized as expected.\")\n return tokenizer.encode(token, add_special_tokens=False)\n\ndef find_special_underscore_token(tokenizer):\n vocab = tokenizer.get_vocab()\n count_prefix_G = sum(1 for token in vocab if token.startswith(\"\u0120\"))\n count_prefix_underscore = sum(1 for token in vocab if token.startswith(\"\u2581\"))\n if count_prefix_G > count_prefix_underscore:\n return \"\"\n underscore_tokens = [\n token for token in vocab if token.startswith(\"\u2581\") and token != \"\u2581\"\n ]\n special_tokens = []\n for token in tqdm(underscore_tokens, desc=\"Analyzing tokens\"):\n cleaned_token = token[1:]\n if (\n not any(\n token in other_token\n for other_token in underscore_tokens\n if other_token != token\n )\n and token.count(\"\u2581\") == 1\n and cleaned_token.strip() != \"\"\n ):\n special_tokens.append(cleaned_token)\n if not special_tokens:\n raise ValueError(\"No special underscore token found that meets the criteria.\")\n return min(special_tokens, key=lambda x: (len(x), x))\n\ndef get_special_prefix_tokens_for_all(tokenizers):\n special_prefix_tokens = {}\n for tokenizer in tokenizers:\n if tokenizer.vocab_size == 256000:\n logger.info(\"gemma-it detected, use '\u00a2' as special_prefix_token\")\n special_prefix_tokens[tokenizer] = \"\u00a2\"\n continue\n token = find_special_underscore_token(tokenizer)\n special_prefix_tokens[tokenizer] = token\n return special_prefix_tokens\n\ndef greedy_search(\n model,\n input_ids: torch.LongTensor,\n logits_processor: Optional[LogitsProcessorList] = None,\n stopping_criteria: Optional[StoppingCriteriaList] = None,\n max_length: Optional[int] = None,\n pad_token_id: Optional[int] = None,\n eos_token_id: Optional[Union[int, List[int]]] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n output_scores: Optional[bool] = None,\n return_dict_in_generate: Optional[bool] = None,\n synced_gpus: bool = False,\n streamer: Optional[\"BaseStreamer\"] = None,\n **model_kwargs,\n) -> Union[GreedySearchOutput, torch.LongTensor]:\n logits_processor = (\n logits_processor if logits_processor is not None else LogitsProcessorList()\n )\n stopping_criteria = (\n stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()\n )\n if max_length is not None:\n warnings.warn(\n \"`max_length` is deprecated in this function, use\"\n \" `stopping_criteria=StoppingCriteriaList([MaxLengthCriteria(max_length=max_length)])` instead.\",\n UserWarning,\n )\n stopping_criteria = validate_stopping_criteria(stopping_criteria, max_length)\n pad_token_id = (\n pad_token_id\n if pad_token_id is not None\n else model.generation_config.pad_token_id\n )\n eos_token_id = (\n eos_token_id\n if eos_token_id is not None\n else model.generation_config.eos_token_id\n )\n if isinstance(eos_token_id, int):\n eos_token_id = [eos_token_id]\n eos_token_id_tensor = (\n torch.tensor(eos_token_id).to(input_ids.device)\n if eos_token_id is not None\n else None\n )\n output_scores = (\n output_scores\n if output_scores is not None\n else model.generation_config.output_scores\n )\n output_attentions = (\n output_attentions\n if output_attentions is not None\n else model.generation_config.output_attentions\n )\n output_hidden_states = (\n output_hidden_states\n if output_hidden_states is not None\n else model.generation_config.output_hidden_states\n )\n return_dict_in_generate = (\n return_dict_in_generate\n if return_dict_in_generate is not None\n else model.generation_config.return_dict_in_generate\n )\n scores = () if (return_dict_in_generate and output_scores) else None\n model_kwargs = model._get_initial_cache_position(input_ids, model_kwargs)\n if model.config.is_encoder_decoder:\n raise Exception(\"We only support decorder arch!\")\n unfinished_sequences = torch.ones(\n input_ids.shape[0], dtype=torch.long, device=input_ids.device\n )\n this_peer_finished = False\n return {\n \"input_ids\": input_ids,\n \"model_kwargs\": model_kwargs,\n \"output_attentions\": output_attentions,\n \"output_hidden_states\": output_hidden_states,\n \"stopping_criteria\": stopping_criteria,\n \"logits_processor\": logits_processor,\n \"scores\": scores,\n \"pad_token_id\": pad_token_id,\n \"eos_token_id_tensor\": eos_token_id_tensor,\n \"unfinished_sequences\": unfinished_sequences,\n \"this_peer_finished\": this_peer_finished,\n }\n\ndef get_one_token(model, state):\n input_ids = state[\"input_ids\"]\n model_kwargs = state[\"model_kwargs\"]\n output_attentions = state[\"output_attentions\"]\n output_hidden_states = state[\"output_hidden_states\"]\n logits_processor = state[\"logits_processor\"]\n model_inputs = model.prepare_inputs_for_generation(input_ids, **model_kwargs)\n with torch.no_grad():\n outputs = model(\n **model_inputs,\n return_dict=True,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n )\n next_token_logits = outputs.logits[:, -1, :]\n next_tokens_scores = logits_processor(input_ids, next_token_logits)\n next_tokens_scores = F.softmax(next_tokens_scores, dim=-1)\n return next_tokens_scores, outputs\n\ndef generate_prepare(\n model,\n inputs: Optional[torch.Tensor] = None,\n generation_config: Optional[GenerationConfig] = None,\n logits_processor: Optional[LogitsProcessorList] = None,\n stopping_criteria: Optional[StoppingCriteriaList] = None,\n prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,\n synced_gpus: Optional[bool] = None,\n assistant_model: Optional[\"PreTrainedModel\"] = None,\n streamer: Optional[\"BaseStreamer\"] = None,\n negative_prompt_ids: Optional[torch.Tensor] = None,\n negative_prompt_attention_mask: Optional[torch.Tensor] = None,\n **kwargs,\n) -> Union[GenerateOutput, torch.LongTensor]:\n model._validate_model_class()\n tokenizer = kwargs.pop(\n \"tokenizer\", None\n )\n generation_config, model_kwargs = model._prepare_generation_config(\n generation_config, **kwargs\n )\n if 'model_name_list' in model_kwargs:\n del model_kwargs['model_name_list']\n model._validate_model_kwargs(model_kwargs.copy())\n model._validate_assistant(assistant_model)\n if synced_gpus is None:\n if is_deepspeed_zero3_enabled() and dist.get_world_size() > 1:\n synced_gpus = True\n else:\n synced_gpus = False\n logits_processor = (\n logits_processor if logits_processor is not None else LogitsProcessorList()\n )\n stopping_criteria = (\n stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()\n )\n accepts_attention_mask = \"attention_mask\" in set(\n inspect.signature(model.forward).parameters.keys()\n )\n requires_attention_mask = \"encoder_outputs\" not in model_kwargs\n kwargs_has_attention_mask = model_kwargs.get(\"attention_mask\", None) is not None\n inputs_tensor, model_input_name, model_kwargs = model._prepare_model_inputs(\n inputs, generation_config.bos_token_id, model_kwargs\n )\n batch_size = inputs_tensor.shape[0]\n device = inputs_tensor.device\n model._prepare_special_tokens(\n generation_config, kwargs_has_attention_mask, device=device\n )\n if not model.config.is_encoder_decoder and not is_torchdynamo_compiling():\n if (\n generation_config._pad_token_tensor is not None\n and batch_size > 1\n and len(inputs_tensor.shape) == 2\n and torch.sum(inputs_tensor[:, -1] == generation_config._pad_token_tensor)\n > 0\n ):\n logger.warning(\n \"A decoder-only architecture is being used, but right-padding was detected! For correct \"\n \"generation results, please set `padding_side='left'` when initializing the tokenizer.\"\n )\n if not model.config.is_encoder_decoder and model_input_name == \"inputs_embeds\":\n model_kwargs[\"use_cache\"] = True\n else:\n model_kwargs[\"use_cache\"] = generation_config.use_cache\n if (\n not kwargs_has_attention_mask\n and requires_attention_mask\n and accepts_attention_mask\n ):\n model_kwargs[\"attention_mask\"] = model._prepare_attention_mask_for_generation(\n inputs_tensor,\n generation_config._pad_token_tensor,\n generation_config._eos_token_tensor,\n )\n if model.config.is_encoder_decoder and \"encoder_outputs\" not in model_kwargs:\n model_kwargs = model._prepare_encoder_decoder_kwargs_for_generation(\n inputs_tensor, model_kwargs, model_input_name, generation_config\n )\n if model.config.is_encoder_decoder:\n input_ids, model_kwargs = model._prepare_decoder_input_ids_for_generation(\n batch_size=batch_size,\n model_input_name=model_input_name,\n model_kwargs=model_kwargs,\n decoder_start_token_id=generation_config._decoder_start_token_tensor,\n device=inputs_tensor.device,\n )\n else:\n input_ids = (\n inputs_tensor\n if model_input_name == \"input_ids\"\n else model_kwargs.pop(\"input_ids\")\n )\n if generation_config.token_healing:\n input_ids = model.heal_tokens(input_ids, tokenizer)\n if streamer is not None:\n streamer.put(input_ids.cpu())\n input_ids_length = input_ids.shape[-1]\n has_default_max_length = (\n kwargs.get(\"max_length\") is None and generation_config.max_length is not None\n )\n has_default_min_length = (\n kwargs.get(\"min_length\") is None and generation_config.min_length is not None\n )\n generation_config = model._prepare_generated_length(\n generation_config=generation_config,\n has_default_max_length=has_default_max_length,\n has_default_min_length=has_default_min_length,\n model_input_name=model_input_name,\n inputs_tensor=inputs_tensor,\n input_ids_length=input_ids_length,\n )\n use_dynamic_cache_by_default = False\n if \"mamba\" in model.__class__.__name__.lower():\n cache_name = \"cache_params\"\n else:\n cache_name = \"past_key_values\"\n if (\n assistant_model is not None\n and generation_config.cache_implementation is not None\n and model._supports_default_dynamic_cache()\n ):\n logger.warning_once(\n \"An assistant model is provided, using a dynamic cache instead of a cache of type=\"\n f\"'{generation_config.cache_implementation}'.\"\n )\n generation_config.cache_implementation = None\n if (model_kwargs.get(cache_name) is not None) and is_torchdynamo_compiling():\n raise ValueError(\n \"Passing `past_key_values` is not supported when compiling `model.generate` with torch.compile -- you \"\n \"may get incorrect outputs. Please compile `model.forward` only or use the `cache_implementation` \"\n \"input argument.\"\n )\n if generation_config.cache_implementation is not None and (\n model_kwargs.get(cache_name) is not None\n ):\n raise ValueError(\n f\"Passing both `cache_implementation` (used to initialize certain caches) and `{cache_name}` (a \"\n \"Cache object) is unsupported. Please use only one of the two.\"\n )\n elif generation_config.cache_implementation is not None:\n if generation_config.cache_implementation in NEED_SETUP_CACHE_CLASSES_MAPPING:\n if (\n generation_config.cache_implementation == \"static\"\n and not model._supports_static_cache\n ):\n raise ValueError(\n \"This model does not support `cache_implementation='static'`. Please check the following \"\n \"issue: https://github.com/huggingface/transformers/issues/28981\"\n )\n model_kwargs[cache_name] = model._get_cache(\n cache_implementation=generation_config.cache_implementation,\n max_batch_size=generation_config.num_beams\n * generation_config.num_return_sequences\n * batch_size,\n max_cache_len=generation_config.max_length,\n device=device,\n model_kwargs=model_kwargs,\n )\n elif generation_config.cache_implementation == \"quantized\":\n if not model._supports_quantized_cache:\n raise ValueError(\n \"This model does not support the quantized cache. If you want your model to support quantized \"\n \"cache, please open an issue.\"\n )\n cache_config = (\n generation_config.cache_config\n if generation_config.cache_config is not None\n else QuantizedCacheConfig()\n )\n cache_class = QUANT_BACKEND_CLASSES_MAPPING[cache_config.backend]\n if cache_config.backend == \"quanto\" and not is_quanto_available():\n raise ImportError(\n \"You need to install `quanto` in order to use KV cache quantization with quanto backend. \"\n \"Please install it via with `pip install quanto`\"\n )\n elif cache_config.backend == \"HQQ\" and not is_hqq_available():\n raise ImportError(\n \"You need to install `HQQ` in order to use KV cache quantization with HQQ backend. \"\n \"Please install it via with `pip install hqq`\"\n )\n model_kwargs[cache_name] = cache_class(cache_config)\n elif generation_config.cache_implementation == \"offloaded\":\n model_kwargs[cache_name] = OffloadedCache()\n elif (\n generation_config.cache_implementation is None\n and model._supports_default_dynamic_cache()\n ):\n past = model_kwargs.get(cache_name, None)\n requires_cross_attention_cache = (\n model.config.is_encoder_decoder\n or model_kwargs.get(\"encoder_outputs\") is not None\n )\n if past is None:\n model_kwargs[cache_name] = (\n DynamicCache()\n if not requires_cross_attention_cache\n else EncoderDecoderCache(DynamicCache(), DynamicCache())\n )\n use_dynamic_cache_by_default = True\n elif isinstance(past, tuple):\n model_kwargs[cache_name] = (\n DynamicCache.from_legacy_cache(past)\n if not requires_cross_attention_cache\n else EncoderDecoderCache.from_legacy_cache(past)\n )\n use_dynamic_cache_by_default = True\n model._validate_generated_length(\n generation_config, input_ids_length, has_default_max_length\n )\n generation_mode = generation_config.get_generation_mode(assistant_model)\n if streamer is not None and (generation_config.num_beams > 1):\n raise ValueError(\n \"`streamer` cannot be used with beam search (yet!). Make sure that `num_beams` is set to 1.\"\n )\n if not is_torchdynamo_compiling() and model.device.type != input_ids.device.type:\n warnings.warn(\n \"You are calling .generate() with the `input_ids` being on a device type different\"\n f\" than your model's device. `input_ids` is on {input_ids.device.type}, whereas the model\"\n f\" is on {model.device.type}. You may experience unexpected behaviors or slower generation.\"\n \" Please make sure that you have put `input_ids` to the\"\n f\" correct device by calling for example input_ids = input_ids.to('{model.device.type}') before\"\n \" running `.generate()`.\",\n UserWarning,\n )\n prepared_logits_processor = model._get_logits_processor(\n generation_config=generation_config,\n input_ids_seq_length=input_ids_length,\n encoder_input_ids=inputs_tensor,\n prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,\n logits_processor=logits_processor,\n device=inputs_tensor.device,\n model_kwargs=model_kwargs,\n negative_prompt_ids=negative_prompt_ids,\n negative_prompt_attention_mask=negative_prompt_attention_mask,\n )\n prepared_stopping_criteria = model._get_stopping_criteria(\n generation_config=generation_config,\n stopping_criteria=stopping_criteria,\n tokenizer=tokenizer,\n **kwargs,\n )\n return greedy_search(\n model,\n input_ids,\n logits_processor=prepared_logits_processor,\n stopping_criteria=prepared_stopping_criteria,\n pad_token_id=generation_config.pad_token_id,\n eos_token_id=generation_config.eos_token_id,\n output_scores=generation_config.output_scores,\n return_dict_in_generate=generation_config.return_dict_in_generate,\n synced_gpus=synced_gpus,\n streamer=streamer,\n **model_kwargs,\n )" } ] }, { "paper_id": 3, "paper_details": { "title": "Simple but Effective Compound Geometric Operations for Temporal Knowledge Graph Completion", "url": "https://www.arxiv.org/abs/2408.06603" }, "repo_original_url": "https://github.com/nk-ruiying/tcompounde", "project_path": "Benchmark/3-Simple/TCompoundE-main", "enviorment_name": "tcom_env", "file_organization": "\nTCompoundE-main/\n compare.py\n data/\n GDELT/\n ent_id\n probas.pickle\n rel_id\n test.pickle\n to_skip.pickle\n train.pickle\n ts_id\n valid.pickle\n ICEWS05-15/\n ent_id\n probas.pickle\n rel_id\n test.pickle\n to_skip.pickle\n train.pickle\n ts_id\n valid.pickle\n ICEWS14/\n ent_id\n probas.pickle\n rel_id\n test.pickle\n to_skip.pickle\n train.pickle\n ts_id\n valid.pickle\n datasets.py\n learner.py\n models.py\n optimizers.py\n process_gdelt.py\n process_icews.py\n README.md\n regularizers.py\n requirements.txt\n src_data/\n GDELT/\n test\n train\n valid\n ICEWS05-15/\n LICENSE\n test\n train\n valid\n ICEWS14/\n LICENSE\n test\n train\n valid\n", "latex_code_path": "Benchmark/3-Simple/arXiv-2408.06603v1", "task_details": [ { "task_id": 0, "indent": 2, "latex_code": "\n\\subsection{TCompoundE Model}\nIn this section, we present our model, TCompoundE, which employs compound geometric operations on both relations and timestamps. For a quadruple $(s, \\hat{r}, o, \\tau )$ in TKG. We utilize the notations $\\bm{e_s}, \\bm{e_o}$ to represent the embeddings of the head entity $s$ and tail entity $o$. We utilize $\\bm{S_{\\hat{r}}}$ and $\\bm{T_{\\hat{r}}}$ to represent relation-specific scaling, translation operations. Integrate temporal information into relation-specific operations before applying them to entity embeddings. This merging involves time-specific translation $\\bm{T_{\\tau}}$ and scaling $\\bm{S_{\\tau}}$ operations in a relationship-specific process. In our model, we employ translation and scaling operations to represent relation-specific operations and time-specific operations. To facilitate a comprehensive introduction to our model, we categorize it into two distinct sections: \\textbf{Time-Specific Operation} and \\textbf{Relation-Specific Operation}; The initial section elucidates the utilization of time-specific operations in conjunction with relation-specific operations within a quadruple. In the subsequent section, we elaborate on the impact of relation-specific operations on the embedding of the head entity.\n\n\\textbf{Time-Specific Operation}. In our model, we employ time-specific translation $\\bm{T_{\\tau}}$ and scaling $\\bm{S_{\\tau}}$ operations to imbue temporal information into the relation. We exclusively apply these operations to the relation-specific scaling operation $\\bm{S_{\\hat{r}}}$. It is crucial to highlight that we scale the relation-specific operation by first applying translation and then scaling. This sequencing is intentional, as the order of operations can influence the outcome. However, for the relation-specific translation operation, we refrain from integrating time information. This approach aims to capture features of relations that remain constant over time. Subsequently, we obtain relation-specific operations that integrate temporal information. Herein, $\\bm{S_{\\hat{r} \\tau}}$ and $\\bm{T_{\\hat{r} \\tau}}$ denote the relation-specific scaling and translation operations, respectively, after incorporating time information. These operations can be precisely described by the following formula: \n\\begin{align}\\label{forva}\n \\bm{S_{\\hat{r} \\tau}} &= \\bm{S_{\\tau}} \\cdot \\bm{T_{\\tau}} \\cdot \\bm{S_{\\hat{r}}} \\\\ \n \\label{forvaT}\n \\bm{T_{\\hat{r} \\tau}} &= \\bm{T_{\\hat{r}}}\n\\end{align}\n\\textbf{Relation-Specific Operation}. We denote the relation-specific translation and relation-specific scaling operations for the head entity as $\\bm{T_{\\hat{r}}}$ and $\\bm{S_{\\hat{r}}}$ respectively. To capture temporal information within the TKG, we refrain from applying these operations directly to the head entity embeddings. Instead, we execute relation-specific operations subsequent to the time-specific operations. Specifically, we utilize $\\bm{S_{\\hat{r} \\tau}}$ and $\\bm{T_{\\hat{r} \\tau}}$ to conduct relation-specific operations incorporating time information on the head entity embedding. This operation is formally represented as:\n\\begin{equation}\\label{headevo}\n\\bm{e_{s}^{\\hat{r} \\tau}} = \\bm{S_{\\hat{r} \\tau}} \\cdot \\bm{T_{\\hat{r} \\tau}} \\cdot \\bm{e_s}\n\\end{equation}\n\nWe obtain the head entity representation $\\bm{e_{s}^{\\hat{r} \\tau}}$ incorporating fused time and relation information using Formula \\ref{headevo}. Unlike CompoundE \\citep{Ge2022CompoundEKG}, our chosen score function is not a distance metric; instead, it is determined by the semantic similarity between $\\bm{e_{s}^{\\hat{r} \\tau}}$ and the tail entity $\\bm{e_o}$. This decision is grounded in our belief that semantic similarity offers more advantages than distance metrics in the context of TKG \\emph{(proof in Appendix \\ref{apx:difscore})}. The score function for TCompoundE is expressed as:\n\\begin{equation}\\label{fuc:sim}\n\\phi (s,\\hat{r},o, \\tau) = <\\bm{e_{s}^{\\hat{r} \\tau}}, \\bm{e_o}>\n\\end{equation}\n", "completion_path": "./models.py", "namespace": "models.TCompoundE.score", "type": "method", "signature_position": [ 166, 166 ], "body_position": [ 167, 177 ], "script": "\npython learner.py --dataset ICEWS14 --emb_reg 0.01 --time_reg 0.01 --learning_rate 0.01 --rank 6000 --batch_size 4000 --max_epochs 400\n", "ReferenceCode_With_Comments": "\nlhs = self.embeddings[0](x[:, 0]) # Embedding of the subject (head entity).\nrel = self.embeddings[1](x[:, 1]) # Embedding of the relation.\nrhs = self.embeddings[0](x[:, 2]) # Embedding of the object (tail entity).\ntime = self.embeddings[2](x[:, 3]) # Embedding of the time.\n\n# ---------------------------------------------------------------------------\n# Snippet 1: We separate the entity embeddings into scaling and translation components,\n# aligning with the time-specific and relation-specific operations defined in the LaTeX section.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nlhs = lhs[:, :self.rank], lhs[:, self.rank:]\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: The relation embeddings are scaled by pi to integrate temporal information\n# into the relation-specific scaling operation, as described in the Time-Specific Operation section.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nrel = rel[:, :self.rank] / (1 / self.pi), rel[:, self.rank:] / (1 / self.pi)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: The object entity embeddings are also split into scaling and translation components,\n# preparing them for the semantic similarity computation with the transformed head entity.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nrhs = rhs[:, :self.rank], rhs[:, self.rank:]\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Similarly, the time embeddings are divided into scaling and translation components\n# to incorporate temporal information into the relation-specific operations.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\ntime = time[:, :self.rank], time[:, self.rank:]\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: We compute the relation-time scaling and translation operations by combining\n# relation and time-specific embeddings, following the formulation in the LaTeX description.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nrt = (rel[0] + time[0]) * time[1], rel[1]\n# [End Snippet 5]\n\n# ---------------------------------------------------------------------------\n# Snippet 6: The final output score is calculated as the semantic similarity between the\n# transformed head entity and the tail entity, aligning with the score function defined in the LaTeX.\n# Return the output score.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 6]\noutput = torch.sum(((lhs[0] + rt[1]) * rt[0]) * rhs[0], 1, keepdim=True)\nreturn output\n# [End Snippet 6]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - Implementation strategy of concatenating scaling/translation components into single embedding vectors (not described in LaTeX)\n - Practical splitting mechanism for separating these components during computation (implied but not explicitly stated in equations)\n - The code utilizes pi to rescale the relation embeddings.\n \n - Mismatched Details:\n - The LaTeX formally depicts a sequence of multiplications \\(\\bm{S_{\\tau}} \\cdot \\bm{T_{\\tau}} \\cdot \\bm{S_{\\hat{r}}}\\) for \\(\\bm{S_{\\hat{r} \\tau}}\\), whereas the code conveys this by adding and then multiplying embeddings. Despite the slight difference in expression, it functions as an analogous realization of time-specific plus relation-specific transformations.\n", "Missing_details": [ "\n- Implementation strategy of concatenating scaling/translation components into single embedding vectors (not described in LaTeX)\n", "\n- Practical splitting mechanism for separating these components during computation (implied but not explicitly stated in equations)\n" ], "Mismatched_details": [ "\n- The LaTeX formally depicts a sequence of multiplications \\(\\bm{S_{\\tau}} \\cdot \\bm{T_{\\tau}} \\cdot \\bm{S_{\\hat{r}}}\\) for \\(\\bm{S_{\\hat{r} \\tau}}\\), whereas the code conveys this by adding and then multiplying embeddings. Despite the slight difference in expression, it functions as an analogous realization of time-specific plus relation-specific transformations.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - x (torch.Tensor): A tensor representing a batch of quadruples (s, r, o, t) where:\n - Column 0: Indices of the subject entities.\n - Column 1: Indices of the relations.\n - Column 2: Indices of the object entities.\n - Column 3: Indices of the timestamps.\n", "Arguments_list": [ { "name": "x", "string": "\n- x (torch.Tensor): A tensor representing a batch of quadruples (s, r, o, t) where:\n - Column 0: Indices of the subject entities.\n - Column 1: Indices of the relations.\n - Column 2: Indices of the object entities.\n - Column 3: Indices of the timestamps.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-File dependency: \n - TCompoundE.rank\n - TCompoundE.embeddings\n - TCompoundE.pi\n\n - Cross-File dependency: \n - None\n", "intra_file": [ "TCompoundE.rank", "TCompoundE.embeddings", "TCompoundE.pi" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.sum\n", "list": [ "torch.sum" ] }, "Return": { "Return_String": "\nOutput Variables:\n - output (torch.Tensor, shape=[batch_size, 1]): Similarity scores between transformed head entities and tail entities\n", "Return_list": [ { "name": "output", "string": "\n- output (torch.Tensor, shape=[batch_size, 1]): Similarity scores between transformed head entities and tail entities\n", "dependency": null } ] }, "ori_python_file": "from abc import ABC, abstractmethod\nfrom typing import Tuple\n\nimport torch\nfrom torch import nn\nimport numpy as np\nimport os, pickle\n\nclass TKBCModel(nn.Module, ABC):\n @abstractmethod\n def get_rhs(self, chunk_begin: int, chunk_size: int):\n pass\n\n @abstractmethod\n def get_queries(self, queries: torch.Tensor):\n pass\n\n @abstractmethod\n def score(self, x: torch.Tensor):\n pass\n\n def get_ranking(\n self, queries, filters, year2id = {},\n batch_size: int = 1000, chunk_size: int = -1\n ):\n \"\"\"\n Returns filtered ranking for each queries.\n :param queries: a torch.LongTensor of quadruples (lhs, rel, rhs, timestam)\n :param filters: filters[(lhs, rel, ts)] gives the elements to filter from ranking\n :param batch_size: maximum number of queries processed at once\n :param chunk_size: maximum number of candidates processed at once\n :return:\n \"\"\"\n if chunk_size < 0:\n chunk_size = self.sizes[2]\n ranks = torch.ones(len(queries))\n with torch.no_grad():\n c_begin = 0\n while c_begin < self.sizes[2]:\n b_begin = 0\n rhs = self.get_rhs(c_begin, chunk_size) # \u5c06\u8f93\u5165\u8fdb\u6765\u7684\u8bad\u7ec3\u96c6\u5206\u4e3a\u51e0\u4e2abatch\n while b_begin < len(queries):\n if queries.shape[1] > 4: # time intervals exist \u5bf9\u4e94\u5143\u7ec4\u4e2d\u65f6\u95f4\u6233\u7684\u5904\u7406\n these_queries = queries[b_begin:b_begin + batch_size]\n start_queries = []\n end_queries = []\n for triple in these_queries:\n if triple[3].split('-')[0] == '####':\n start_idx = -1\n start = -5000\n elif triple[3][0] == '-':\n start = -int(triple[3].split('-')[1].replace('#', '0'))\n elif triple[3][0] != '-':\n start = int(triple[3].split('-')[0].replace('#','0'))\n if triple[4].split('-')[0] == '####':\n end_idx = -1\n end = 5000\n elif triple[4][0] == '-':\n end =-int(triple[4].split('-')[1].replace('#', '0'))\n elif triple[4][0] != '-':\n end = int(triple[4].split('-')[0].replace('#','0'))\n for key, time_idx in sorted(year2id.items(), key=lambda x:x[1]): # \u65f6\u95f4\u6233\u8f6c\u6362\u6210id\n if start>=key[0] and start<=key[1]:\n start_idx = time_idx\n if end>=key[0] and end<=key[1]:\n end_idx = time_idx\n\n\n if start_idx < 0:\n start_queries.append([int(triple[0]), int(triple[1])+self.sizes[1]//4, int(triple[2]), end_idx])\n else:\n start_queries.append([int(triple[0]), int(triple[1]), int(triple[2]), start_idx])\n if end_idx < 0:\n end_queries.append([int(triple[0]), int(triple[1]), int(triple[2]), start_idx])\n else:\n end_queries.append([int(triple[0]), int(triple[1])+self.sizes[1]//4, int(triple[2]), end_idx])\n\n start_queries = torch.from_numpy(np.array(start_queries).astype('int64')).cuda()\n end_queries = torch.from_numpy(np.array(end_queries).astype('int64')).cuda()\n\n q_s = self.get_queries(start_queries)\n q_e = self.get_queries(end_queries)\n scores = q_s @ rhs + q_e @ rhs\n targets = self.score(start_queries)+self.score(end_queries)\n else:\n these_queries = queries[b_begin:b_begin + batch_size] # 500, 4\n q = self.get_queries(these_queries) # 500, 400\n \"\"\"\n if use_left_queries:\n lhs_queries = torch.ones(these_queries.size()).long().cuda()\n lhs_queries[:,1] = (these_queries[:,1]+self.sizes[1]//2)%self.sizes[1]\n lhs_queries[:,0] = these_queries[:,2]\n lhs_queries[:,2] = these_queries[:,0]\n lhs_queries[:,3] = these_queries[:,3]\n q_lhs = self.get_lhs_queries(lhs_queries)\n\n scores = q @ rhs + q_lhs @ rhs\n targets = self.score(these_queries) + self.score(lhs_queries)\n \"\"\"\n \n scores = q @ rhs \n targets = self.score(these_queries)\n\n assert not torch.any(torch.isinf(scores)), \"inf scores\"\n assert not torch.any(torch.isnan(scores)), \"nan scores\"\n assert not torch.any(torch.isinf(targets)), \"inf targets\"\n assert not torch.any(torch.isnan(targets)), \"nan targets\"\n\n # set filtered and true scores to -1e6 to be ignored\n # take care that scores are chunked\n for i, query in enumerate(these_queries):\n if queries.shape[1]>4:\n filter_out = filters[int(query[0]), int(query[1]), query[3], query[4]]\n filter_out += [int(queries[b_begin + i, 2])] \n else: \n filter_out = filters[(query[0].item(), query[1].item(), query[3].item())]\n filter_out += [queries[b_begin + i, 2].item()]\n if chunk_size < self.sizes[2]:\n filter_in_chunk = [\n int(x - c_begin) for x in filter_out\n if c_begin <= x < c_begin + chunk_size\n ]\n scores[i, torch.LongTensor(filter_in_chunk)] = -1e6\n else:\n scores[i, torch.LongTensor(filter_out)] = -1e6\n ranks[b_begin:b_begin + batch_size] += torch.sum(\n (scores >= targets).float(), dim=1\n ).cpu()\n\n b_begin += batch_size\n\n c_begin += chunk_size\n return ranks\n\n\n\nclass TCompoundE(TKBCModel):\n\n def __init__(self, sizes: Tuple[int, int, int, int], rank: int,no_time_emb=False, init_size: float = 1e-2):\n super().__init__()\n super().__init__()\n self.sizes = sizes\n self.rank = rank\n torch.manual_seed(42) # set CPU seed\n torch.cuda.manual_seed(42) # set CUDA seed\n self.embeddings = nn.ModuleList([\n nn.Embedding(s, 2 * rank) for s in [\n sizes[0], # Entity embeddings\n sizes[1], # Relation embeddings\n sizes[3] # Time embeddings\n ]\n ])\n for emb in self.embeddings:\n nn.init.xavier_uniform_(emb.weight)\n\n self.embeddings[0].weight.data *= init_size\n self.embeddings[1].weight.data *= init_size\n self.embeddings[2].weight.data *= init_size\n self.no_time_emb = no_time_emb\n self.pi = 3.14159265358979323846\n\n @staticmethod\n def has_time():\n return True\n \n def score(self, x):\n lhs = self.embeddings[0](x[:, 0]) \n rel = self.embeddings[1](x[:, 1]) \n rhs = self.embeddings[0](x[:, 2]) \n time = self.embeddings[2](x[:, 3]) \n lhs = lhs[:, :self.rank], lhs[:, self.rank:]\n rel = rel[:, :self.rank] / (1 / self.pi), rel[:, self.rank:] / (1 / self.pi)\n rhs = rhs[:, :self.rank], rhs[:, self.rank:]\n time = time[:, :self.rank], time[:, self.rank:]\n rt = (rel[0] + time[0]) * time[1], rel[1]\n output = torch.sum(((lhs[0] + rt[1]) * rt[0]) * rhs[0], 1, keepdim=True)\n return output\n\n def forward(self, x):\n lhs = self.embeddings[0](x[:, 0])\n rel = self.embeddings[1](x[:, 1]) \n rhs = self.embeddings[0](x[:, 2])\n time = self.embeddings[2](x[:, 3])\n lhs = lhs[:, :self.rank], lhs[:, self.rank:]\n rhs = rhs[:, :self.rank], rhs[:, self.rank:]\n rel = rel[:, :self.rank] / (1 / self.pi), rel[:, self.rank:] / (1 / self.pi)\n time = time[:, :self.rank], time[:, self.rank:]\n right = self.embeddings[0].weight\n right = right[:, :self.rank], right[:, self.rank:]\n rt = ((rel[0] + time[0]) * time[1], rel[1])\n scores = ((lhs[0] + rt[1]) * rt[0]) @ right[0].t()\n regularizer = (\n torch.sqrt(lhs[0] ** 2),\n torch.sqrt(rt[0] ** 2 + rt[1] ** 2),\n torch.sqrt(rhs[0] ** 2)\n )\n time = self.embeddings[2].weight[:-1] if self.no_time_emb else self.embeddings[2].weight\n return scores, regularizer, time\n\n def get_rhs(self, chunk_begin: int, chunk_size: int):\n rhs = self.embeddings[0].weight.data[chunk_begin:chunk_begin + chunk_size][:, :self.rank].transpose(0, 1)\n return rhs\n\n def get_queries(self, queries: torch.Tensor):\n lhs = self.embeddings[0](queries[:, 0]) # Embedding of the subject (head entity).\n rel = self.embeddings[1](queries[:, 1]) # Embedding of the relation.\n time = self.embeddings[2](queries[:, 3]) # Embedding of the time.\n lhs = lhs[:, :self.rank], lhs[:, self.rank:]\n rel = rel[:, :self.rank] / (1 / self.pi), rel[:, self.rank:] / (1 / self.pi)\n time = time[:, :self.rank], time[:, self.rank:]\n rt = (rel[0] + time[0]) * time[1], rel[1]\n output = (lhs[0] + rt[1]) * rt[0]\n\n return output\n" }, { "task_id": 1, "indent": 2, "latex_code": "\n\\subsection{TCompoundE Model}\nIn this section, we present our model, TCompoundE, which employs compound geometric operations on both relations and timestamps. For a quadruple $(s, \\hat{r}, o, \\tau )$ in TKG. We utilize the notations $\\bm{e_s}, \\bm{e_o}$ to represent the embeddings of the head entity $s$ and tail entity $o$. We utilize $\\bm{S_{\\hat{r}}}$ and $\\bm{T_{\\hat{r}}}$ to represent relation-specific scaling, translation operations. Integrate temporal information into relation-specific operations before applying them to entity embeddings. This merging involves time-specific translation $\\bm{T_{\\tau}}$ and scaling $\\bm{S_{\\tau}}$ operations in a relationship-specific process. In our model, we employ translation and scaling operations to represent relation-specific operations and time-specific operations. To facilitate a comprehensive introduction to our model, we categorize it into two distinct sections: \\textbf{Time-Specific Operation} and \\textbf{Relation-Specific Operation}; The initial section elucidates the utilization of time-specific operations in conjunction with relation-specific operations within a quadruple. In the subsequent section, we elaborate on the impact of relation-specific operations on the embedding of the head entity.\n\n\\textbf{Time-Specific Operation}. In our model, we employ time-specific translation $\\bm{T_{\\tau}}$ and scaling $\\bm{S_{\\tau}}$ operations to imbue temporal information into the relation. We exclusively apply these operations to the relation-specific scaling operation $\\bm{S_{\\hat{r}}}$. It is crucial to highlight that we scale the relation-specific operation by first applying translation and then scaling. This sequencing is intentional, as the order of operations can influence the outcome. However, for the relation-specific translation operation, we refrain from integrating time information. This approach aims to capture features of relations that remain constant over time. Subsequently, we obtain relation-specific operations that integrate temporal information. Herein, $\\bm{S_{\\hat{r} \\tau}}$ and $\\bm{T_{\\hat{r} \\tau}}$ denote the relation-specific scaling and translation operations, respectively, after incorporating time information. These operations can be precisely described by the following formula: \n\\begin{align}\\label{forva}\n \\bm{S_{\\hat{r} \\tau}} &= \\bm{S_{\\tau}} \\cdot \\bm{T_{\\tau}} \\cdot \\bm{S_{\\hat{r}}} \\\\ \n \\label{forvaT}\n \\bm{T_{\\hat{r} \\tau}} &= \\bm{T_{\\hat{r}}}\n\\end{align}\n\\textbf{Relation-Specific Operation}. We denote the relation-specific translation and relation-specific scaling operations for the head entity as $\\bm{T_{\\hat{r}}}$ and $\\bm{S_{\\hat{r}}}$ respectively. To capture temporal information within the TKG, we refrain from applying these operations directly to the head entity embeddings. Instead, we execute relation-specific operations subsequent to the time-specific operations. Specifically, we utilize $\\bm{S_{\\hat{r} \\tau}}$ and $\\bm{T_{\\hat{r} \\tau}}$ to conduct relation-specific operations incorporating time information on the head entity embedding. This operation is formally represented as:\n\\begin{equation}\\label{headevo}\n\\bm{e_{s}^{\\hat{r} \\tau}} = \\bm{S_{\\hat{r} \\tau}} \\cdot \\bm{T_{\\hat{r} \\tau}} \\cdot \\bm{e_s}\n\\end{equation}\n\nWe obtain the head entity representation $\\bm{e_{s}^{\\hat{r} \\tau}}$ incorporating fused time and relation information using Formula \\ref{headevo}. Unlike CompoundE \\citep{Ge2022CompoundEKG}, our chosen score function is not a distance metric; instead, it is determined by the semantic similarity between $\\bm{e_{s}^{\\hat{r} \\tau}}$ and the tail entity $\\bm{e_o}$. This decision is grounded in our belief that semantic similarity offers more advantages than distance metrics in the context of TKG \\emph{(proof in Appendix \\ref{apx:difscore})}. The score function for TCompoundE is expressed as:\n\\begin{equation}\\label{fuc:sim}\n\\phi (s,\\hat{r},o, \\tau) = <\\bm{e_{s}^{\\hat{r} \\tau}}, \\bm{e_o}>\n\\end{equation}\n", "completion_path": "./models.py", "namespace": "models.TCompoundE.forward", "type": "method", "signature_position": [ 179, 179 ], "body_position": [ 180, 198 ], "script": "\npython learner.py --dataset ICEWS14 --emb_reg 0.01 --time_reg 0.01 --learning_rate 0.01 --rank 6000 --batch_size 4000 --max_epochs 400\n", "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Retrieve the embeddings for the head entity, relation, tail entity,\n# and timestamp. This implements the notation in the LaTeX for \\(\\bm{e_s}, \\bm{S_{\\hat{r}}},\n# \\bm{T_{\\hat{r}}}, \\bm{T_{\\tau}}, \\bm{S_{\\tau}}\\), forming the basic components\n# needed for time-specific and relation-specific transformations.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nlhs = self.embeddings[0](x[:, 0])\nrel = self.embeddings[1](x[:, 1]) \nrhs = self.embeddings[0](x[:, 2])\ntime = self.embeddings[2](x[:, 3])\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Split each retrieved embedding into two parts (e.g., scaling and\n# translation).The code also applies a transformation by dividing the relation embedding by a factor related to \\(\\pi\\).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nlhs = lhs[:, :self.rank], lhs[:, self.rank:]\nrhs = rhs[:, :self.rank], rhs[:, self.rank:]\nrel = rel[:, :self.rank] / (1 / self.pi), rel[:, self.rank:] / (1 / self.pi)\ntime = time[:, :self.rank], time[:, self.rank:]\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Retrieve the entire embedding matrix for all entities (referred to\n# by 'right'), enabling the model to compare \\(\\bm{e_s^{\\hat{r}\\tau}}\\) with every\n# potential \\(\\bm{e_o}\\) in the dataset, consistent with \\(\\phi(s, \\hat{r}, o, \\tau)\\)\n# defined in Equation \\ref{fuc:sim}.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nright = self.embeddings[0].weight\nright = right[:, :self.rank], right[:, self.rank:]\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Combine the time and relation embeddings to form the composite\n# relation-time operations (\\(\\bm{S_{\\hat{r}\\tau}}, \\bm{T_{\\hat{r}\\tau}}\\)).\n# Although the LaTeX states \\(\\bm{S_{\\hat{r}\\tau}} = \\bm{S_{\\tau}} \\cdot \\bm{T_{\\tau}}\n# \\cdot \\bm{S_{\\hat{r}}}\\) and \\(\\bm{T_{\\hat{r}\\tau}} = \\bm{T_{\\hat{r}}}\\), here\n# it is computed by adding before multiplying, thus achieving an analogous\n# combined effect for time-specific scaling and relation-specific operations.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nrt = ((rel[0] + time[0]) * time[1], rel[1])\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Compute the semantic similarity scores (scores) and form the\n# regularizer tuple. 'scores' corresponds to \\(\\langle \\bm{e_s^{\\hat{r}\\tau}},\n# \\bm{e_o}\\rangle\\) in the LaTeX (Equation \\ref{fuc:sim}), while the regularizer\n# is an auxiliary term for model training. Finally, extract the time embeddings\n# if 'no_time_emb' is specified, otherwise preserve them all.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nscores = ((lhs[0] + rt[1]) * rt[0]) @ right[0].t()\nregularizer = (\n torch.sqrt(lhs[0] ** 2),\n torch.sqrt(rt[0] ** 2 + rt[1] ** 2),\n torch.sqrt(rhs[0] ** 2)\n)\ntime = self.embeddings[2].weight[:-1] if self.no_time_emb else self.embeddings[2].weight\nreturn scores, regularizer, time\n# [End Snippet 5]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - Implementation strategy of concatenating scaling/translation components into single embedding vectors (not described in LaTeX)\n - Practical splitting mechanism for separating these components during computation (implied but not explicitly stated in equations)\n - The code utilizes pi to rescale the relation embeddings.\n \n - Mismatched Details:\n - The LaTeX formally depicts a sequence of multiplications \\(\\bm{S_{\\tau}} \\cdot \\bm{T_{\\tau}} \\cdot \\bm{S_{\\hat{r}}}\\) for \\(\\bm{S_{\\hat{r} \\tau}}\\), whereas the code conveys this by adding and then multiplying embeddings. Despite the slight difference in expression, it functions as an analogous realization of time-specific plus relation-specific transformations.\n - Time operations applied to both relation components despite LaTeX specifying only scaling component\n - Regularization uses L2 norm instead of L3 mentioned in loss function\n", "Missing_details": [ "\n- Implementation strategy of concatenating scaling/translation components into single embedding vectors (not described in LaTeX)\n", "\n- Practical splitting mechanism for separating these components during computation (implied but not explicitly stated in equations)\n", "\n- The code utilizes pi to rescale the relation embeddings.\n" ], "Mismatched_details": [ "\n- The LaTeX formally depicts a sequence of multiplications \\(\\bm{S_{\\tau}} \\cdot \\bm{T_{\\tau}} \\cdot \\bm{S_{\\hat{r}}}\\) for \\(\\bm{S_{\\hat{r} \\tau}}\\), whereas the code conveys this by adding and then multiplying embeddings. Despite the slight difference in expression, it functions as an analogous realization of time-specific plus relation-specific transformations.\n", "\n- Time operations applied to both relation components despite LaTeX specifying only scaling component\n", "\n- Regularization uses L2 norm instead of L3 mentioned in loss function\n" ] }, "Arguments": { "string": "\nInput Variables:\n - x (torch.Tensor, shape=[batch_size, 4]): A tensor representing a batch of quadruples (s, r, o, t) where:\n - Column 0: Indices of the subject entities.\n - Column 1: Indices of the relations.\n - Column 2: Indices of the object entities.\n - Column 3: Indices of the timestamps.\n", "Arguments_list": [ { "name": "x", "string": "\n- x (torch.Tensor, shape=[batch_size, 4]): A tensor representing a batch of quadruples (s, r, o, t) where:\n - Column 0: Indices of the subject entities.\n - Column 1: Indices of the relations.\n - Column 2: Indices of the object entities.\n - Column 3: Indices of the timestamps.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-File dependency: \n - TCompoundE.no_time_emb\n - TCompoundE.rank\n - TCompoundE.embeddings\n - TCompoundE.pi\n\n - Cross-File dependency: \n - None\n", "intra_file": [ "TCompoundE.no_time_emb", "TCompoundE.rank", "TCompoundE.embeddings", "TCompoundE.pi" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.sqrt\n", "list": [ "torch.sqrt" ] }, "Return": { "Return_String": "\nOutput Variables:\n - scores (torch.Tensor, shape=[batch_size, num_entities]): The semantic similarity scores for each quadruple against all possible tail entities, corresponding to \\(\\phi(s,\\hat{r},o,\\tau)\\) in the LaTeX (Formula \\ref{fuc:sim}).\n - regularizer (tuple of torch.Tensor): L2 norms of (head embeddings, combined rt operations, tail embeddings)\n - time (torch.Tensor, shape=[num_timestamps, 2 * rank]): The time embeddings. \n", "Return_list": [ { "name": "scores", "string": "\n- scores (torch.Tensor, shape=[batch_size, num_entities]): The semantic similarity scores for each quadruple against all possible tail entities, corresponding to \\(\\phi(s,\\hat{r},o,\\tau)\\) in the LaTeX (Formula \\ref{fuc:sim}).\n", "dependency": null }, { "name": "regularizer", "string": "\n- regularizer (tuple of torch.Tensor): L2 norms of (head embeddings, combined rt operations, tail embeddings)\n", "dependency": null }, { "name": "time", "string": "\n- time (torch.Tensor, shape=[num_timestamps, 2 * rank]): The time embeddings.\n", "dependency": null } ] }, "ori_python_file": "from abc import ABC, abstractmethod\nfrom typing import Tuple\n\nimport torch\nfrom torch import nn\nimport numpy as np\nimport os, pickle\n\nclass TKBCModel(nn.Module, ABC):\n @abstractmethod\n def get_rhs(self, chunk_begin: int, chunk_size: int):\n pass\n\n @abstractmethod\n def get_queries(self, queries: torch.Tensor):\n pass\n\n @abstractmethod\n def score(self, x: torch.Tensor):\n pass\n\n def get_ranking(\n self, queries, filters, year2id = {},\n batch_size: int = 1000, chunk_size: int = -1\n ):\n \"\"\"\n Returns filtered ranking for each queries.\n :param queries: a torch.LongTensor of quadruples (lhs, rel, rhs, timestam)\n :param filters: filters[(lhs, rel, ts)] gives the elements to filter from ranking\n :param batch_size: maximum number of queries processed at once\n :param chunk_size: maximum number of candidates processed at once\n :return:\n \"\"\"\n if chunk_size < 0:\n chunk_size = self.sizes[2]\n ranks = torch.ones(len(queries))\n with torch.no_grad():\n c_begin = 0\n while c_begin < self.sizes[2]:\n b_begin = 0\n rhs = self.get_rhs(c_begin, chunk_size) # \u5c06\u8f93\u5165\u8fdb\u6765\u7684\u8bad\u7ec3\u96c6\u5206\u4e3a\u51e0\u4e2abatch\n while b_begin < len(queries):\n if queries.shape[1] > 4: # time intervals exist \u5bf9\u4e94\u5143\u7ec4\u4e2d\u65f6\u95f4\u6233\u7684\u5904\u7406\n these_queries = queries[b_begin:b_begin + batch_size]\n start_queries = []\n end_queries = []\n for triple in these_queries:\n if triple[3].split('-')[0] == '####':\n start_idx = -1\n start = -5000\n elif triple[3][0] == '-':\n start = -int(triple[3].split('-')[1].replace('#', '0'))\n elif triple[3][0] != '-':\n start = int(triple[3].split('-')[0].replace('#','0'))\n if triple[4].split('-')[0] == '####':\n end_idx = -1\n end = 5000\n elif triple[4][0] == '-':\n end =-int(triple[4].split('-')[1].replace('#', '0'))\n elif triple[4][0] != '-':\n end = int(triple[4].split('-')[0].replace('#','0'))\n for key, time_idx in sorted(year2id.items(), key=lambda x:x[1]): # \u65f6\u95f4\u6233\u8f6c\u6362\u6210id\n if start>=key[0] and start<=key[1]:\n start_idx = time_idx\n if end>=key[0] and end<=key[1]:\n end_idx = time_idx\n\n\n if start_idx < 0:\n start_queries.append([int(triple[0]), int(triple[1])+self.sizes[1]//4, int(triple[2]), end_idx])\n else:\n start_queries.append([int(triple[0]), int(triple[1]), int(triple[2]), start_idx])\n if end_idx < 0:\n end_queries.append([int(triple[0]), int(triple[1]), int(triple[2]), start_idx])\n else:\n end_queries.append([int(triple[0]), int(triple[1])+self.sizes[1]//4, int(triple[2]), end_idx])\n\n start_queries = torch.from_numpy(np.array(start_queries).astype('int64')).cuda()\n end_queries = torch.from_numpy(np.array(end_queries).astype('int64')).cuda()\n\n q_s = self.get_queries(start_queries)\n q_e = self.get_queries(end_queries)\n scores = q_s @ rhs + q_e @ rhs\n targets = self.score(start_queries)+self.score(end_queries)\n else:\n these_queries = queries[b_begin:b_begin + batch_size] # 500, 4\n q = self.get_queries(these_queries) # 500, 400\n \"\"\"\n if use_left_queries:\n lhs_queries = torch.ones(these_queries.size()).long().cuda()\n lhs_queries[:,1] = (these_queries[:,1]+self.sizes[1]//2)%self.sizes[1]\n lhs_queries[:,0] = these_queries[:,2]\n lhs_queries[:,2] = these_queries[:,0]\n lhs_queries[:,3] = these_queries[:,3]\n q_lhs = self.get_lhs_queries(lhs_queries)\n\n scores = q @ rhs + q_lhs @ rhs\n targets = self.score(these_queries) + self.score(lhs_queries)\n \"\"\"\n \n scores = q @ rhs \n targets = self.score(these_queries)\n\n assert not torch.any(torch.isinf(scores)), \"inf scores\"\n assert not torch.any(torch.isnan(scores)), \"nan scores\"\n assert not torch.any(torch.isinf(targets)), \"inf targets\"\n assert not torch.any(torch.isnan(targets)), \"nan targets\"\n\n # set filtered and true scores to -1e6 to be ignored\n # take care that scores are chunked\n for i, query in enumerate(these_queries):\n if queries.shape[1]>4:\n filter_out = filters[int(query[0]), int(query[1]), query[3], query[4]]\n filter_out += [int(queries[b_begin + i, 2])] \n else: \n filter_out = filters[(query[0].item(), query[1].item(), query[3].item())]\n filter_out += [queries[b_begin + i, 2].item()]\n if chunk_size < self.sizes[2]:\n filter_in_chunk = [\n int(x - c_begin) for x in filter_out\n if c_begin <= x < c_begin + chunk_size\n ]\n scores[i, torch.LongTensor(filter_in_chunk)] = -1e6\n else:\n scores[i, torch.LongTensor(filter_out)] = -1e6\n ranks[b_begin:b_begin + batch_size] += torch.sum(\n (scores >= targets).float(), dim=1\n ).cpu()\n\n b_begin += batch_size\n\n c_begin += chunk_size\n return ranks\n\n\n\nclass TCompoundE(TKBCModel):\n\n def __init__(self, sizes: Tuple[int, int, int, int], rank: int,no_time_emb=False, init_size: float = 1e-2):\n super().__init__()\n super().__init__()\n self.sizes = sizes\n self.rank = rank\n torch.manual_seed(42) # set CPU seed\n torch.cuda.manual_seed(42) # set CUDA seed\n self.embeddings = nn.ModuleList([\n nn.Embedding(s, 2 * rank) for s in [\n sizes[0], # Entity embeddings\n sizes[1], # Relation embeddings\n sizes[3] # Time embeddings\n ]\n ])\n for emb in self.embeddings:\n nn.init.xavier_uniform_(emb.weight)\n\n self.embeddings[0].weight.data *= init_size\n self.embeddings[1].weight.data *= init_size\n self.embeddings[2].weight.data *= init_size\n self.no_time_emb = no_time_emb\n self.pi = 3.14159265358979323846\n\n @staticmethod\n def has_time():\n return True\n \n def score(self, x):\n lhs = self.embeddings[0](x[:, 0]) \n rel = self.embeddings[1](x[:, 1]) \n rhs = self.embeddings[0](x[:, 2]) \n time = self.embeddings[2](x[:, 3]) \n lhs = lhs[:, :self.rank], lhs[:, self.rank:]\n rel = rel[:, :self.rank] / (1 / self.pi), rel[:, self.rank:] / (1 / self.pi)\n rhs = rhs[:, :self.rank], rhs[:, self.rank:]\n time = time[:, :self.rank], time[:, self.rank:]\n rt = (rel[0] + time[0]) * time[1], rel[1]\n output = torch.sum(((lhs[0] + rt[1]) * rt[0]) * rhs[0], 1, keepdim=True)\n return output\n\n def forward(self, x):\n lhs = self.embeddings[0](x[:, 0])\n rel = self.embeddings[1](x[:, 1]) \n rhs = self.embeddings[0](x[:, 2])\n time = self.embeddings[2](x[:, 3])\n lhs = lhs[:, :self.rank], lhs[:, self.rank:]\n rhs = rhs[:, :self.rank], rhs[:, self.rank:]\n rel = rel[:, :self.rank] / (1 / self.pi), rel[:, self.rank:] / (1 / self.pi)\n time = time[:, :self.rank], time[:, self.rank:]\n right = self.embeddings[0].weight\n right = right[:, :self.rank], right[:, self.rank:]\n rt = ((rel[0] + time[0]) * time[1], rel[1])\n scores = ((lhs[0] + rt[1]) * rt[0]) @ right[0].t()\n regularizer = (\n torch.sqrt(lhs[0] ** 2),\n torch.sqrt(rt[0] ** 2 + rt[1] ** 2),\n torch.sqrt(rhs[0] ** 2)\n )\n time = self.embeddings[2].weight[:-1] if self.no_time_emb else self.embeddings[2].weight\n return scores, regularizer, time\n\n def get_rhs(self, chunk_begin: int, chunk_size: int):\n rhs = self.embeddings[0].weight.data[chunk_begin:chunk_begin + chunk_size][:, :self.rank].transpose(0, 1)\n return rhs\n\n def get_queries(self, queries: torch.Tensor):\n lhs = self.embeddings[0](queries[:, 0]) # Embedding of the subject (head entity).\n rel = self.embeddings[1](queries[:, 1]) # Embedding of the relation.\n time = self.embeddings[2](queries[:, 3]) # Embedding of the time.\n lhs = lhs[:, :self.rank], lhs[:, self.rank:]\n rel = rel[:, :self.rank] / (1 / self.pi), rel[:, self.rank:] / (1 / self.pi)\n time = time[:, :self.rank], time[:, self.rank:]\n rt = (rel[0] + time[0]) * time[1], rel[1]\n output = (lhs[0] + rt[1]) * rt[0]\n\n return output\n" }, { "task_id": 2, "indent": 2, "script": "\npython learner.py --dataset ICEWS14 --emb_reg 0.01 --time_reg 0.01 --learning_rate 0.01 --rank 6000 --batch_size 4000 --max_epochs 400\n", "latex_code": "\n\\subsection{Loss Function}\nBuilding upon TNTComplEx \\citep{Lacroix2020TensorDF} and TeAST \\citep{Li2023TeASTTK}, we adopt reciprocal learning for training our model, with the loss function defined as follows:\n\\begin{large}\n\\begin{equation}\\label{...}\n\\begin{split}\n\\mathcal{L}_u = - \\log( \\frac{\\exp (\\phi (s,\\hat{r},o, \\tau))}{\\sum_{o' \\in \\varepsilon } \\exp (\\phi (s,\\hat{r},o', \\tau))} ) \\\\\n - \\log( \\frac{\\exp (\\phi (o,\\hat{r}^{-1},s, \\tau))}{\\sum_{s' \\in \\varepsilon } \\exp (\\phi (o,\\hat{r}^{-1},s', \\tau))} )\\\\\n + \\lambda_u\\sum\\limits_{i=1}^{k} (\\| \\bm{e_s} \\|_3^3 + \\| \\bm{T_{\\hat{r} \\tau}} + \\bm{S_{\\hat{r} \\tau}} \\|_3^3 + \\| \\bm{e_o} \\|_3^3 )\n\\end{split}\n\\end{equation}\n\\end{large}\n\\noindent\nwhere $\\lambda_u$ is the weight of the N3 regularization, and $r^{-1}$ denotes the inverse relation. We use the smoothing temporal regularizer in TNTComplEx \\citep{Lacroix2020TensorDF} to make neighboring timestamps having close representations. It is defined as:\n\\begin{equation}\\label{...}\n\\mathcal{L}_{\\tau} = \\frac{1}{N_{\\tau - 1}} \\sum\\limits_{i=1}^{N_{\\tau}-1} \\| \\bm{e_{\\tau(i+1)} - e_{\\tau(i)}} \\|_3^3\n\\end{equation}\n\nThe total loss function of TCompoundE is defined as:\n\\begin{equation}\\label{...}\n\\mathcal{L} = \\mathcal{L}_u + \\lambda_{\\tau} \\mathcal{L}_{\\tau}\n\\end{equation}\nwhere $\\lambda_{\\tau}$ represents temporal regularization.\n", "completion_path": "./optimizers.py", "namespace": "optimizers.TKBCOptimizer.epoch", "type": "method", "signature_position": [ 39, 39 ], "body_position": [ 40, 64 ], "ReferenceCode_With_Comments": "\nloss_all = 0\nloss = nn.CrossEntropyLoss(reduction='mean')\n\nb_begin = 0\nwhile b_begin < examples.shape[0]:\n input_batch = examples[\n b_begin:b_begin + self.batch_size\n ].cuda()\n\n # -----------------------------------------------------------------------\n # Snippet 1: Performs a forward pass through the model to obtain predictions,\n # embedding factors, and temporal information for the current batch.\n # This step is essential for computing the loss components based on the model's output.\n # -----------------------------------------------------------------------\n # [Begin Snippet 1]\n predictions, factors, time = self.model.forward(input_batch)\n # [End Snippet 1]\n\n # -----------------------------------------------------------------------\n # Snippet 2: Extracts the true object entities from the input batch to serve as targets\n # for the cross-entropy loss computation, aligning with the reciprocal learning loss.\n # -----------------------------------------------------------------------\n # [Begin Snippet 2]\n truth = input_batch[:, 2]\n # [End Snippet 2]\n\n # -----------------------------------------------------------------------\n # Snippet 3: Calculates the fitting loss (\\mathcal{L}_u) by comparing the model's\n # predictions with the true objects using the cross-entropy loss.\n # -----------------------------------------------------------------------\n # [Begin Snippet 3]\n l_fit = loss(predictions, truth)\n # [End Snippet 3]\n\n # -----------------------------------------------------------------------\n # Snippet 4: Computes the regularization loss (\\mathcal{L}_u) using the embedding\n # regularizer on the model's factors to prevent overfitting and ensure smoothness.\n # -----------------------------------------------------------------------\n # [Begin Snippet 4]\n l_reg = self.emb_regularizer.forward(factors)\n # [End Snippet 4]\n\n # -----------------------------------------------------------------------\n # Snippet 5: Initializes the temporal regularization loss. If temporal data is present,\n # it computes the temporal regularizer (\\mathcal{L}_{\\tau}) to enforce temporal consistency.\n # -----------------------------------------------------------------------\n # [Begin Snippet 5]\n l_time = torch.zeros_like(l_reg)\n if time is not None:\n l_time = self.temporal_regularizer.forward(time)\n # [End Snippet 5]\n\n # -----------------------------------------------------------------------\n # Snippet 6: Aggregates the total loss by summing the fitting loss, embedding regularization,\n # and temporal regularization, corresponding to the total loss function (\\mathcal{L}).\n # -----------------------------------------------------------------------\n # [Begin Snippet 6]\n l = l_fit + l_reg + l_time\n loss_all += l \n # [End Snippet 6]\n\n # -----------------------------------------------------------------------\n # Snippet 7: Performs backpropagation by zeroing gradients, computing gradients through\n # backward pass, handling any NaN values in gradients, and updating model parameters.\n # This step optimizes the total loss defined earlier.\n # -----------------------------------------------------------------------\n # [Begin Snippet 7]\n self.optimizer.zero_grad() \n l.backward() \n for param in self.model.parameters():\n if param.grad is not None:\n if torch.isnan(param.grad).any():\n param.grad = torch.nan_to_num(param.grad)\n self.optimizer.step()\n # [End Snippet 7]\n\n b_begin += self.batch_size\n # -----------------------------------------------------------------------\n # Snippet 8: Return the total loss computed over all batches in the epoch.\n # -----------------------------------------------------------------------\n # [Begin Snippet 8]\n return loss_all\n # [End Snippet 8]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - Temporal regularization scope: the code should only computes L_\u03c4 (temporal smoothing regularization) for timestamps present in the current batch.\n \n - Mismatched Details:\n - None\n \n", "Missing_details": [], "Mismatched_details": [ "\n- Temporal regularization scope: The LaTeX equation for L_\u03c4 suggests computing over all timestamps, but the code should only computes it for timestamps present in the current batch.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - examples (torch.LongTensor, shape=[num_examples, 4]): A tensor representing the training examples. Each row contains (subject, relation, object, timestamp).\n", "Arguments_list": [ { "name": "examples", "string": "\n- examples (torch.LongTensor, shape=[num_examples, 4]): A tensor representing the training examples. Each row contains (subject, relation, object, timestamp).\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-File dependency: \n - TKBCOptimizer.model\n - TKBCOptimizer.emb_regularizer\n - TKBCOptimizer.temporal_regularizer\n - TKBCOptimizer.optimizer\n - TKBCOptimizer.batch_size\n\n - Cross-File dependency:\n - None\n", "intra_file": [ "TKBCOptimizer.model", "TKBCOptimizer.emb_regularizer", "TKBCOptimizer.temporal_regularizer", "TKBCOptimizer.optimizer", "TKBCOptimizer.batch_size" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.nn.CrossEntropyLoss\n - torch.zeros_like\n - torch.nan_to_num\n - torch.isnan\n", "list": [ "torch.nn.CrossEntropyLoss", "torch.zeros_like", "torch.nan_to_num", "torch.isnan" ] }, "Return": { "Return_String": "\nOutput Variables:\n - loss_all (torch.Tensor): The total loss computed over all batches in the epoch.\n", "Return_list": [ { "name": "loss_all", "string": "\n- loss_all (torch.Tensor): The total loss computed over all batches in the epoch.\n", "dependency": null } ] }, "ori_python_file": "import tqdm\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport os, pickle\nfrom models import TCompoundE\nfrom regularizers import Lambda3\nfrom regularizers import N3\nfrom datasets import TemporalDataset\nimport os\nimport numpy as np\nimport torch\nimport random\nos.environ['PYTHONHASHSEED'] = str(42)\nos.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\nnp.random.seed(42)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\ntorch.use_deterministic_algorithms(True)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nrandom.seed(42)\n\nclass TKBCOptimizer(object):\n def __init__(\n self, model: TCompoundE,\n emb_regularizer: N3, temporal_regularizer: Lambda3,\n optimizer: optim.Optimizer, batch_size: int = 256,\n verbose: bool = True\n ):\n self.model = model\n self.emb_regularizer = emb_regularizer\n self.temporal_regularizer = temporal_regularizer\n self.optimizer = optimizer\n self.batch_size = batch_size\n self.verbose = verbose\n\n def epoch(self, examples: torch.LongTensor):\n loss_all = 0\n loss = nn.CrossEntropyLoss(reduction='mean')\n b_begin = 0\n while b_begin < examples.shape[0]:\n input_batch = examples[\n b_begin:b_begin + self.batch_size\n ].cuda()\n predictions, factors, time = self.model.forward(input_batch)\n truth = input_batch[:, 2]\n l_fit = loss(predictions, truth)\n l_reg = self.emb_regularizer.forward(factors)\n l_time = torch.zeros_like(l_reg)\n if time is not None:\n l_time = self.temporal_regularizer.forward(time)\n l = l_fit + l_reg + l_time\n loss_all += l\n self.optimizer.zero_grad()\n l.backward()\n for param in self.model.parameters():\n if param.grad is not None:\n if torch.isnan(param.grad).any():\n param.grad = torch.nan_to_num(param.grad)\n self.optimizer.step()\n b_begin += self.batch_size\n return loss_all" } ] }, { "paper_id": 4, "paper_details": { "title": "When is Tree Search Useful for LLM Planning? It Depends on the Discriminator", "url": "https://arxiv.org/pdf/2402.10890#page=2.70" }, "repo_original_url": "https://github.com/OSU-NLP-Group/llm-planning-eval", "project_path": "Benchmark/4-llm-planning-eval/llm-planning-eval-main/llm-planning-eval", "enviorment_name": "llm-planning", "file_organization": "\nllm-planning-eval/\n data/\n bird_dev_300_gold.sql\n bird_dev_300.json\n bird_dev.json\n bird_evaluator_train_cls_exec.json\n bird_evaluator_train_cls.json\n bird_evaluator_train.json\n bird_evaluator_train_prompt.json\n bird_intrin_eval.json\n bird_train.json\n gsm8k_dev_100.json\n gsm8k_dev_500.json\n gsm8k_intrin_eval.json\n spider_dev_400_gold.sql\n spider_dev_400.json\n spider_dev.json\n spider_evaluator_train_cls_exec.json\n spider_evaluator_train_cls.json\n spider_evaluator_train.json\n spider_evaluator_train_prompt.json\n spider_intrin_eval.json\n spider_train.json\n environment.yml\n evaluation_configs/\n base.json\n check.json\n exec.json\n pro.json\n evaluators/\n codellama_evaluator.py\n codellama_evaluator_py.py\n __init__.py\n openai_evaluator.py\n openai_evaluator_py.py\n oracle_evaluator.py\n oracle_evaluator_py.py\n generation_configs/\n greedy.json\n temp_sampling.json\n generators/\n hf_generator.py\n __init__.py\n inference.py\n inference_py.py\n intrin_eval.py\n intrin_eval_py.py\n log/\n spider_dev_oracle_rerank_10.json\n overview.png\n planning_methods/\n greedy.py\n greedy_py.py\n __init__.py\n iter_correction.py\n iter_correction_py.py\n mc_tot.py\n mc_tot_py.py\n rerank.py\n rerank_py.py\n preprocess_evaluator_cls.py\n preprocess_evaluator_prompt.py\n preprocess_evaluator.py\n preprocess.py\n README.md\n results/\n spider_dev_oracle_rerank_10.sql\n retrievers/\n bm25.py\n scripts/\n e2e_eval/\n e2e_eval_gsm8k_ic.sh\n e2e_eval_gsm8k_oracle.sh\n e2e_eval_gsm8k_rr.sh\n e2e_eval_gsm8k_ts.sh\n e2e_eval_text2sql_ic.sh\n e2e_eval_text2sql_oracle.sh\n e2e_eval_text2sql_rr.sh\n e2e_eval_text2sql_ts.sh\n intrin_eval/\n intrin_eval_gsm8k.sh\n intrin_eval_text2sql_ft.sh\n intrin_eval_text2sql.sh\n preproc/\n preproc_evaluator_cls.sh\n preproc_evaluator_prompt.sh\n preproc_evaluator.sh\n preproc_raw.sh\n train_evaluator.sh\n spider-evaluator-cls-42/\n adapter_config.json\n adapter_model.bin\n README.md\n trainer_state.json\n spider-evaluator-cls-exec-42/\n adapter_config.json\n adapter_model.bin\n README.md\n trainer_state.json\n train_evaluator.py\n utils/\n constants.py\n exec_eval.py\n exec_py.py\n inference_utils.py\n __init__.py\n normalize_sql.py\n parse.py\n train_utils.py\nspider/\n database/\n academic/\n academic.sqlite\n schema.sql\n activity_1/\n activity_1.sqlite\n schema.sql\n aircraft/\n aircraft.sqlite\n schema.sql\n allergy_1/\n allergy_1.sqlite\n schema.sql\n apartment_rentals/\n apartment_rentals.sqlite\n schema.sql\n architecture/\n architecture.sqlite\n schema.sql\n assets_maintenance/\n assets_maintenance.sqlite\n schema.sql\n baseball_1/\n baseball_1.sqlite\n schema.sql\n battle_death/\n battle_death.sqlite\n schema.sql\n behavior_monitoring/\n behavior_monitoring.sqlite\n schema.sql\n bike_1/\n bike_1.sqlite\n schema.sql\n body_builder/\n body_builder.sqlite\n schema.sql\n book_2/\n book_2.sqlite\n schema.sql\n browser_web/\n browser_web.sqlite\n schema.sql\n candidate_poll/\n candidate_poll.sqlite\n schema.sql\n car_1/\n annotation.json\n car_1.json\n car_1.sql\n car_1.sqlite\n data_csv/\n car-makers.csv\n car-names.csv\n cars-data.csv\n cars.desc\n continents.csv\n countries.csv\n model-list.csv\n README.CARS.TXT\n \u2026 *(other database directories and files)*\n dev_gold.sql\n dev.json\n README.txt\n tables.json\n train_gold.sql\n train_others.json\n train_spider.json\ntest-suite-sql-eval/\n classical_provenance.ipynb\n classical_test.pkl\n database/\n readme.txt\n evaluate_classical.py\n evaluation_examples/\n academic_gold.txt\n classical_test_gold.txt\n gold.txt\n predict.txt\n evaluation.py\n exec_eval.py\n exec_subprocess.py\n LICENSE\n parse.py\n process_sql.py\n README.md\n tables.json\n tmp/\n readme.txt\n", "latex_code_path": "Benchmark/4-llm-planning-eval/arXiv-2402.10890v2", "task_details": [ { "task_id": 0, "indent": 2, "latex_code": "\n\\subsection{Generator}\n\\label{generator}\n\nFor each planning step, we prompt the generator to sample action sequences (SQL queries or Python programs for math reasoning).\nFor text-to-SQL parsing, we use 1-shot prompting, where the example is retrieved from the training sets using BM25 \\citep{bm25}.\nFor math reasoning, we use a fixed 2-shot prompt adapted from \\citet{ni2023l2ceval}. \nSee prompts in Appendix \\ref{app:prompts}.\n", "completion_path": "./retrievers/bm25.py", "namespace": "retrievers.bm25.BM25Retriever.retrieve", "type": "method", "script": "\npython -u inference.py \\\n --test_fname data/spider_dev_400.json \\\n --result_fname results/spider_dev_oracle_rerank_10.sql \\\n --log_fname spider_dev_oracle_rerank_10.json \\\n --dataset_name spider \\\n --db_path ../spider/database \\\n --method_name iter_corr \\\n --generator_name codellama/CodeLlama-13b-Instruct-hf \\\n --retriever_name bm25 \\\n --retriever_corpus_gen data/spider_train.json \\\n --evaluator_name oracle \\\n --oracle_prob 1.0 \\\n --retrieve_k 1 \\\n --seed 42 \\\n --generation_config generation_configs/temp_sampling.json \\\n --evaluation_config evaluation_configs/pro.json\n", "signature_position": [ 14, 14 ], "body_position": [ 15, 17 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: This line corresponds to using BM25 to retrieve the top-k questions\n# from the corpus based on tokenized input. In the LaTeX snippet, this\n# matches the mention of retrieving examples from the training set using BM25.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\ntop_questions = self.model.get_top_n(word_tokenize(query), self.corpus_questions, n=retrieve_k)\noutput = [self.corpus[self.corpus_index[q]] for q in top_questions]\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: return the retrieved corpus entries.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nreturn output\n# [End Snippet 2]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - None\n\n Mismatched Details:\n - None\n", "Missing_details": [], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - query (str): The query for which relevant examples are retrieved.\n - self.corpus (dict):\n - 'db_id' (str): The database identifier.\n - 'schema' (str): The schema of the database.\n - 'question' (str): The user question.\n - 'sql' (str): The ground truth SQL (used for oracle evaluation).\n - \"difficulty\" (str): The difficulty level of the question.\n - self.corpus_questions (list): A list of all questions in the corpus.\n - self.corpus_index (dict): A mapping from each question to its index in the corpus.\n - retrieve_k (int): The number of examples to retrieve.\n", "Arguments_list": [ { "name": "query", "string": "\n- query (str): The query for which relevant examples are retrieved.\n", "dependency": null }, { "name": "self.corpus", "string": "\n- self.corpus (dict):\n - 'db_id' (str): The database identifier.\n - 'schema' (str): The schema of the database.\n - 'question' (str): The user question.\n - 'sql' (str): The ground truth SQL (used for oracle evaluation).\n - \"difficulty\" (str): The difficulty level of the question.\n", "dependency": null }, { "name": "self.corpus_questions", "string": "\n- self.corpus_questions (list): A list of all questions in the corpus.\n", "dependency": null }, { "name": "self.corpus_index", "string": "\n- self.corpus_index (dict): A mapping from each question to its index in the corpus.\n", "dependency": null }, { "name": "retrieve_k", "string": "\n- retrieve_k (int): The number of examples to retrieve.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n Intra File Dependencies: \n - BM25Retriever.model\n \n Cross File Dependencies: \n - None\n", "intra_file": [ "BM25Retriever.model" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - nltk.word_tokenize\n", "list": [ "nltk.word_tokenize" ] }, "Return": { "Return_String": "\nOutput Variables:\n - output (list): A list of dictionaries representing the top-k relevant examples from the corpus.\n" }, "ori_python_file": "from nltk import word_tokenize\nfrom rank_bm25 import BM25Okapi\nimport os, pickle\nimport json\n\nclass BM25Retriever():\n def __init__(self, corpus_fname, retrieve_k):\n self.corpus = json.load(open(corpus_fname))\n self.corpus_questions = [ex[\"question\"] for ex in self.corpus]\n self.corpus_index = dict([(ex[\"question\"], i) for i, ex in enumerate(self.corpus)])\n self.model = BM25Okapi(self.corpus_questions, tokenizer=word_tokenize)\n self.retrieve_k = retrieve_k\n\n def retrieve(self, query, retrieve_k=1):\n top_questions = self.model.get_top_n(word_tokenize(query), self.corpus_questions, n=retrieve_k)\n output = [self.corpus[self.corpus_index[q]] for q in top_questions]\n return output" }, { "task_id": 1, "indent": 1, "latex_code": "\n\\noindent \\textbf{Iterative correction.} \nLike re-ranking, iterative correction starts with the generator proposing a complete action sequence.\nThen it leverages multiple rounds of revision to improve the initial plan based on the discriminator's feedback (Figure \\ref{fig:ic}).\nWhen the generator and the discriminator are the same LLM, it becomes a prevalent planning method, self-correction \\citep{madaan2023selfrefine, shinn2023reflexion, yao2023react, chen2024selfdebug}. \n\nWhile some work uses greedy generation, our implementation samples the same number of action sequences as other planning methods for fair comparison. \nThen, it uses the discriminator to select the best-scoring one for the next round's revision.\nWe allow up to 10 rounds of corrections, with early exiting when the best plan meets a threshold of discrimination score ($> 0.99$), or the score is not improved for 3 consecutive iterations.\nFor fair comparison, we prompt the generator to revise plans with 0-shot instruction following (Appendix \\ref{app:prompts}) instead of few-shot, since in-context examples may introduce additional information.\n", "script": "\npython -u inference.py \\\n --test_fname data/spider_dev_400.json \\\n --result_fname results/spider_dev_oracle_rerank_10.sql \\\n --log_fname spider_dev_oracle_rerank_10.json \\\n --dataset_name spider \\\n --db_path ../spider/database \\\n --method_name iter_corr \\\n --generator_name codellama/CodeLlama-13b-Instruct-hf \\\n --retriever_name bm25 \\\n --retriever_corpus_gen data/spider_train.json \\\n --evaluator_name oracle \\\n --oracle_prob 1.0 \\\n --retrieve_k 1 \\\n --seed 42 \\\n --generation_config generation_configs/temp_sampling.json \\\n --evaluation_config evaluation_configs/pro.json\n", "completion_path": "./planning_methods/iter_correction.py", "namespace": "planning_methods.iter_correction.iter_correction", "type": "function", "signature_position": [ 9, 9 ], "body_position": [ 10, 77 ], "ReferenceCode_With_Comments": "\nconfig = json.load(open(args.generation_config)) \nevaluation_config = json.load(open(args.evaluation_config)) \n\n# ---------------------------------------------------------------------------\n# Snippet 1: Prepare the initial prompt for the generator. including few-shot examples or a zero-shot prompt.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nif retriever_gen is None:\n model_inp = TEMPLATE.format(example[\"db_id\"], example[\"schema\"], example[\"question\"])\nelse:\n demos = retriever_gen.retrieve(example[\"question\"])\n model_inp = \"\\n\".join(\n [TEMPLATE.format(ex[\"db_id\"], ex[\"schema\"], ex[\"question\"]) + ex[\"sql\"] for ex in demos]\n )\n model_inp += \"\\n\" + TEMPLATE.format(example[\"db_id\"], example[\"schema\"], example[\"question\"])\n\nprompt = model_inp\nif generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n prompt = INST_CODELLAMA_GEN.format(prompt) + \" SELECT\"\n# [End Snippet 1]\n\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Generate the initial set of SQL completions using the generator\n# based on the prepared prompt and configuration.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nresponses = generator.generate(prompt, config)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Extract and normalize unique SQL completions from the generator's\n# responses.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nif generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n sql_completions = list(set(\n [normalize_sql(r.split(\" [/INST] \")[-1].split(\"\\n\")[0]) for r in responses if r.split(\" [/INST] \")[-1].split(\"\\n\")[0] != \"\"]\n ))\nelse:\n sql_completions = list(set(\n [normalize_sql(r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0]) for r in responses if r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0] != \"\"]\n ))\n# [End Snippet 3]\n\ncurrent_score = 18 \npatience = 0 \ncandidates_scores = {} \nanswer_sql = \"\" \n\nfor t in range(10): \n # -----------------------------------------------------------------------\n # Snippet 4: Evaluate the current set of SQL completions using the evaluator.\n # Depending on the evaluator type, handle oracle evaluation with timeout\n # or standard scoring mechanisms. This step leverages the discriminator's\n # feedback to assess the quality of each SQL query.\n # -----------------------------------------------------------------------\n # [Begin Snippet 4]\n if args.evaluator_name == \"oracle\":\n try:\n scores = func_timeout(300.0, evaluator.score, args=(example[\"db_id\"], example[\"question\"], sql_completions, example[\"sql\"]))\n except:\n scores = [0]\n elif retriever_eval is None:\n scores = evaluator.score(example[\"db_id\"], example[\"question\"], sql_completions, evaluation_config)\n else:\n scores = evaluator.score_fewshot(example[\"db_id\"], example[\"question\"], sql_completions, retriever_eval, evaluation_config)\n # [End Snippet 4]\n\n # ---------------------------------------------------------------------------\n # Snippet 5: Determine the best score among the evaluated SQL completions.\n # This identifies the top-performing SQL query to consider for potential\n # acceptance or further refinement.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 5]\n best_score = min(scores) \n # [End Snippet 5]\n\n # ---------------------------------------------------------------------------\n # Snippet 6: Check if the best score meets the high-quality threshold or\n # if there's no improvement over consecutive iterations. If either condition\n # is met, exit the loop early to finalize the current best SQL query.\n # This implements the early termination criteria as specified in the LaTeX.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 6]\n if best_score < -0.99: \n answer_sql = sql_completions[np.argmin(scores)]\n current_score = best_score\n candidates_scores[answer_sql] = best_score\n break\n elif best_score >= current_score: \n patience += 1\n if patience >= 3:\n break\n else:\n answer_sql = sql_completions[np.argmin(scores)]\n current_score = best_score\n candidates_scores[answer_sql] = best_score\n patience = 0\n # [End Snippet 6]\n\n # ---------------------------------------------------------------------------\n # Snippet 7: Prepare the prompt for the next iteration by incorporating the\n # best SQL query found so far. This revised prompt guides the generator to\n # refine the SQL query in the subsequent round of corrections.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 7]\n prompt = TEMPLATE_CORR.format(example[\"db_id\"], example[\"schema\"], example[\"question\"], answer_sql)\n if generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n prompt = INST_CODELLAMA_ITER_CORR.format(prompt) + \" SELECT\"\n # [End Snippet 7]\n\n # ---------------------------------------------------------------------------\n # Snippet 8: Generate a new set of SQL completions based on the revised prompt\n # and normalize them. This iterative generation aims to improve the SQL query\n # by leveraging the discriminator's feedback from the previous evaluation.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 8]\n responses = generator.generate(prompt, config)\n if generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n sql_completions = list(set(\n [normalize_sql(r.split(\" [/INST] \")[-1].split(\"\\n\")[0]) for r in responses if r.split(\" [/INST] \")[-1].split(\"\\n\")[0] != \"\"]\n ))\n else:\n sql_completions = list(set(\n [normalize_sql(r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0]) for r in responses if r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0] != \"\"]\n ))\n # [End Snippet 8]\n\n# ---------------------------------------------------------------------------\n# Snippet 9: After completing the iterative correction process, finalize the\n# best SQL query by cleaning and normalizing it.\n# Return the answer.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 9]\nanswer = answer_sql.replace(\"\\n\", \" \")\nexample_log = deepcopy(example)\nexample_log[\"candidates\"] = candidates_scores \nlog.append(example_log)\nreturn answer\n# [End Snippet 9]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The initial score for the iterative refinement process is set to 18 in the code, which is not specified in the LaTeX text.\n - The process of using a \u201cretriever\u201d (`retriever_gen` and `retriever_eval`) to produce few-shot demonstrations or evaluation examples is omitted from the LaTeX description. The reference code either retrieves examples from a BM25 retriever or falls back to zero-shot prompting.\n - The maximum iteration for the iterative refinement process is 10.\n - Evaluation configuration handling: The code constructs the prompt for the generator in a dynamic way, supporting both zero-shot and few-shot prompting scenarios. In the zero-shot case (`retriever_gen is None`), it formats a template with the current example\u2019s database ID, schema, and question to create a standalone prompt. In the few-shot case, it uses a retriever to fetch similar examples, formats each with their database ID, schema, question, and SQL query, joins these demonstrations with single newlines, and appends the current example\u2019s prompt. This workflow enables the generator to leverage contextual examples for improved performance, a process not detailed in the LaTeX description\u2019s simple mention of \"sampling a few complete action sequences.\"\n - SQL extraction methodology: The code extracts SQL queries from responses by splitting on markers and taking the first line (e.g., `r.split(\" [/INST] \")[-1].split(\"\\n\")[0]` for CodeLlama), assuming a single-line query format.\n\n Mismatched Details:\n - The LaTeX states an early-exit threshold for a high-quality score of (> 0.99), whereas the code uses (< -0.99). This suggests the code\u2019s scoring mechanism is reversed or uses negative scoring.\n", "Missing_details": [ "\n- The initial score for the iterative refinement process is set to 18 in the code, which is not specified in the LaTeX text.\n", "\n- The process of using a \u201cretriever\u201d (`retriever_gen` and `retriever_eval`) to produce few-shot demonstrations or evaluation examples is omitted from the LaTeX description. The reference code either retrieves examples from a BM25 retriever or falls back to zero-shot prompting.\n", "\n- The maximum iteration for the iterative refinement process is 10.\n", "\n- Evaluation configuration handling: The code constructs the prompt for the generator in a dynamic way, supporting both zero-shot and few-shot prompting scenarios. In the zero-shot case (`retriever_gen is None`), it formats a template with the current example\u2019s database ID, schema, and question to create a standalone prompt. In the few-shot case, it uses a retriever to fetch similar examples, formats each with their database ID, schema, question, and SQL query, joins these demonstrations with single newlines, and appends the current example\u2019s prompt. This workflow enables the generator to leverage contextual examples for improved performance, a process not detailed in the LaTeX description\u2019s simple mention of \"sampling a few complete action sequences.\"\n", "\n- SQL extraction methodology: The code extracts SQL queries from responses by splitting on markers and taking the first line (e.g., `r.split(\" [/INST] \")[-1].split(\"\\n\")[0]` for CodeLlama), assuming a single-line query format.\n" ], "Mismatched_details": [ "\n- The LaTeX states an early-exit threshold for a high-quality score of (> 0.99), whereas the code uses (< -0.99). This suggests the code\u2019s scoring mechanism is reversed or uses negative scoring.\n" ] }, "Arguments": { "Arguments_list": [ { "name": "example", "string": "\n- example (dict): A dictionary containing details about the current example, including:\n - \"db_id\" (str): The database identifier.\n - \"schema\" (str): The schema of the database.\n - \"question\" (str): The user question.\n - \"sql\" (str, optional): The ground truth SQL (used for oracle evaluation).\n", "dependency": null }, { "name": "generator", "string": "\n- generator (generators.hf_generator.HFGenerator ,object): The generator used to produce SQL query completions based on prompts.\n - The HFGeneratordefined class is defined in generators/hf_generator.py\n", "dependency": "generators.hf_generator.HFGenerator" }, { "name": "evaluator", "string": "\n- evaluator (evaluators.oracle_evaluator.OracleEvaluator, object): The evaluator (discriminator) that scores the generated SQL queries.\n - The OracleEvaluator class is defined in evaluators/oracle_evaluator.py\n", "dependency": "evaluators.oracle_evaluator.OracleEvaluator" }, { "name": "retriever_gen", "string": "\n- retriever_gen (retrievers.bm25.BM25Retriever object or None): A retriever object for finding similar examples for 1-shot or few-shot prompting.\n If None, a zero-shot prompt is used.\n - The BM25Retriever class is defined in retrievers/bm25.py\n", "dependency": "retrievers.bm25.BM25Retriever" }, { "name": "retriever_eval", "string": "\n- retriever_eval (object or None): A retriever object for evaluation-specific few-shot examples.\n If None, default evaluation is used.\n", "dependency": null }, { "name": "args", "string": "\n- args (inference.args_definition, Namespace): Configuration arguments containing paths to generation and evaluation configs,\n as well as evaluator settings (e.g., evaluator name).\n - args is defined in the args_definition() function in inference.py\n", "dependency": null }, { "name": "log", "string": "\n- log (list): A log to store details of the re-ranking process for later analysis.\n", "dependency": null }, { "name": "The template for the initial prompt is defined in the utils.constants file:", "string": "\nThe template for the initial prompt is defined in the utils.constants file:\n - utils.constants.TEMPLATE: The template for the initial prompt, which includes the database schema and user question.\n - utils.constants.INST_CODELLAMA_GEN: The template for the codellama instruct generation model.\n - utils.constants.TEMPLATE_CORR: The prompt template for correction after the initial generation.\n - utils.constants.INST_CODELLAMA_ITER_CORR: The template for the codellama instruct iteration correction model.\n", "dependency": null } ], "string": "\nInput Variables:\n - example (dict): A dictionary containing details about the current example, including:\n - \"db_id\" (str): The database identifier.\n - \"schema\" (str): The schema of the database.\n - \"question\" (str): The user question.\n - \"sql\" (str, optional): The ground truth SQL (used for oracle evaluation).\n - generator (generators.hf_generator.HFGenerator ,object): The generator used to produce SQL query completions based on prompts.\n - The HFGeneratordefined class is defined in generators/hf_generator.py\n - evaluator (evaluators.oracle_evaluator.OracleEvaluator, object): The evaluator (discriminator) that scores the generated SQL queries.\n - The OracleEvaluator class is defined in evaluators/oracle_evaluator.py\n - retriever_gen (retrievers.bm25.BM25Retriever object or None): A retriever object for finding similar examples for 1-shot or few-shot prompting. \n If None, a zero-shot prompt is used.\n - The BM25Retriever class is defined in retrievers/bm25.py\n - retriever_eval (object or None): A retriever object for evaluation-specific few-shot examples.\n If None, default evaluation is used.\n - args (inference.args_definition, Namespace): Configuration arguments containing paths to generation and evaluation configs,\n as well as evaluator settings (e.g., evaluator name). It is defined in the args_definition() function in inference.py\n - args.evaluation_config: The evaluation configuration for scoring the generated SQL queries.\n - args.generation_config: The generation configuration for generating SQL completions.\n - log (list): A log to store details of the re-ranking process for later analysis.\n The template for the initial prompt is defined in the utils.constants file:\n - utils.constants.TEMPLATE: The template for the initial prompt, which includes the database schema and user question.\n - utils.constants.INST_CODELLAMA_GEN: The template for the codellama instruct generation model.\n - utils.constants.TEMPLATE_CORR: The prompt template for correction after the initial generation.\n - utils.constants.INST_CODELLAMA_ITER_CORR: The template for the codellama instruct iteration correction model.\n" }, "dependency": { "string": "\nDependencies: \n - Intra File Dependencies: \n - None\n \n - Cross File Dependencies: \n - utils.normalize_sql.normalize_sql\n", "intra_file": [], "cross_file": [ "utils.normalize_sql.normalize_sql" ] }, "external_APIs": { "string": "\nExternal APIs:\n - func_timeout.func_timeout\n - copy.deepcopy\n - json.load\n - numpy.argmin\n", "list": [ "func_timeout.func_timeout", "copy.deepcopy", "json.load", "numpy.argmin" ] }, "Return": { "Return_list": [ { "name": "answer", "string": "- answer (str): The SQL query from the generated completions with the highest (best) score, normalized and cleaned.", "dependency": null } ], "Return_String": "\nOutput Variables:\n - answer (str): The SQL query from the generated completions with the highest (best) score, normalized and cleaned.\n" }, "ori_python_file": "from utils.constants import TEMPLATE, TEMPLATE_CORR, INST_CODELLAMA_GEN, INST_CODELLAMA_ITER_CORR\nfrom utils.normalize_sql import normalize_sql\nfrom copy import deepcopy\nfrom func_timeout import func_timeout\nimport os, pickle\nimport numpy as np\nimport json\n\ndef iter_correction(example, generator, evaluator, retriever_gen, retriever_eval, args, log):\n config = json.load(open(args.generation_config))\n evaluation_config = json.load(open(args.evaluation_config))\n if retriever_gen is None:\n model_inp = TEMPLATE.format(example[\"db_id\"], example[\"schema\"], example[\"question\"])\n else:\n demos = retriever_gen.retrieve(example[\"question\"])\n model_inp = \"\\n\".join(\n [TEMPLATE.format(ex[\"db_id\"], ex[\"schema\"], ex[\"question\"]) + ex[\"sql\"] for ex in demos]\n )\n model_inp += \"\\n\" + TEMPLATE.format(example[\"db_id\"], example[\"schema\"], example[\"question\"])\n prompt = model_inp\n if generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n prompt = INST_CODELLAMA_GEN.format(prompt) + \" SELECT\"\n responses = generator.generate(prompt, config)\n if generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n sql_completions = list(set(\n [normalize_sql(r.split(\" [/INST] \")[-1].split(\"\\n\")[0]) for r in responses if r.split(\" [/INST] \")[-1].split(\"\\n\")[0] != \"\"]\n ))\n else:\n sql_completions = list(set(\n [normalize_sql(r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0]) for r in responses if r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0] != \"\"]\n ))\n current_score = 18\n patience = 0\n candidates_scores = {}\n answer_sql = \"\"\n for t in range(10):\n if args.evaluator_name == \"oracle\":\n try:\n scores = func_timeout(300.0, evaluator.score, args=(example[\"db_id\"], example[\"question\"], sql_completions, example[\"sql\"]))\n except:\n scores = [0]\n elif retriever_eval is None:\n scores = evaluator.score(example[\"db_id\"], example[\"question\"], sql_completions, evaluation_config)\n else:\n scores = evaluator.score_fewshot(example[\"db_id\"], example[\"question\"], sql_completions, retriever_eval, evaluation_config)\n best_score = min(scores)\n if best_score < -0.99:\n answer_sql = sql_completions[np.argmin(scores)]\n current_score = best_score\n candidates_scores[answer_sql] = best_score\n break\n elif best_score >= current_score:\n patience += 1\n if patience >= 3:\n break\n else:\n answer_sql = sql_completions[np.argmin(scores)]\n current_score = best_score\n candidates_scores[answer_sql] = best_score\n patience = 0\n prompt = TEMPLATE_CORR.format(example[\"db_id\"], example[\"schema\"], example[\"question\"], answer_sql)\n if generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n prompt = INST_CODELLAMA_ITER_CORR.format(prompt) + \" SELECT\"\n responses = generator.generate(prompt, config)\n if generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n sql_completions = list(set(\n [normalize_sql(r.split(\" [/INST] \")[-1].split(\"\\n\")[0]) for r in responses if r.split(\" [/INST] \")[-1].split(\"\\n\")[0] != \"\"]\n ))\n else:\n sql_completions = list(set(\n [normalize_sql(r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0]) for r in responses if r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0] != \"\"]\n ))\n answer = answer_sql.replace(\"\\n\", \" \")\n example_log = deepcopy(example)\n example_log[\"candidates\"] = candidates_scores\n log.append(example_log)\n return answer" }, { "task_id": 2, "indent": 1, "latex_code": "\n\\noindent \\textbf{Tree Search.} \nTree search is another popular planning method for language agents, such as Monte-Carlo Tree Search \\citep{chaffin-etal-2022-ppl}, Pangu \\citep{gu-etal-2023-dont}, RAP \\citep{hao-etal-2023-reasoning}, Tree of Thoughts \\citep{yao2023tot}, and LATS \\citep{zhou2023language}. \nIt uses a memory structure (e.g., a heap) to store observed partial action sequences and their scores.\nFor each iteration, it prompts the generator for possible next steps of the current best partial plan, calls the discriminator to evaluate the steps, and updates the memory with new plans and scores (Figure \\ref{fig:ts}).\nOur tree search implementation is a kind of MCTS \\citep{zhang2023planning}:\n\n\\noindent \\textbf{(1)} \\textit{Selection}: Find the highest scoring partial plan in the memory, implemented as a heap structure.\n\n\\noindent \\textbf{(2)} \\textit{Expansion}: Prompt the generator for the next step of this partial plan. \nWe follow recent work to define a step to be a SQL clause \\citep{chen-etal-2023-text} or one line of Python code \\citep{bui-etal-2022-detect}, which is semantically more meaningful. \n\n\\noindent \\textbf{(3)} \\textit{Simulation}: Reuse the generator to complete the partial plans as Monte-Carlo simulations.\n\n\n\\noindent \\textbf{(4)} \\textit{Evaluation}: Evaluate the simulations with the discriminator.\nThe score for each new step is the maximum score of all simulations starting from it.\n\n\\noindent \\textbf{(5)} \\textit{Backpropagation}: Update the partial plan with the new step and score (if higher) and insert them into the heap memory.\nAfter the update, if there is a complete plan in the heap memory, we terminate the tree search and return this plan.\n", "completion_path": "./planning_methods/mc_tot.py", "namespace": "planning_methods.mc_tot.mc_tot", "type": "function", "signature_position": [ 10, 10 ], "body_position": [ 11, 89 ], "script": "\npython -u inference.py \\\n --test_fname data/spider_dev_400.json \\\n --result_fname results/spider_dev_oracle_rerank_10.sql \\\n --log_fname spider_dev_oracle_rerank_10.json \\\n --dataset_name spider \\\n --db_path ../spider/database \\\n --method_name mctot \\\n --generator_name codellama/CodeLlama-13b-Instruct-hf \\\n --retriever_name bm25 \\\n --retriever_corpus_gen data/spider_train.json \\\n --evaluator_name oracle \\\n --oracle_prob 1.0 \\\n --retrieve_k 1 \\\n --seed 42 \\\n --generation_config generation_configs/temp_sampling.json \\\n --evaluation_config evaluation_configs/pro.json\n", "ReferenceCode_With_Comments": "\nconfig = json.load(open(args.generation_config)) \nevaluation_config = json.load(open(args.evaluation_config)) \n\n# ---------------------------------------------------------------------------\n# Snippet 1: Initialize the model input by formatting the template with the database\n# ID, schema, and user question. Including few-shot examples or a zero-shot prompt.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nif retriever_gen is None:\n model_inp = TEMPLATE.format(example[\"db_id\"], example[\"schema\"], example[\"question\"])\nelse:\n demos = retriever_gen.retrieve(example[\"question\"])\n model_inp = \"\\n\".join(\n [TEMPLATE.format(ex[\"db_id\"], ex[\"schema\"], ex[\"question\"]) + ex[\"sql\"] for ex in demos]\n )\n model_inp += \"\\n\" + TEMPLATE.format(example[\"db_id\"], example[\"schema\"], example[\"question\"])\nprompt = model_inp\nif generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n prompt = INST_CODELLAMA_GEN.format(prompt) + \" SELECT\"\n# [End Snippet 1]\n\npartial_sql = \"\" \ncurrent_score = 18 \nheap = [] \ncandidates = [] \nsql_score_cache = {} \n\nfor t in range(50): \n # -----------------------------------------------------------------------\n # Snippet 2: Generate possible SQL completions for the current prompt using the\n # generator. This corresponds to the Expansion phase where new steps are\n # proposed for the partial plan.\n # -----------------------------------------------------------------------\n # [Begin Snippet 2]\n responses = generator.generate(prompt, config)\n if generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n sql_completions = list(set(\n [normalize_sql(r.split(\" [/INST] \")[-1].split(\"\\n\")[0]) for r in responses if r.split(\" [/INST] \")[-1].split(\"\\n\")[0] != \"\"]\n ))\n else:\n sql_completions = list(set(\n [normalize_sql(r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0]) for r in responses if r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0] != \"\"]\n ))\n # [End Snippet 2]\n\n # ---------------------------------------------------------------------------\n # Snippet 3: Extract the meaningful next steps from the generated SQL completions,\n # ensuring that each step is semantically coherent and properly formatted.\n # This prepares the candidates for simulation.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 3]\n steps = set([\n (\n segment_step(sql[len(partial_sql):].lstrip()).rstrip()\n if len(sql) > len(partial_sql)\n else sql\n )\n for sql in sql_completions\n ])\n # [End Snippet 3]\n\n step_score = {}\n\n # ---------------------------------------------------------------------------\n # Snippet 4: Iterate over each proposed step to perform Simulation and Evaluation.\n # Generate rollouts for each step and evaluate their quality using the discriminator.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 4]\n for s in steps:\n mc_prompt = model_inp + partial_sql\n if generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n mc_prompt = INST_CODELLAMA_GEN.format(model_inp) + \" \" + partial_sql + \" \" + s\n\n mc_rollouts = generator.generate(mc_prompt, config)\n if generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n mc_sql_completions = list(set(\n [normalize_sql(r.split(\" [/INST] \")[-1].split(\"\\n\")[0]) for r in mc_rollouts if r.split(\" [/INST] \")[-1].split(\"\\n\")[0] != \"\"]\n ))\n else:\n mc_sql_completions = list(set(\n [normalize_sql(r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0]) for r in mc_rollouts if r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0] != \"\"]\n ))\n\n try:\n if args.evaluator_name == \"oracle\":\n scores = func_timeout(300.0, evaluator.score, args=(example[\"db_id\"], example[\"question\"], mc_sql_completions, example[\"sql\"]))\n elif retriever_eval is None:\n scores = func_timeout(300.0, evaluator.score, args=(example[\"db_id\"], example[\"question\"], mc_sql_completions, evaluation_config))\n else:\n scores = func_timeout(300.0, evaluator.score_fewshot, args=(example[\"db_id\"], example[\"question\"], mc_sql_completions, retriever_eval, evaluation_config))\n except:\n scores = [0 for _ in mc_sql_completions]\n\n step_score[s] = min(scores)\n # [End Snippet 4]\n\n # ---------------------------------------------------------------------------\n # Snippet 5: For each step, if the evaluated score meets the threshold, add the\n # new partial plan to the heap. This integrates the Evaluation results back\n # into the search tree, facilitating Backpropagation.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 5]\n for k, v in step_score.items():\n if v <= 0: \n heapq.heappush(heap, (v, partial_sql + \" \" + k))\n # [End Snippet 5]\n\n # ---------------------------------------------------------------------------\n # Snippet 6: If no valid candidates are found in the heap, either terminate the\n # search or continue with the best available partial SQL. This handles cases\n # where expansions do not yield promising results.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 6]\n if len(heap) == 0:\n if not partial_sql.endswith(\";\"):\n partial_sql = sql_completions[0]\n break\n # [End Snippet 6]\n\n # ---------------------------------------------------------------------------\n # Snippet 7: Selection phase where the highest scoring partial plan is selected\n # from the heap for further expansion. If a complete plan is found, terminate\n # the search.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 7]\n current_score, partial_sql = heapq.heappop(heap)\n if partial_sql.endswith(\";\"): \n break\n else:\n partial_sql = normalize_sql(partial_sql).rstrip(\";\")\n prompt = (INST_CODELLAMA_GEN.format(model_inp) if generator.base_model_name.startswith(\"codellama\") else model_inp) + \" \" + partial_sql\n # [End Snippet 7]\n\n# ---------------------------------------------------------------------------\n# Snippet 8: After completing the iterations, finalize the best SQL query by\n# normalizing and cleaning it. Log the final heap state for analysis and return\n# the optimized query as the answer.\n# Return the answer as the final SQL query.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 8]\nanswer = partial_sql.replace(\"\\n\", \" \")\nheapq.heappush(heap, (current_score, partial_sql))\nexample_log = deepcopy(example)\nexample_log[\"heap\"] = dict([(t[1], t[0]) for t in heap])\nlog.append(example_log)\nreturn answer\n# [End Snippet 8]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The initial score for the iterative refinement process is set to 18 in the code, which is not specified in the LaTeX text.\n - The maximum iteration for the iterative process of the tree search is 50.\n - Step segmentation logic: The LaTeX does not mention the critical process of extracting semantically meaningful steps (e.g., SQL clauses) from raw generator outputs. The code should uses split SQL completions into valid partial plans by trimming redundant prefixes/suffixes and normalizing syntax, which is essential for valid tree construction.\n - Evaluation configuration handling: The code constructs the prompt for the generator in a dynamic way, supporting both zero-shot and few-shot prompting scenarios. In the zero-shot case (`retriever_gen is None`), it formats a template with the current example\u2019s database ID, schema, and question to create a standalone prompt. In the few-shot case, it uses a retriever to fetch similar examples, formats each with their database ID, schema, question, and SQL query, joins these demonstrations with single newlines, and appends the current example\u2019s prompt. This workflow enables the generator to leverage contextual examples for improved performance, a process not detailed in the LaTeX description\u2019s simple mention of \"sampling a few complete action sequences.\"\n - SQL extraction methodology: The code extracts SQL queries from responses by splitting on markers and taking the first line (e.g., `r.split(\" [/INST] \")[-1].split(\"\\n\")[0]` for CodeLlama), assuming a single-line query format.\n\n Mismatched Details:\n - The LaTeX states an early-exit threshold for a high-quality score of (> 0.99), whereas the code uses (< -0.99). This suggests the code\u2019s scoring mechanism is reversed or uses negative scoring.\n - Simulation uses minimum score instead of maximum as described in LaTeX.\n - Termination condition: The paper states termination occurs when \"a complete plan is in the heap\", but the code should explicitly checks for SQL statements ending with semicolons.\n", "Missing_details": [ "\n- The initial score for the iterative refinement process is set to 18 in the code, which is not specified in the LaTeX text.\n", "\n- The maximum iteration for the iterative process of the tree search is 50.\n", "\n- Step segmentation logic: The LaTeX does not mention the critical process of extracting semantically meaningful steps (e.g., SQL clauses) from raw generator outputs. The code should uses split SQL completions into valid partial plans by trimming redundant prefixes/suffixes and normalizing syntax, which is essential for valid tree construction.\n", "\n- Evaluation configuration handling: The code constructs the prompt for the generator in a dynamic way, supporting both zero-shot and few-shot prompting scenarios. In the zero-shot case (`retriever_gen is None`), it formats a template with the current example\u2019s database ID, schema, and question to create a standalone prompt. In the few-shot case, it uses a retriever to fetch similar examples, formats each with their database ID, schema, question, and SQL query, joins these demonstrations with single newlines, and appends the current example\u2019s prompt. This workflow enables the generator to leverage contextual examples for improved performance, a process not detailed in the LaTeX description\u2019s simple mention of \"sampling a few complete action sequences.\"\n", "\n- SQL extraction methodology: The code extracts SQL queries from responses by splitting on markers and taking the first line (e.g., `r.split(\" [/INST] \")[-1].split(\"\\n\")[0]` for CodeLlama), assuming a single-line query format.\n" ], "Mismatched_details": [ "\n- The LaTeX states an early-exit threshold for a high-quality score of (> 0.99), whereas the code uses (< -0.99). This suggests the code\u2019s scoring mechanism is reversed or uses negative scoring.\n", "\n- Simulation uses minimum score instead of maximum as described in LaTeX.\n", "\n- Termination condition: The paper states termination occurs when \"a complete plan is in the heap\", but the code should explicitly checks for SQL statements ending with semicolons.\n" ] }, "Arguments": { "Arguments_list": [ { "name": "example", "string": "\n- example (dict): A dictionary containing details about the current example, including:\n - \"db_id\" (str): The database identifier.\n - \"schema\" (str): The schema of the database.\n - \"question\" (str): The user question.\n - \"sql\" (str, optional): The ground truth SQL (used for oracle evaluation).\n", "dependency": null }, { "name": "generator", "string": "\n- generator (generators.hf_generator.HFGenerator ,object): The generator used to produce SQL query completions based on prompts.\n - The HFGeneratordefined class is defined in generators/hf_generator.py\n", "dependency": "generators.hf_generator.HFGenerator" }, { "name": "evaluator", "string": "\n- evaluator (evaluators.oracle_evaluator.OracleEvaluator, object): The evaluator (discriminator) that scores the generated SQL queries.\n - The OracleEvaluator class is defined in evaluators/oracle_evaluator.py\n", "dependency": "evaluators.oracle_evaluator.OracleEvaluator" }, { "name": "retriever_gen", "string": "\n- retriever_gen (retrievers.bm25.BM25Retriever object or None): A retriever object for finding similar examples for 1-shot or few-shot prompting.\n If None, a zero-shot prompt is used.\n - The BM25Retriever class is defined in retrievers/bm25.py\n", "dependency": "retrievers.bm25.BM25Retriever" }, { "name": "retriever_eval", "string": "\n- retriever_eval (object or None): A retriever object for evaluation-specific few-shot examples.\n If None, default evaluation is used.\n", "dependency": null }, { "name": "args", "string": "\n- args (inference.args_definition, Namespace): Configuration arguments containing paths to generation and evaluation configs,\n as well as evaluator settings (e.g., evaluator name).\n - args is defined in the args_definition() function in inference.py\n", "dependency": null }, { "name": "log", "string": "\n- log (list): A log to store details of the re-ranking process for later analysis.\n", "dependency": null }, { "name": "The template for the initial prompt is defined in the utils.constants file:", "string": "\nThe template for the initial prompt is defined in the utils.constants file:\n - utils.constants.TEMPLATE: The template for the initial prompt, which includes the database schema and user question.\n - utils.constants.INST_CODELLAMA_GEN: The template for the codellama instruct generation model.\n", "dependency": null } ], "string": "\nInput Variables:\n - example (dict): A dictionary containing details about the current example, including:\n - \"db_id\" (str): The database identifier.\n - \"schema\" (str): The schema of the database.\n - \"question\" (str): The user question.\n - \"sql\" (str, optional): The ground truth SQL (used for oracle evaluation).\n - generator (generators.hf_generator.HFGenerator ,object): The generator used to produce SQL query completions based on prompts.\n - The HFGeneratordefined class is defined in generators/hf_generator.py\n - evaluator (evaluators.oracle_evaluator.OracleEvaluator, object): The evaluator (discriminator) that scores the generated SQL queries.\n - The OracleEvaluator class is defined in evaluators/oracle_evaluator.py\n - retriever_gen (retrievers.bm25.BM25Retriever object or None): A retriever object for finding similar examples for 1-shot or few-shot prompting. \n If None, a zero-shot prompt is used.\n - The BM25Retriever class is defined in retrievers/bm25.py\n - retriever_eval (object or None): A retriever object for evaluation-specific few-shot examples.\n If None, default evaluation is used.\n - args (inference.args_definition, Namespace): Configuration arguments containing paths to generation and evaluation configs,\n as well as evaluator settings (e.g., evaluator name). It is defined in the args_definition() function in inference.py\n - args.evaluation_config: The evaluation configuration for scoring the generated SQL queries.\n - args.generation_config: The generation configuration for generating SQL completions.\n - log (list): A log to store details of the re-ranking process for later analysis.\n The template for the initial prompt is defined in the utils.constants file:\n - utils.constants.TEMPLATE: The template for the initial prompt, which includes the database schema and user question.\n - utils.constants.INST_CODELLAMA_GEN: The template for the codellama instruct generation model.\n" }, "dependency": { "string": "\nDependencies: \n - Intra File Dependencies:\n - None\n \n - Cross File Dependencies: \n - utils.normalize_sql.normalize_sql\n - utils.inference_utils.segment_step\n", "intra_file": [], "cross_file": [ "utils.normalize_sql.normalize_sql", "utils.inference_utils.segment_step" ] }, "external_APIs": { "string": "\nExternal APIs:\n - func_timeout.func_timeout\n - copy.deepcopy\n - json.load\n - heapq.heappush\n", "list": [ "func_timeout.func_timeout", "copy.deepcopy", "json.load", "heapq.heappush" ] }, "Return": { "Return_list": [ { "name": "answer", "string": "- answer (str): The SQL query from the generated completions with the highest (best) score, normalized and cleaned.", "dependency": null } ], "Return_String": "\nOutput Variables:\n - answer (str): The SQL query from the generated completions with the highest (best) score, normalized and cleaned.\n" }, "ori_python_file": "from utils.constants import TEMPLATE, INST_CODELLAMA_GEN\nfrom utils.inference_utils import segment_step\nfrom utils.normalize_sql import normalize_sql\nfrom copy import deepcopy\nfrom func_timeout import func_timeout\nimport os, pickle\nimport heapq\nimport json\n\ndef mc_tot(example, generator, evaluator, retriever_gen, retriever_eval, args, log):\n config = json.load(open(args.generation_config))\n evaluation_config = json.load(open(args.evaluation_config))\n if retriever_gen is None:\n model_inp = TEMPLATE.format(example[\"db_id\"], example[\"schema\"], example[\"question\"])\n else:\n demos = retriever_gen.retrieve(example[\"question\"])\n model_inp = \"\\n\".join(\n [TEMPLATE.format(ex[\"db_id\"], ex[\"schema\"], ex[\"question\"]) + ex[\"sql\"] for ex in demos]\n )\n model_inp += \"\\n\" + TEMPLATE.format(example[\"db_id\"], example[\"schema\"], example[\"question\"])\n prompt = model_inp\n if generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n prompt = INST_CODELLAMA_GEN.format(prompt) + \" SELECT\"\n partial_sql = \"\"\n current_score = 18\n heap = []\n candidates = []\n sql_score_cache = {}\n for t in range(50):\n responses = generator.generate(prompt, config)\n if generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n sql_completions = list(set(\n [normalize_sql(r.split(\" [/INST] \")[-1].split(\"\\n\")[0]) for r in responses if r.split(\" [/INST] \")[-1].split(\"\\n\")[0] != \"\"]\n ))\n else:\n sql_completions = list(set(\n [normalize_sql(r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0]) for r in responses if r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0] != \"\"]\n ))\n steps = set([\n (\n segment_step(sql[len(partial_sql):].lstrip()).rstrip()\n if len(sql) > len(partial_sql)\n else sql\n )\n for sql in sql_completions\n ])\n step_score = {}\n for s in steps:\n mc_prompt = model_inp + partial_sql\n if generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n mc_prompt = INST_CODELLAMA_GEN.format(model_inp) + \" \" + partial_sql + \" \" + s\n mc_rollouts = generator.generate(mc_prompt, config)\n if generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n mc_sql_completions = list(set(\n [normalize_sql(r.split(\" [/INST] \")[-1].split(\"\\n\")[0]) for r in mc_rollouts if r.split(\" [/INST] \")[-1].split(\"\\n\")[0] != \"\"]\n ))\n else:\n mc_sql_completions = list(set(\n [normalize_sql(r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0]) for r in mc_rollouts if r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0] != \"\"]\n ))\n try:\n if args.evaluator_name == \"oracle\":\n scores = func_timeout(300.0, evaluator.score, args=(example[\"db_id\"], example[\"question\"], mc_sql_completions, example[\"sql\"]))\n elif retriever_eval is None:\n scores = func_timeout(300.0, evaluator.score, args=(example[\"db_id\"], example[\"question\"], mc_sql_completions, evaluation_config))\n else:\n scores = func_timeout(300.0, evaluator.score_fewshot, args=(example[\"db_id\"], example[\"question\"], mc_sql_completions, retriever_eval, evaluation_config))\n except:\n scores = [0 for _ in mc_sql_completions]\n step_score[s] = min(scores)\n for k, v in step_score.items():\n if v <= 0:\n heapq.heappush(heap, (v, partial_sql + \" \" + k))\n if len(heap) == 0:\n if not partial_sql.endswith(\";\"):\n partial_sql = sql_completions[0]\n break\n current_score, partial_sql = heapq.heappop(heap)\n if partial_sql.endswith(\";\"):\n break\n else:\n partial_sql = normalize_sql(partial_sql).rstrip(\";\")\n prompt = (INST_CODELLAMA_GEN.format(model_inp) if generator.base_model_name.startswith(\"codellama\") else model_inp) + \" \" + partial_sql\n answer = partial_sql.replace(\"\\n\", \" \")\n heapq.heappush(heap, (current_score, partial_sql))\n example_log = deepcopy(example)\n example_log[\"heap\"] = dict([(t[1], t[0]) for t in heap])\n log.append(example_log)\n return answer" }, { "task_id": 3, "indent": 1, "latex_code": "\n\\noindent \\textbf{Re-ranking.} \nRe-ranking is a straightforward planning method.\nAfter sampling a few complete action sequences from the generator, it uses the discriminator to score them and return the highest-scoring plan (Figure \\ref{fig:rr}).\nAlthough simple, it is commonly used for code generation \\citep{pmlr-v202-ni23b-lever} and mathematical reasoning tasks \\citep{wang2023selfconsistency, li-etal-2023-making}.\nWe consider re-ranking as a baseline planning method for more advanced ones. \n", "script": "\npython -u inference.py \\\n --test_fname data/spider_dev_400.json \\\n --result_fname results/spider_dev_oracle_rerank_10.sql \\\n --log_fname spider_dev_oracle_rerank_10.json \\\n --dataset_name spider \\\n --db_path ../spider/database \\\n --method_name rerank \\\n --generator_name codellama/CodeLlama-13b-Instruct-hf \\\n --retriever_name bm25 \\\n --retriever_corpus_gen data/spider_train.json \\\n --evaluator_name oracle \\\n --oracle_prob 1.0 \\\n --retrieve_k 1 \\\n --seed 42 \\\n --generation_config generation_configs/temp_sampling.json \\\n --evaluation_config evaluation_configs/pro.json\n", "completion_path": "./planning_methods/rerank.py", "namespace": "planning_methods.rerank.rerank", "type": "function", "signature_position": [ 8, 8 ], "body_position": [ 9, 36 ], "ReferenceCode_With_Comments": "\nconfig = json.load(open(args.generation_config)) \nevaluation_config = json.load(open(args.evaluation_config)) \n\n# ---------------------------------------------------------------------------\n# Snippet 1: Construct the prompt for the generator. If a retriever is available,\n# incorporate few-shot examples to guide the generation; otherwise, proceed with zero-shot prompting.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nif retriever_gen is None:\n model_inp = TEMPLATE.format(example[\"db_id\"], example[\"schema\"], example[\"question\"])\n prompt = model_inp\nelse:\n demos = retriever_gen.retrieve(example[\"question\"])\n model_inp = \"\\n\".join([TEMPLATE.format(ex[\"db_id\"], ex[\"schema\"], ex[\"question\"]) + ex[\"sql\"] for ex in demos])\n prompt = model_inp + \"\\n\" + TEMPLATE.format(example[\"db_id\"], example[\"schema\"], example[\"question\"])\n\nif generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n prompt = INST_CODELLAMA_GEN.format(prompt) + \" SELECT\"\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Generate multiple SQL query completions using the configured generator and prompt.\n# This step directly corresponds to sampling complete action sequences from the generator.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nresponses = generator.generate(prompt, config)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Process and normalize the generated responses to extract unique SQL completions,\n# ensuring that only valid and distinct queries are considered for evaluation.\n# This aligns with preparing the action sequences for scoring.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nif generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n sql_completions = list(set([normalize_sql(r.split(\" [/INST] \")[-1].split(\"\\n\")[0]) for r in responses if r.split(\" [/INST] \")[-1].split(\"\\n\")[0] != \"\"]))\nelse:\n sql_completions = list(set([normalize_sql(r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0]) for r in responses if r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0] != \"\"]))\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Utilize the evaluator to score each generated SQL completion. Depending on the evaluator\n# configuration, perform either standard or few-shot evaluation to obtain relevance scores.\n# This step embodies the use of the discriminator to assess and rank the action sequences.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nif args.evaluator_name == \"oracle\":\n scores = evaluator.score(example[\"db_id\"], example[\"question\"], sql_completions, example[\"sql\"])\nelif retriever_eval is None:\n scores = evaluator.score(example[\"db_id\"], example[\"question\"], sql_completions, evaluation_config)\nelse:\n scores = evaluator.score_fewshot(example[\"db_id\"], example[\"question\"], sql_completions, retriever_eval, evaluation_config)\n# [End Snippet 4]\n\nexample_log = deepcopy(example)\nexample_log[\"top_n\"] = sql_completions \nexample_log[\"scores\"] = scores \nlog.append(example_log)\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Select and return the SQL query with the highest score (i.e., the best-ranked plan),\n# finalizing the re-ranking process by choosing the most suitable action sequence.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nanswer = sql_completions[np.argmin(scores)].replace(\"\\n\", \" \")\nreturn answer\n# [End Snippet 5]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - Response processing and deduplication: The LaTeX description omits the critical step of normalizing SQL queries and removing duplicates from generated responses using list(set(...)), which ensures only distinct/valid candidates are considered during scoring.\n - Evaluation configuration handling: The code constructs the prompt for the generator in a dynamic way, supporting both zero-shot and few-shot prompting scenarios. In the zero-shot case (`retriever_gen is None`), it formats a template with the current example\u2019s database ID, schema, and question to create a standalone prompt. In the few-shot case, it uses a retriever to fetch similar examples, formats each with their database ID, schema, question, and SQL query, joins these demonstrations with single newlines, and appends the current example\u2019s prompt. This workflow enables the generator to leverage contextual examples for improved performance, a process not detailed in the LaTeX description\u2019s simple mention of \"sampling a few complete action sequences.\"\n - SQL extraction methodology: The code extracts SQL queries from responses by splitting on markers and taking the first line (e.g., `r.split(\" [/INST] \")[-1].split(\"\\n\")[0]` for CodeLlama), assuming a single-line query format.\n\n Mismatched Details:\n - Scoring interpretation direction: The LaTeX description states it returns the \"highest-scoring plan\" (implying higher scores are better) while the code actually uses np.argmin(scores) (lower scores are better), creating a fundamental mismatch in score interpretation logic.\n", "Missing_details": [ "\n- Response processing and deduplication: The LaTeX description omits the critical step of normalizing SQL queries and removing duplicates from generated responses using list(set(...)), which ensures only distinct/valid candidates are considered during scoring.\n", "\n- Evaluation configuration handling: The code constructs the prompt for the generator in a dynamic way, supporting both zero-shot and few-shot prompting scenarios. In the zero-shot case (`retriever_gen is None`), it formats a template with the current example\u2019s database ID, schema, and question to create a standalone prompt. In the few-shot case, it uses a retriever to fetch similar examples, formats each with their database ID, schema, question, and SQL query, joins these demonstrations with single newlines, and appends the current example\u2019s prompt. This workflow enables the generator to leverage contextual examples for improved performance, a process not detailed in the LaTeX description\u2019s simple mention of \"sampling a few complete action sequences.\"\n", "\n- SQL extraction methodology: The code extracts SQL queries from responses by splitting on markers and taking the first line (e.g., `r.split(\" [/INST] \")[-1].split(\"\\n\")[0]` for CodeLlama), assuming a single-line query format.\n" ], "Mismatched_details": [ "\n- Scoring interpretation direction: The LaTeX description states it returns the \"highest-scoring plan\" (implying higher scores are better) while the code actually uses np.argmin(scores) (lower scores are better), creating a fundamental mismatch in score interpretation logic.\n" ] }, "Arguments": { "Arguments_list": [ { "name": "example", "string": "\n- example (dict): A dictionary containing details about the current example, including:\n - \"db_id\" (str): The database identifier.\n - \"schema\" (str): The schema of the database.\n - \"question\" (str): The user question.\n - \"sql\" (str, optional): The ground truth SQL (used for oracle evaluation).\n", "dependency": null }, { "name": "generator", "string": "\n- generator (generators.hf_generator.HFGenerator ,object): The generator used to produce SQL query completions based on prompts.\n - The HFGeneratordefined class is defined in generators/hf_generator.py\n", "dependency": "generators.hf_generator.HFGenerator" }, { "name": "evaluator", "string": "\n- evaluator (evaluators.oracle_evaluator.OracleEvaluator, object): The evaluator (discriminator) that scores the generated SQL queries.\n - The OracleEvaluator class is defined in evaluators/oracle_evaluator.py\n", "dependency": "evaluators.oracle_evaluator.OracleEvaluator" }, { "name": "retriever_gen", "string": "\n- retriever_gen (retrievers.bm25.BM25Retriever object or None): A retriever object for finding similar examples for 1-shot or few-shot prompting.\n If None, a zero-shot prompt is used.\n - The BM25Retriever class is defined in retrievers/bm25.py\n", "dependency": "retrievers.bm25.BM25Retriever" }, { "name": "retriever_eval", "string": "\n- retriever_eval (object or None): A retriever object for evaluation-specific few-shot examples.\n If None, default evaluation is used.\n", "dependency": null }, { "name": "args", "string": "\n- args (inference.args_definition, Namespace): Configuration arguments containing paths to generation and evaluation configs,\n as well as evaluator settings (e.g., evaluator name).\n - args is defined in the args_definition() function in inference.py\n", "dependency": null }, { "name": "log", "string": "\n- log (list): A log to store details of the re-ranking process for later analysis.\n", "dependency": null }, { "name": "The template for the initial prompt is defined in the utils.constants file:", "string": "\nThe template for the initial prompt is defined in the utils.constants file:\n - utils.constants.TEMPLATE: The template for the initial prompt, which includes the database schema and user question.\n - utils.constants.INST_CODELLAMA_GEN: The template for the codellama instruct generation model.\n", "dependency": null } ], "string": "\nInput Variables:\n - example (dict): A dictionary containing details about the current example, including:\n - \"db_id\" (str): The database identifier.\n - \"schema\" (str): The schema of the database.\n - \"question\" (str): The user question.\n - \"sql\" (str, optional): The ground truth SQL (used for oracle evaluation).\n - generator (generators.hf_generator.HFGenerator ,object): The generator used to produce SQL query completions based on prompts.\n - The HFGeneratordefined class is defined in generators/hf_generator.py\n - evaluator (evaluators.oracle_evaluator.OracleEvaluator, object): The evaluator (discriminator) that scores the generated SQL queries.\n - The OracleEvaluator class is defined in evaluators/oracle_evaluator.py\n - retriever_gen (retrievers.bm25.BM25Retriever object or None): A retriever object for finding similar examples for 1-shot or few-shot prompting. \n If None, a zero-shot prompt is used.\n - The BM25Retriever class is defined in retrievers/bm25.py\n - retriever_eval (object or None): A retriever object for evaluation-specific few-shot examples.\n If None, default evaluation is used.\n - args (inference.args_definition, Namespace): Configuration arguments containing paths to generation and evaluation configs,\n as well as evaluator settings (e.g., evaluator name). It is defined in the args_definition() function in inference.py\n - args.evaluation_config: The evaluation configuration for scoring the generated SQL queries.\n - args.generation_config: The generation configuration for generating SQL completions.\n - log (list): A log to store details of the re-ranking process for later analysis.\n The template for the initial prompt is defined in the utils.constants file:\n - utils.constants.TEMPLATE: The template for the initial prompt, which includes the database schema and user question.\n - utils.constants.INST_CODELLAMA_GEN: The template for the codellama instruct generation model.\n" }, "dependency": { "string": "\nDependencies: \n - Intra File Dependencies: \n - None\n \n - Cross File Dependencies: \n - utils.normalize_sql.normalize_sql\n \n", "intra_file": [], "cross_file": [ "utils.normalize_sql.normalize_sql" ] }, "external_APIs": { "string": "\nExternal APIs:\n - numpy.argmin\n - copy.deepcopy\n - json.load\n", "list": [ "numpy.argmin", "copy.deepcopy", "json.load" ] }, "Return": { "Return_list": [ { "name": "answer", "string": "- answer (str): The SQL query from the generated completions with the highest (best) score, normalized and cleaned.", "dependency": null } ], "Return_String": "\nOutput Variables:\n - answer (str): The SQL query from the generated completions with the highest (best) score, normalized and cleaned.\n" }, "ori_python_file": "from utils.constants import TEMPLATE, INST_CODELLAMA_GEN\nfrom utils.normalize_sql import normalize_sql\nfrom copy import deepcopy\nimport os, pickle\nimport numpy as np\nimport json\n\ndef rerank(example, generator, evaluator, retriever_gen, retriever_eval, args, log):\n config = json.load(open(args.generation_config))\n evaluation_config = json.load(open(args.evaluation_config))\n if retriever_gen is None:\n model_inp = TEMPLATE.format(example[\"db_id\"], example[\"schema\"], example[\"question\"])\n prompt = model_inp\n else:\n demos = retriever_gen.retrieve(example[\"question\"])\n model_inp = \"\\n\".join([TEMPLATE.format(ex[\"db_id\"], ex[\"schema\"], ex[\"question\"]) + ex[\"sql\"] for ex in demos])\n prompt = model_inp + \"\\n\" + TEMPLATE.format(example[\"db_id\"], example[\"schema\"], example[\"question\"])\n if generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n prompt = INST_CODELLAMA_GEN.format(prompt) + \" SELECT\"\n responses = generator.generate(prompt, config)\n if generator.base_model_name.startswith(\"codellama\") and \"Instruct\" in generator.base_model_name:\n sql_completions = list(set([normalize_sql(r.split(\" [/INST] \")[-1].split(\"\\n\")[0]) for r in responses if r.split(\" [/INST] \")[-1].split(\"\\n\")[0] != \"\"]))\n else:\n sql_completions = list(set([normalize_sql(r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0]) for r in responses if r.split(\"-- SQL:\\n\")[-1].split(\"\\n\")[0] != \"\"]))\n if args.evaluator_name == \"oracle\":\n scores = evaluator.score(example[\"db_id\"], example[\"question\"], sql_completions, example[\"sql\"])\n elif retriever_eval is None:\n scores = evaluator.score(example[\"db_id\"], example[\"question\"], sql_completions, evaluation_config)\n else:\n scores = evaluator.score_fewshot(example[\"db_id\"], example[\"question\"], sql_completions, retriever_eval, evaluation_config)\n example_log = deepcopy(example)\n example_log[\"top_n\"] = sql_completions\n example_log[\"scores\"] = scores\n log.append(example_log)\n answer = sql_completions[np.argmin(scores)].replace(\"\\n\", \" \")\n return answer" } ] }, { "paper_id": 5, "paper_details": { "title": "Functional Overlap Reranking for Neural Code Generation", "url": "https://arxiv.org/abs/2311.03366" }, "repo_original_url": "https://github.com/fsoft-ai4code/srank-coderanker", "project_path": "Benchmark/5-Functional/SRank-CodeRanker-main", "enviorment_name": "SRank", "file_organization": "\nSRank-CodeRanker-main/\n execution/\n _execution.py\n execution.py\n results/\n humaneval/\n wizardcoder/\n T0.8_N100/\n ground_truth_exec_result.pkl\n model_generated_test_cases.pkl\n test_inputs_exec_result.pkl\n run_greedy.py\n run.py\n utils.py\n generation/\n configs.py\n gen_code/\n post_process.py\n postprocess_wizardcoder_humaneval.py\n postprocess_wizardcoder_mbpp.py\n postprocess_wizardcoder.py\n preds/\n humaneval/\n starcoder/\n T0.8_N100/\n wizardcoder/\n postprocessed_T0.8_N100.jsonl\n T0.8_N100/\n 0.jsonl\n ...\n prompt.py\n sh/\n postprocess_greedy.sh\n postprocess_greedy_wizardcoder.sh\n postprocess.sh\n run_greedy.sh\n run.sh\n wizardcoder34B_greedy.sh\n wizardcoder34B.sh\n starcoder.py\n wizardcoder34B.py\n wizardcoder.py\n gen_test/\n post_process.py\n preds/\n humaneval/\n wizardcoder/\n postprocessed_T0.8_N100.jsonl\n T0.8_N100/\n 0.jsonl\n ...\n prompt.py\n sh/\n postprocess.sh\n run.sh\n wizardcoder34B.sh\n starcoder.py\n wizardcoder34B.py\n wizardcoder.py\n model_utils.py\n human-eval-master/\n data/\n example_problem.jsonl\n example_samples.jsonl\n HumanEval.jsonl.gz\n human_eval/\n data.py\n evaluate_functional_correctness.py\n evaluation.py\n execution.py\n __init__.py\n LICENSE\n README.md\n requirements.txt\n setup.py\n README.md\n requirements.txt\n reranking/\n codet_evaluation.py\n evaluator.py\n functionality_processing.py\n pyminifier_canonicalize.py\n run.py\n sh/\n run.sh\n utils.py\n src/\n", "latex_code_path": "Benchmark/5-Functional/arXiv-2311.03366v4", "task_details": [ { "task_id": 0, "indent": 1, "latex_code": "\n\\subsection{Clustering Solutions by Execution Outputs}\n\nWe first execute each solution $s_i \\in \\mathbf{S}$ on the test inputs $\\mathbf{Z}$ to produce execution outputs $\\mathbf{O}$. Solutions that exhibit identical execution outputs are grouped into the same cluster:\n\\[F(s_i) = F(s_j) \\iff \\mathbf{O}_{s_i} = \\mathbf{O}_{s_j}.\\]\nHere, $F$ represents the clustering function that maps a solution $s$ to a cluster identifier $C_k$. The above equation indicates that two solutions $s_i$ and $s_j$ are assigned to the same cluster if and only if their output sets $\\mathbf{O}_{s_i}$ and $\\mathbf{O}_{s_j}$ are exactly equal.\n", "script": "\npython reranking/run.py --method attention --ground_truth_exec_path execution/results/humaneval/wizardcoder/T0.8_N100/ground_truth_exec_result.pkl --test_inputs_exec_path execution/results/humaneval/wizardcoder/T0.8_N100/test_inputs_exec_result.pkl --model_generated_test_path execution/results/humaneval/wizardcoder/T0.8_N100/model_generated_test_cases.pkl --dataset_name HumanEval --logprob_path None --reverse_logprob_path None --verbose\n", "completion_path": "./reranking/functionality_processing.py", "namespace": "reranking.functionality_processing.cluster_solutions_by_execution_outputs", "type": "function", "signature_position": [ 52, 52 ], "body_position": [ 53, 82 ], "ReferenceCode_With_Comments": "\nexist_completions = set()\noutput_list_counter = []\ncount_invalid = 0\npassed_results_of_invalid = []\n\n# ----------------------------------------------------------------------------\n# Snippet 1: Iterates over each solution s_i to verify its validity and collect its execution outputs. While the LaTeX snippet focuses on solution outputs, this portion also filters out invalid solutions.\n# ----------------------------------------------------------------------------\n# [Begin Snippet 1]\nfor i, item in enumerate(task_items):\n item[\"validity\"] = True \n if not check_validity(item):\n item[\"validity\"] = False\n count_invalid += 1\n passed_results_of_invalid.append(item[\"passed\"])\n continue \n# [End Snippet 1]\n\n # ----------------------------------------------------------------------------\n # Snippet 2: Extracts the key components (completion, outputs, pass status) for valid solutions and compares them against existing clusters to enforce F(s_i) = F(s_j) iff O_{s_i} = O_{s_j} from the LaTeX snippet. If identical outputs exist, the solution joins that cluster; otherwise, a new cluster is formed.\n # ----------------------------------------------------------------------------\n # [Begin Snippet 2]\n completion = item[\"completion\"]\n outputs = item[\"outputs\"][:num_limit_test_cases]\n passed = item[\"passed\"]\n\n output_list_existed = False\n for i, counter in enumerate(output_list_counter):\n try:\n if all(output[0] == cluster_output[0] and output[1] == cluster_output[1] \n for output, cluster_output in zip(outputs, counter[0])):\n output_list_existed = True\n if not completion in exist_completions:\n counter[1] += 1\n counter[2].append(passed)\n break \n except TypeError:\n continue\n # [End Snippet 2]\n\n # ----------------------------------------------------------------------------\n # Snippet 3: If a solution\u2019s outputs do not match any existing cluster, create a new entry. The function then collects completions to ensure unique solutions are counted correctly. This finalizes the grouping step, ensuring that all identical outputs form a single cluster.\n # ----------------------------------------------------------------------------\n # [Begin Snippet 3]\n if not output_list_existed:\n output_list_counter.append([outputs, 1, [passed]])\n\n exist_completions.add(completion)\nreturn output_list_counter, count_invalid, passed_results_of_invalid\n# [End Snippet 3]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The LaTeX description omits the step of checking the validity of each solution before clustering. In the reference Python code, each solution's validity is explicitly checked first, and invalid solutions are tracked separately. This preprocessing step ensures that only valid solutions contribute to clusters based on execution outputs.\n - Tracking the number of discarded solutions with the variable 'count_invalid'.\n - The LaTeX description does not mention deduplication of identical code completions. In contrast, the Python implementation maintains a set to avoid counting the same solution implementation multiple times within a cluster. Without this detail, clusters could incorrectly inflate their counts if identical completions repeatedly occur.\n - The LaTeX description defines clustering purely by equality of execution outputs (`\\mathbf{O}_{s_i} = \\mathbf{O}_{s_j}`), but does not specify how equality should be verified. The reference code explicitly compares outputs pairwise and element-wise, preserving type and order.\n\n - Mismatched Details:\n - None\n", "Missing_details": [ "\n- The LaTeX description omits the step of checking the validity of each solution before clustering. In the reference Python code, each solution's validity is explicitly checked first, and invalid solutions are tracked separately. This preprocessing step ensures that only valid solutions contribute to clusters based on execution outputs.\n", "\n- Tracking the number of discarded solutions with the variable 'count_invalid'.\n", "\n- The LaTeX description does not mention deduplication of identical code completions. In contrast, the Python implementation maintains a set to avoid counting the same solution implementation multiple times within a cluster. Without this detail, clusters could incorrectly inflate their counts if identical completions repeatedly occur.\n", "\n- The LaTeX description defines clustering purely by equality of execution outputs (`\\mathbf{O}_{s_i} = \\mathbf{O}_{s_j}`), but does not specify how equality should be verified. The reference code explicitly compares outputs pairwise and element-wise, preserving type and order.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - task_items (List[Dict]). Each dictionary represents a single solution to a specific task. \n - The dictionary contains:\n - \"task_id\": A string identifier for the task (e.g., \"HumanEval/0\").\n - \"completion\": A string containing the generated code solution.\n - \"all_code\": A string containing the code and possibly additional context or instructions.\n - \"prompt\": A string containing the original prompt or problem description.\n - \"entry_point\": A string indicating the function name to be tested within the code solution.\n - \"test\": A string containing test cases to be executed against the code solution.\n - \"solution_id\": An integer identifier for the solution.\n - \"result\": A string indicating the overall result of executing the test cases (e.g., \"passed\", \"failed\").\n - \"passed\": A boolean indicating whether all test cases passed.\n - \"test_inputs\": A list of strings, where each string is an individual test case input.\n - \"outputs\": A list of lists, It represents the execution results for a specific code solution across multiple test cases. It contains a list of pairs where each pair follows the format [Boolean, Value]:\n - The first element (True or False) indicates whether the execution completed successfully without errors.\n - The second element (alternating between True and False) represents the actual output of the code for the corresponding test input.\n - \"test_inputs_passed\": A boolean indicating whether the solution passed all the provided test inputs.\n - num_limit_test_cases (int): An integer specifying the maximum number of test cases to be considered when comparing solution outputs. This limits the comparison to the first 'num_limit_test_cases' outputs.\n", "Arguments_list": [ { "name": "task_items", "string": "\n- task_items (List[Dict]). Each dictionary represents a single solution to a specific task. \n - The dictionary contains:\n - \"task_id\": A string identifier for the task (e.g., \"HumanEval/0\").\n - \"completion\": A string containing the generated code solution.\n - \"all_code\": A string containing the code and possibly additional context or instructions.\n - \"prompt\": A string containing the original prompt or problem description.\n - \"entry_point\": A string indicating the function name to be tested within the code solution.\n - \"test\": A string containing test cases to be executed against the code solution.\n - \"solution_id\": An integer identifier for the solution.\n - \"result\": A string indicating the overall result of executing the test cases (e.g., \"passed\", \"failed\").\n - \"passed\": A boolean indicating whether all test cases passed.\n - \"test_inputs\": A list of strings, where each string is an individual test case input.\n - \"outputs\": A list of lists, where each inner list contains the output of a single test case execution on the code solution. Each output is itself a list, possibly representing multiple return values or printed outputs.\n - \"test_inputs_passed\": A boolean indicating whether the solution passed all the provided test inputs.\n", "dependency": null }, { "name": "num_limit_test_cases", "string": "- num_limit_test_cases (int): An integer specifying the maximum number of test cases to be considered when comparing solution outputs. This limits the comparison to the first 'num_limit_test_cases' outputs.", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File dependency:\n - None\n\n Cross-File dependency: \n - utils.check_validity\n", "intra_file": [], "cross_file": [ "utils.check_validity" ] }, "external_APIs": { "string": "\nExternal APIs: \n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - output_list_counter (List[List[List, int, List]]): A list of lists. Each inner list represents a cluster of solutions that share the same execution outputs.\n - Each inner list has the format: `[outputs, count, passed_results]`, where:\n - outputs: A list of lists. Each inner list represents the outputs generated by executing a solution against a sequence of test cases. \n Example: `[[...], [...], [...], ..., [...]]` where each `[...]` is a list containing the output of a single test case. Each `[...]` might contain multiple values if a test case produces multiple outputs. In this specific example, each inner list `[...]` may contain one or more values, and each item within `output_list_counter` may have up to 19 inner lists in the `outputs` because of the default value of the `num_limit_test_cases` variable.\n - count: An integer. This represents the number of solutions that belong to this cluster (i.e., the number of solutions that produced these identical outputs).\n Example: `25` indicates that 25 solutions generated the exact same sequence of outputs.\n - passed_results: A list of boolean values. Each boolean value corresponds to the `passed` status of a solution in the cluster. `True` indicates the solution passed the test cases, and `False` indicates it failed.\n Example: `[True, True, True, ..., True]` where each `True` indicates that a corresponding solution in the cluster passed all its test cases.\n - count_invalid (int): An integer representing the number of solutions that were deemed invalid, meaning they could not be processed or executed correctly.\n - passed_results_of_invalid (List): A list containing the ground truth results (\"passed\" values) for each invalid solution.\n", "Return_list": [ { "name": "output_list_counter", "string": "\n- output_list_counter (List[List[List, int, List]]): A list of lists. Each inner list represents a cluster of solutions that share the same execution outputs.\n - Each inner list has the format: `[outputs, count, passed_results]`, where: \n - outputs: A list of lists. Each inner list represents the outputs generated by executing a solution against a sequence of test cases.\n Example: `[[...], [...], [...], ..., [...]]` where each `[...]` is a list containing the output of a single test case. Each `[...]` might contain multiple values if a test case produces multiple outputs. In this specific example, each inner list `[...]` may contain one or more values, and each item within `output_list_counter` may have up to 19 inner lists in the `outputs` because of the default value of the `num_limit_test_cases` variable.\n - count: An integer. This represents the number of solutions that belong to this cluster (i.e., the number of solutions that produced these identical outputs).\n Example: `25` indicates that 25 solutions generated the exact same sequence of outputs.\n - passed_results: A list of boolean values. Each boolean value corresponds to the `passed` status of a solution in the cluster. `True` indicates the solution passed the test cases, and `False` indicates it failed.\n Example: `[True, True, True, ..., True]` where each `True` indicates that a corresponding solution in the cluster passed all its test cases.\n" }, { "name": "count_invalid", "string": "- count_invalid (int): An integer representing the number of solutions that were deemed invalid, meaning they could not be processed or executed correctly.", "dependency": null }, { "name": "passed_results_of_invalid", "string": "- passed_results_of_invalid (List): A list containing the ground truth results ('passed' values) for each invalid solution.", "dependency": null } ] }, "ori_python_file": "import numpy as np\nfrom utils import check_validity\nimport pickle\nNUM_LIMIT_TEST_CASES = int(1e6)\nimport os\n\ndef calculate_pair_overlap(outputs, other_outputs):\n assert len(outputs) == len(other_outputs), f\"{len(outputs) = }, {len(other_outputs) = }, \\n\\n{outputs = }\\n\\n\\n{other_outputs = }\"\n if len(outputs) == 0:\n return 0\n overlap = 0\n num_inputs = len(outputs)\n for output, other_output in zip(outputs, other_outputs):\n try:\n overlap += output[0] and other_output[0] and output[1] == other_output[1]\n except TypeError:\n print(f\"Cannot compare output and other_output\\n\\n{output[1] = }\\n\\n{other_output[1] = }\",)\n continue\n overlap /= num_inputs\n return overlap\n\ndef calculate_cluster_pass_rate(outputs, model_generated_outputs):\n assert len(outputs) == len(model_generated_outputs)\n if len(outputs) == 0:\n return 0\n num_inputs = 0\n pass_rate = 0\n for output, generated_outputs in zip(outputs, model_generated_outputs):\n for generated_output in generated_outputs:\n num_inputs += 1\n try:\n pass_rate += output[0] and output[1] == generated_output\n except TypeError:\n print(f\"Cannot compare output to virtual_output\\n\\n{output[1] = }\\n\\n{generated_output = }\")\n pass_rate /= num_inputs\n return pass_rate\n\ndef calculate_attention_score_matrix(cluster_execution_outputs):\n attention_score_matrix = []\n for i, outputs in enumerate(cluster_execution_outputs):\n pair_overlaps = []\n for j, other_outputs in enumerate(cluster_execution_outputs):\n if i == j:\n pair_overlaps.append(1)\n else:\n pair_overlap = calculate_pair_overlap(outputs, other_outputs)\n pair_overlaps.append(pair_overlap)\n attention_score_matrix.append(pair_overlaps)\n attention_score_matrix = np.array(attention_score_matrix)\n return attention_score_matrix\n\ndef cluster_solutions_by_execution_outputs(task_items, num_limit_test_cases=NUM_LIMIT_TEST_CASES):\n exist_completions = set()\n output_list_counter = []\n count_invalid = 0\n passed_results_of_invalid = []\n for i, item in enumerate(task_items):\n item[\"validity\"] = True\n if not check_validity(item):\n item[\"validity\"] = False\n count_invalid += 1\n passed_results_of_invalid.append(item[\"passed\"])\n continue\n completion = item[\"completion\"]\n outputs = item[\"outputs\"][:num_limit_test_cases]\n passed = item[\"passed\"]\n output_list_existed = False\n for i, counter in enumerate(output_list_counter):\n try:\n if all(output[0] == cluster_output[0] and output[1] == cluster_output[1]\n for output, cluster_output in zip(outputs, counter[0])):\n output_list_existed = True\n if not completion in exist_completions:\n counter[1] += 1\n counter[2].append(passed)\n break\n except TypeError:\n continue\n if not output_list_existed:\n output_list_counter.append([outputs, 1, [passed]])\n exist_completions.add(completion)\n return output_list_counter, count_invalid, passed_results_of_invalid\n\ndef process_cluster_attention_one_task(inputs, num_limit_test_cases=NUM_LIMIT_TEST_CASES, TestCode=False):\n task_id, task_items, model_generated_input_output_dict = inputs\n output_list_counter, count_invalid, passed_results_of_invalid = cluster_solutions_by_execution_outputs(task_items, num_limit_test_cases)\n cluster_execution_outputs = [counter[0] for counter in output_list_counter]\n attention_score_matrix = calculate_attention_score_matrix(cluster_execution_outputs)\n test_inputs = task_items[0][\"test_inputs\"][:num_limit_test_cases]\n intersection_inputs, intersection_input_indices = [], []\n for i, test_input in enumerate(test_inputs):\n if test_input in model_generated_input_output_dict:\n intersection_inputs.append(test_input)\n intersection_input_indices.append(i)\n model_generated_outputs = [model_generated_input_output_dict[test_input] for test_input in intersection_inputs]\n pass_rates = []\n for outputs in cluster_execution_outputs:\n _outputs = [outputs[i] for i in intersection_input_indices]\n pass_rate = calculate_cluster_pass_rate(_outputs, model_generated_outputs)\n pass_rates.append(pass_rate)\n num_solutions = [counter[1] for counter in output_list_counter]\n passed_results = [counter[2] for counter in output_list_counter]\n if count_invalid > 0:\n if len(attention_score_matrix.shape) == 2:\n n = attention_score_matrix.shape[0]\n new_matrix = np.zeros((n + 1, n + 1))\n new_matrix[:n,:n] = attention_score_matrix\n attention_score_matrix = new_matrix\n else:\n attention_score_matrix = np.array([0])\n num_solutions.append(0)\n pass_rates.append(0)\n passed_results.append(passed_results_of_invalid)\n if sum(num_solutions) == 0:\n correctness_features = (np.array(num_solutions), np.array(pass_rates))\n else:\n correctness_features = (np.array(num_solutions) / sum(num_solutions), np.array(pass_rates))\n return task_id, attention_score_matrix, correctness_features, passed_results" }, { "task_id": 1, "indent": 1, "completion_path": "./reranking/functionality_processing.py", "latex_code": "\n\\subsection{Computing Interaction Matrix}\nAfter obtaining execution outputs $o_{ij}$ for each cluster $C_i$ on test input $z_j$, we define an interaction matrix $\\mathbf{I} \\in \\mathbb{R}^{K \\times K}$ to quantify functional overlap:\n\\begin{equation} \\label{eq:interaction-matrix}\n\tI_{ij} = \\frac{1}{M}\\sum_{k=1}^{M}\\delta(o_{ik} = o_{jk}),\n\\end{equation}\nwhere $o_{ik}$ and $o_{jk}$ refer directly to the execution outputs of clusters $C_i$ and $C_j$, respectively, on the $k^{\\text{th}}$ test input. $\\delta$ is the indicator function that returns 1 if the condition inside is true and 0 otherwise.\n", "namespace": "reranking.functionality_processing.calculate_attention_score_matrix", "type": "function", "signature_position": [ 38, 38 ], "body_position": [ 39, 50 ], "script": "\npython reranking/run.py --method attention --ground_truth_exec_path execution/results/humaneval/wizardcoder/T0.8_N100/ground_truth_exec_result.pkl --test_inputs_exec_path execution/results/humaneval/wizardcoder/T0.8_N100/test_inputs_exec_result.pkl --model_generated_test_path execution/results/humaneval/wizardcoder/T0.8_N100/model_generated_test_cases.pkl --dataset_name HumanEval --logprob_path None --reverse_logprob_path None --verbose\n", "ReferenceCode_With_Comments": "\nattention_score_matrix = []\n\nfor i, outputs in enumerate(cluster_execution_outputs):\n pair_overlaps = []\n for j, other_outputs in enumerate(cluster_execution_outputs):\n\n\n # ----------------------------------------------------------------------------\n # Snippet 1: The diagonal entries (\\(i = j\\)) are set to 1, indicating each cluster fully overlaps with itself, consistent with the notion that \\(\\mathbf{I}_{ii}\\) should be the maximum overlap (i.e., 100%).\n # ----------------------------------------------------------------------------\n # [Begin Snippet 1]\n if i == j:\n pair_overlaps.append(1)\n # [End Snippet 1]\n else:\n # ----------------------------------------------------------------------------\n # Snippet 2: If diagonal entries i \u2260 j: Then computes the similarity between clusters \\(C_i\\) and \\(C_j\\) based on their execution outputs. This corresponds to \\(\\delta(o_{ik} = o_{jk})\\), where the indicator function checks whether two clusters produce identical outputs for each test input.\n # ----------------------------------------------------------------------------\n # [Begin Snippet 2]\n pair_overlap = calculate_pair_overlap(outputs, other_outputs) \n pair_overlaps.append(pair_overlap)\n # [Begin Snippet 2]\n \n attention_score_matrix.append(pair_overlaps)\n\n# ----------------------------------------------------------------------------\n# Snippet 3: Finalizing \\(\\mathbf{I}\\) as a NumPy array and returning it as \n# the interaction matrix. \n# ----------------------------------------------------------------------------\n# [Begin Snippet 3]\nattention_score_matrix = np.array(attention_score_matrix)\nreturn attention_score_matrix\n# [End Snippet 3]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX does not mention that diagonal entries of the interaction matrix (`I_{ii}`) should explicitly be set to 1 without computation. The code should skips calculation for `i == j` and directly assigns `1`, ensuring self-overlap is maximal regardless of test inputs. This workflow is absent in the LaTeX description.\n\n Mismatched Details:\n - None\n", "Missing_details": [ "\n- The LaTeX does not mention that diagonal entries of the interaction matrix (`I_{ii}`) should explicitly be set to 1 without computation. The code should skips calculation for `i == j` and directly assigns `1`, ensuring self-overlap is maximal regardless of test inputs. This workflow is absent in the LaTeX description.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - cluster_execution_outputs (List[List[List]]): A list where each inner list represents the execution outputs of a specific cluster on a set of test inputs.\n - Outermost List: Represents the different clusters. Each element of this list corresponds to a single cluster.\n - Second-Level List: Represents the test inputs for a given cluster. Each element of this list represents the execution results of a cluster on a specific test input.\n - Innermost List (or values): Represents the execution output of a cluster on a single test input. The structure of this element appears to be varied:\n - the first element is a boolean value indicating whether the test input passed.\n - the second element is the actual output of the cluster on the test input.\n", "Arguments_list": [ { "name": "cluster_execution_outputs", "string": "\n- cluster_execution_outputs (List[List[List]]): A list where each inner list represents the execution outputs of a specific cluster on a set of test inputs.\n - Outermost List: Represents the different clusters. Each element of this list corresponds to a single cluster.\n - Second-Level List: Represents the test inputs for a given cluster. Each element of this list represents the execution results of a cluster on a specific test input.\n - Innermost List (or values): Represents the execution output of a cluster on a single test input. The structure of this element appears to be varied:\n - the first element is a boolean value indicating whether the test input passed.\n - the second element is the actual output of the cluster on the test input.\n" } ] }, "dependency": { "string": "\nDependencies:\n Intra-File dependency:\n - calculate_pair_overlap\n \n Cross-File dependency: \n - None\n", "intra_file": [ "calculate_pair_overlap" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - numpy.array\n", "list": [ "numpy.array" ] }, "Return": { "Return_String": "\nOutput Variables:\n - attention_score_matrix (np.ndarray, shape=[number of clusters, number of clusters]): A NumPy array representing the interaction between clusters.\n - Each element (i, j) in the matrix represents the interaction score between cluster i and cluster j.\n - The values in the matrix range from 0 to 1, where 1 signifies perfect overlap and 0 represents no overlap.\n", "Return_list": [ { "name": "attention_score_matrix", "string": "\n- attention_score_matrix (np.ndarray, shape=[number of clusters, number of clusters]): A NumPy array representing the interaction between clusters.\n - Each element (i, j) in the matrix represents the interaction score between cluster i and cluster j.\n - The values in the matrix range from 0 to 1, where 1 signifies perfect overlap and 0 represents no overlap.\n" } ] }, "ori_python_file": "import numpy as np\nfrom utils import check_validity\nimport pickle\nNUM_LIMIT_TEST_CASES = int(1e6)\nimport os\n\ndef calculate_pair_overlap(outputs, other_outputs):\n assert len(outputs) == len(other_outputs), f\"{len(outputs) = }, {len(other_outputs) = }, \\n\\n{outputs = }\\n\\n\\n{other_outputs = }\"\n if len(outputs) == 0:\n return 0\n overlap = 0\n num_inputs = len(outputs)\n for output, other_output in zip(outputs, other_outputs):\n try:\n overlap += output[0] and other_output[0] and output[1] == other_output[1]\n except TypeError:\n print(f\"Cannot compare output and other_output\\n\\n{output[1] = }\\n\\n{other_output[1] = }\",)\n continue\n overlap /= num_inputs\n return overlap\n\ndef calculate_cluster_pass_rate(outputs, model_generated_outputs):\n assert len(outputs) == len(model_generated_outputs)\n if len(outputs) == 0:\n return 0\n num_inputs = 0\n pass_rate = 0\n for output, generated_outputs in zip(outputs, model_generated_outputs):\n for generated_output in generated_outputs:\n num_inputs += 1\n try:\n pass_rate += output[0] and output[1] == generated_output\n except TypeError:\n print(f\"Cannot compare output to virtual_output\\n\\n{output[1] = }\\n\\n{generated_output = }\")\n pass_rate /= num_inputs\n return pass_rate\n\ndef calculate_attention_score_matrix(cluster_execution_outputs):\n attention_score_matrix = []\n for i, outputs in enumerate(cluster_execution_outputs):\n pair_overlaps = []\n for j, other_outputs in enumerate(cluster_execution_outputs):\n if i == j:\n pair_overlaps.append(1)\n else:\n pair_overlap = calculate_pair_overlap(outputs, other_outputs)\n pair_overlaps.append(pair_overlap)\n attention_score_matrix.append(pair_overlaps)\n attention_score_matrix = np.array(attention_score_matrix)\n return attention_score_matrix\n\ndef cluster_solutions_by_execution_outputs(task_items, num_limit_test_cases=NUM_LIMIT_TEST_CASES):\n exist_completions = set()\n output_list_counter = []\n count_invalid = 0\n passed_results_of_invalid = []\n for i, item in enumerate(task_items):\n item[\"validity\"] = True\n if not check_validity(item):\n item[\"validity\"] = False\n count_invalid += 1\n passed_results_of_invalid.append(item[\"passed\"])\n continue\n completion = item[\"completion\"]\n outputs = item[\"outputs\"][:num_limit_test_cases]\n passed = item[\"passed\"]\n output_list_existed = False\n for i, counter in enumerate(output_list_counter):\n try:\n if all(output[0] == cluster_output[0] and output[1] == cluster_output[1]\n for output, cluster_output in zip(outputs, counter[0])):\n output_list_existed = True\n if not completion in exist_completions:\n counter[1] += 1\n counter[2].append(passed)\n break\n except TypeError:\n continue\n if not output_list_existed:\n output_list_counter.append([outputs, 1, [passed]])\n exist_completions.add(completion)\n return output_list_counter, count_invalid, passed_results_of_invalid\n\ndef process_cluster_attention_one_task(inputs, num_limit_test_cases=NUM_LIMIT_TEST_CASES, TestCode=False):\n task_id, task_items, model_generated_input_output_dict = inputs\n output_list_counter, count_invalid, passed_results_of_invalid = cluster_solutions_by_execution_outputs(task_items, num_limit_test_cases)\n cluster_execution_outputs = [counter[0] for counter in output_list_counter]\n attention_score_matrix = calculate_attention_score_matrix(cluster_execution_outputs)\n test_inputs = task_items[0][\"test_inputs\"][:num_limit_test_cases]\n intersection_inputs, intersection_input_indices = [], []\n for i, test_input in enumerate(test_inputs):\n if test_input in model_generated_input_output_dict:\n intersection_inputs.append(test_input)\n intersection_input_indices.append(i)\n model_generated_outputs = [model_generated_input_output_dict[test_input] for test_input in intersection_inputs]\n pass_rates = []\n for outputs in cluster_execution_outputs:\n _outputs = [outputs[i] for i in intersection_input_indices]\n pass_rate = calculate_cluster_pass_rate(_outputs, model_generated_outputs)\n pass_rates.append(pass_rate)\n num_solutions = [counter[1] for counter in output_list_counter]\n passed_results = [counter[2] for counter in output_list_counter]\n if count_invalid > 0:\n if len(attention_score_matrix.shape) == 2:\n n = attention_score_matrix.shape[0]\n new_matrix = np.zeros((n + 1, n + 1))\n new_matrix[:n,:n] = attention_score_matrix\n attention_score_matrix = new_matrix\n else:\n attention_score_matrix = np.array([0])\n num_solutions.append(0)\n pass_rates.append(0)\n passed_results.append(passed_results_of_invalid)\n if sum(num_solutions) == 0:\n correctness_features = (np.array(num_solutions), np.array(pass_rates))\n else:\n correctness_features = (np.array(num_solutions) / sum(num_solutions), np.array(pass_rates))\n return task_id, attention_score_matrix, correctness_features, passed_results" }, { "task_id": 2, "indent": 2, "completion_path": "./reranking/evaluator.py", "latex_code": "\n\\subsection{Computing Final Ranking Scores}\nIn addition to modeling inter-cluster interactions via $\\mathbf{I}$, we also consider an extra validation dimension $\\mathbf{V} \\in \\mathbb{R}^{K\\times 1}$ containing cluster features. For instance, $V_i$ could represent the number of solutions in cluster $C_i$ (abbreviated as cluster sizes) or the number of test cases that the solutions in cluster $C_i$ passed (abbreviated as pass rates), providing a notion of cluster confidence. The final ranking vector $\\mathbf{R} \\in \\mathbb{R}^{K\\times 1}$ can then be computed as $\\mathbf{R} = \\mathbf{I} \\cdot \\mathbf{V}$. Here, $R_i$ aggregates information about both the inter-cluster interactions of $C_i$ (via $\\mathbf{I}$) and its cluster features (via $\\mathbf{V}$). Clusters with higher ranking scores in $\\mathbf{R}$ are those with significant functional overlap to other clusters and high validity according to $\\mathbf{V}$. By considering inter-cluster relationships and functional similarity in a principled manner, we believe our ranking approach can effectively identify the most promising solutions. We validate our method through extensive experiments in the following sections.\n", "script": "\npython reranking/run.py --method attention --ground_truth_exec_path execution/results/humaneval/wizardcoder/T0.8_N100/ground_truth_exec_result.pkl --test_inputs_exec_path execution/results/humaneval/wizardcoder/T0.8_N100/test_inputs_exec_result.pkl --model_generated_test_path execution/results/humaneval/wizardcoder/T0.8_N100/model_generated_test_cases.pkl --dataset_name HumanEval --logprob_path None --reverse_logprob_path None --verbose\n", "namespace": "reranking.evaluator.AttentionRankingEvaluator.get_sorted_solutions", "type": "method", "signature_position": [ 133, 133 ], "body_position": [ 134, 153 ], "ReferenceCode_With_Comments": "\nnorm_num_solutions_weight, pass_rate_weight = weight_combination\nranked_results = defaultdict(list)\n\nfor task_id, (attention_score_matrix, correctness_features, passed_results) in results_by_task_id.items():\n \n # -------------------------------------------------------------------\n # Snippet 1: Construct the validation vector V by combining the normalized number of solutions and pass rates for each cluster with the given weight parameters. \n # -------------------------------------------------------------------\n # [Begin Snippet 1]\n V = np.array([\n (norm_num_solutions**norm_num_solutions_weight) * (pass_rate**pass_rate_weight)\n for norm_num_solutions, pass_rate in zip(*correctness_features)\n ])\n # [End Snippet 1]\n\n # -------------------------------------------------------------------\n # Snippet 2: If attention is used, compute R = I * V. Otherwise, the validation vector V alone is used (equivalent to skipping the I multiplication).\n # -------------------------------------------------------------------\n # [Begin Snippet 2]\n if with_attention:\n ranking_scores = attention_score_matrix @ V\n else:\n ranking_scores = V\n \n ranking_scores = ranking_scores.tolist()\n if isinstance(ranking_scores, int):\n ranking_scores = [ranking_scores]\n # [End Snippet 2]\n\n # -------------------------------------------------------------------\n # Snippet 3: Pair each cluster\u2019s pass/fail results with the corresponding ranking score, then sort these results by descending scores. This final step yields the sorted solutions, reflecting how higher scoring clusters are prioritized, as per R in the LaTeX.\n # -------------------------------------------------------------------\n # [Begin Snippet 3]\n passed_and_scores = [\n (passed_result, score)\n for passed_result, score in zip(passed_results, ranking_scores)\n ]\n ranked_results[task_id] = sorted(passed_and_scores, key=lambda x: x[1], reverse=True)\n # [End Snippet 3]\n\n# -----------------------------------------------------------------------\n# Snippet 4: Return the dictionary of ranked results for each task, now ordered by the final ranking score.\n# -----------------------------------------------------------------------\n# [Begin Snippet 4]\nreturn ranked_results\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The function applies weighted combination of cluster features that is used to construct the validation vector V:\n It implements V_i = (size^\u03b1)*(pass_rate^\u03b2) where \u03b1=norm_num_solutions_weight, \u03b2=pass_rate_weight. This extends the LaTeX specification by combining features multiplicatively rather than selecting single features (cluster sizes OR pass rates). Default (1,1) weights create simple feature product matching paper's conceptual description.\n - The code should preserves cluster groupings when sorting (ranking clusters first, then outputting all solutions in each cluster)\n \n - Mismatched Details:\n - None.\n", "Missing_details": [ "\n- The function applies weighted combination of cluster features that is used to construct the validation vector V:\n It implements V_i = (size^\u03b1)*(pass_rate^\u03b2) where \u03b1=norm_num_solutions_weight, \u03b2=pass_rate_weight. This extends the LaTeX specification by combining features multiplicatively rather than selecting single features (cluster sizes OR pass rates). Default (1,1) weights create simple feature product matching paper's conceptual description.\n", "\n- The code should preserves cluster groupings when sorting (ranking clusters first, then outputting all solutions in each cluster)\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - results_by_task_id: A dictionary where keys are task IDs and values are tuples containing the attention score matrix, correctness features, and passed results for each task.\n - attention_score_matrix (numpy.Array, shape=(n_clusters, n_clusters) : A NumPy array representing the interaction scores between clusters.\n - correctness_features (Tuple[numpy.Array, numpy.Array]): A tuple containing two NumPy arrays representing the normalized number of solutions and pass rates for each cluster\uff1a\n - First Array (Normalized Number of Solutions): These values likely represent the proportion of solutions within each cluster relative to the total number of solutions across all clusters for the task.\n - Second Array (Pass Rates): These values indicate the proportion of test cases passed by the solutions in each cluster.\n - passed_results (List[List]): A list of lists containing the results of the test cases for each solution within each cluster.\n - Outer list: Contains the results for each cluster.\n - Inner list: Each corresponds to a cluster and contains boolean values indicating whether each solution within that cluster passed a set of tests.\n - weight_combination:\n - A tuple containing two floating-point values representing the weights used in the calculation of the validation vector V. These weights determine the relative importance of the normalized number of solutions and the pass rate in the final ranking.\n - First Element (norm_num_solutions_weight): A floating-point number representing the weight assigned to the normalized number of solutions.\n - Second Element (pass_rate_weight): A floating-point number representing the weight assigned to the pass rate.\n - with_attention (bool): A boolean indicating whether to use the attention score matrix for computing ranking scores. If False, the ranking is based solely on the validation vector V.\n", "Arguments_list": [ { "name": "results_by_task_id", "string": "\n- results_by_task_id: A dictionary where keys are task IDs and values are tuples containing the attention score matrix, correctness features, and passed results for each task.\n - attention_score_matrix (numpy.Array, shape=(n_clusters, n_clusters) : A NumPy array representing the interaction scores between clusters.\n - correctness_features (Tuple[numpy.Array, numpy.Array]): A tuple containing two NumPy arrays representing the normalized number of solutions and pass rates for each cluster\uff1a\n - First Array (Normalized Number of Solutions): These values likely represent the proportion of solutions within each cluster relative to the total number of solutions across all clusters for the task.\n - Second Array (Pass Rates): These values indicate the proportion of test cases passed by the solutions in each cluster.\n - passed_results (List[List]): A list of lists containing the results of the test cases for each solution within each cluster.\n - Outer list: Contains the results for each cluster.\n - Inner list: Each corresponds to a cluster and contains boolean values indicating whether each solution within that cluster passed a set of tests.\n", "dependency": null }, { "name": "weight_combination", "string": "\n- weight_combination (Tuple):\n - A tuple containing two floating-point values representing the weights used in the calculation of the validation vector V. These weights determine the relative importance of the normalized number of solutions and the pass rate in the final ranking.\n - First Element (norm_num_solutions_weight): A floating-point number representing the weight assigned to the normalized number of solutions.\n - Second Element (pass_rate_weight): A floating-point number representing the weight assigned to the pass rate.\n", "dependency": null }, { "name": "with_attention", "string": "\n- with_attention (bool): A boolean indicating whether to use the attention score matrix for computing ranking scores. If False, the ranking is based solely on the validation vector V.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File dependency: \n - None\n\n Cross-File dependency: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - numpy.array\n - collections.defaultdict\n", "list": [ "numpy.array" ] }, "Return": { "Return_String": "\nOutput Variables:\n - ranked_results(Dict): The ranked_results variable is a dictionary where each item (key-value pair) represents the ranked solutions for a specific task. It contains the final output of the get_sorted_solutions function, presenting the solutions in order of their calculated ranking scores.\n - Keys: Task IDs\n - Values: Lists of tuples. Each list represents the ranked solutions for the task associated with the key. Each tuple within the list has two elements:\n - First Element (Solution): A list of boolean values representing a solution. True typically indicates that a part of the solution passed a corresponding test or condition, while False indicates failure.\n - Second Element (Ranking Score): A floating-point number representing the ranking score of the solution.\n", "Return_list": [ { "name": "ranked_results", "string": "\n- ranked_results(Dict): The ranked_results variable is a dictionary where each item (key-value pair) represents the ranked solutions for a specific task. It contains the final output of the get_sorted_solutions function, presenting the solutions in order of their calculated ranking scores.\n - Keys: Task IDs\n - Values: Lists of tuples. Each list represents the ranked solutions for the task associated with the key. Each tuple within the list has two elements:\n - First Element (Solution): A list of boolean values representing a solution. True typically indicates that a part of the solution passed a corresponding test or condition, while False indicates failure.\n - Second Element (Ranking Score): A floating-point number representing the ranking score of the solution.\n", "dependency": null } ] }, "ori_python_file": "import json\nimport pickle\nimport collections\nfrom functools import partial\nfrom tqdm import tqdm\nfrom collections import defaultdict\nfrom multiprocessing import Pool\nimport numpy as np\nimport os, pickle\nfrom functionality_processing import process_cluster_attention_one_task\nfrom codet_evaluation import get_result_of_sorted_solutions, pass_at_K\nclass Evaluator:\n def __init__(\n self,\n dataset_name,\n ground_truth_exec_path,\n test_inputs_exec_path,\n model_generated_test_path,\n TestCode,\n logprob_path=None,\n reverse_logprob_path=None,\n verbose=False,\n no_rejection=False,\n num_limit_test_cases=int(1e6),\n ):\n assert dataset_name in [\"HumanEval\", \"MbppEval\"]\n self.dataset_name = dataset_name\n self.verbose = verbose\n print(\"Loading ground_truth_exec_path ...\")\n with open(ground_truth_exec_path, \"rb\") as f:\n self.data = pickle.load(f)\n print(\"Finishing loading ground_truth_exec_path\")\n print(\"Loading test_inputs_exec_path ...\")\n with open(test_inputs_exec_path, \"rb\") as f:\n self.test_inputs_exec_results = pickle.load(f)\n print(\"Finishing loading test_input_exec_path\")\n print(\"Loading model_generated_test_path ...\")\n with open(model_generated_test_path, \"rb\") as f:\n self.model_generated_input_output_dicts = pickle.load(f)\n print(\"Finishing loading model_generated_test_path\")\n if logprob_path != \"None\":\n print(\"Loading logprob path ...\")\n with open(logprob_path) as f:\n self.logprob = [json.loads(line) for line in f]\n print(\"Finishing loading logprob_path\")\n print(\"Loading reverse logprob path ...\")\n with open(reverse_logprob_path) as f:\n self.reverse_logprob = [json.loads(line) for line in f]\n print(\"Finishing loading reverse logprob path\")\n else:\n self.logprob = None\n self.reverse_logprob = None\n self.parse_data()\n self.data_by_task_id = collections.defaultdict(list)\n for entry in self.data:\n self.data_by_task_id[entry[\"task_id\"]].append(entry)\n self.num_samples_per_task = len(self.data_by_task_id[self.data[0][\"task_id\"]])\n if not all(len(task_entries) == self.num_samples_per_task for task_entries in self.data_by_task_id.values()):\n print(\"WARNING: all tasks do not have the same number of generated samples\")\n min_num_samples = min(len(task_entries) for task_entries in self.data_by_task_id.values())\n self.num_samples_per_task = min_num_samples\n for task_id, task_entries in self.data_by_task_id.items():\n self.data_by_task_id[task_id] = task_entries[:min_num_samples]\n print(f\"{self.num_samples_per_task} cached samples\")\n self.num_limit_test_cases = num_limit_test_cases\n \n def parse_data(self):\n data_by_completion = collections.defaultdict(dict)\n for item in self.data:\n data_by_completion[item[\"task_id\"]][item[\"completion\"]] = item\n for item in self.test_inputs_exec_results:\n _item = data_by_completion[item[\"task_id\"]][item[\"completion\"]]\n _item[\"test_inputs\"] = item[\"test_inputs\"]\n _item[\"outputs\"] = item[\"outputs\"]\n _item[\"test_inputs_passed\"] = item[\"passed\"]\n logprob_fields = []\n if self.logprob is not None:\n logprob_fields = [\"logprob\", \"reverse_logprob\"]\n for item in self.logprob:\n _item = data_by_completion[item[\"task_id\"]][item[\"completion\"]]\n _item[\"logprob\"] = item[\"logprob\"]\n _item[\"avg_logprob\"] = np.mean(item[\"logprob\"])\n _item[\"sum_logprob\"] = sum(item[\"logprob\"])\n for item in self.reverse_logprob:\n _item = data_by_completion[item[\"task_id\"]][item[\"completion\"]]\n _item[\"reverse_logprob\"] = item[\"reverse_logprob\"]\n _item[\"avg_reverse_logprob\"] = np.mean(item[\"reverse_logprob\"])\n _item[\"sum_reverse_logprob\"] = sum(item[\"reverse_logprob\"])\n for i, item in enumerate(self.data):\n _item = data_by_completion[item[\"task_id\"]][item[\"completion\"]]\n self.data[i] = _item\n for i, item in enumerate(self.data):\n if \"test_inputs\" not in item:\n item[\"test_inputs\"] = []\n item[\"outputs\"] = []\n item[\"test_inputs_passed\"] = []\n for i, item in enumerate(self.data):\n for key in [\"test_inputs\", \"outputs\", \"test_inputs_passed\", \"passed\"] + logprob_fields:\n assert key in item, f\"{i}, {key}, {item['task_id']}\\n\\n{item['completion']}\"\n \n def get_pass_k_results_of_random_selection(self):\n passed_results = []\n for task_items in self.data_by_task_id.values():\n task_passed_results = []\n for item in task_items:\n task_passed_results.append(item[\"passed\"])\n passed_results.append(task_passed_results)\n pass_at_k = pass_at_K(passed_results, k=[1])\n return pass_at_k\n\nclass AttentionRankingEvaluator(Evaluator):\n def __init__(self,\n *args, **kwargs,\n ):\n super().__init__(*args, **kwargs)\n self.with_attention = True\n self.weight_combination = (1,1)\n self.results_by_task_id = dict()\n self.TestCode = args[4]\n self.process()\n\n def process(self):\n pbar = tqdm(total=len(self.data_by_task_id), desc=\"Process solution clustering\")\n with Pool() as p:\n for task_id, task_items in self.data_by_task_id.items():\n task_id, attention_score_matrix, correctness_features, passed_results = process_cluster_attention_one_task(\n (task_id, task_items, self.model_generated_input_output_dicts[task_id]),\n num_limit_test_cases=self.num_limit_test_cases,\n TestCode=self.TestCode,)\n self.results_by_task_id[task_id] = (attention_score_matrix, correctness_features, passed_results)\n pbar.update(1)\n \n def get_sorted_solutions(self, results_by_task_id, weight_combination, with_attention):\n norm_num_solutions_weight, pass_rate_weight = weight_combination\n ranked_results = defaultdict(list)\n for task_id, (attention_score_matrix, correctness_features, passed_results) in results_by_task_id.items():\n V = np.array([\n (norm_num_solutions**norm_num_solutions_weight) * (pass_rate**pass_rate_weight)\n for norm_num_solutions, pass_rate in zip(*correctness_features)\n ])\n if with_attention:\n ranking_scores = attention_score_matrix @ V\n else:\n ranking_scores = V\n ranking_scores = ranking_scores.tolist()\n if isinstance(ranking_scores, int):\n ranking_scores = [ranking_scores]\n passed_and_scores = [\n (passed_result, score)\n for passed_result, score in zip(passed_results, ranking_scores)\n ]\n ranked_results[task_id] = sorted(passed_and_scores, key=lambda x: x[1], reverse=True)\n return ranked_results\n \n def get_pass_k_results(self):\n self.ranked_results = self.get_sorted_solutions(self.results_by_task_id, self.weight_combination, self.with_attention)\n return get_result_of_sorted_solutions(self.ranked_results)" } ] }, { "paper_id": 6, "paper_details": { "title": "Beyond Single-Event Extraction: Towards Efficient Document-Level Multi-Event Argument Extraction", "url": "https://arxiv.org/pdf/2405.01884" }, "repo_original_url": "https://github.com/LWL-cpu/DEEIA", "project_path": "Benchmark/6-DEEIA-master/DEEIA-master", "enviorment_name": "DEEIA", "file_organization": "\nDEEIA-master/\n config_parser.py\n data/\n ace_eeqa/\n convert.py\n download_dataset.sh\n dset_meta/\n description_ace.csv\n description_rams.csv\n description_wikievent.csv\n role_num_ace.json\n role_num_rams.json\n role_num_wikievent.json\n MLEE/\n data/\n train.json\n MLEE_role_name_mapping.json\n raw\n scripts/\n deepeventmine_to_TabEAE.py\n file_utils.py\n MLEE_to_deepeventmine.py\n ssplit.py\n sspostproc.py\n tokenization_bert.py\n tokenization_utils.py\n test\n train\n prompts/\n prompts_ace_concat.csv\n prompts_ace_continuous.csv\n prompts_ace_full.csv\n prompts_MLEE_full.csv\n prompts_rams_concat.csv\n prompts_rams_continuous.csv\n prompts_rams_full.csv\n prompts_wikievent_concat.csv\n prompts_wikievent_continuous.csv\n prompts_wikievent_full.csv\n RAMS_1.0/\n data/\n dev.jsonlines\n test.jsonlines\n train.jsonlines\n data_final/\n dev.jsonlines\n test.jsonlines\n train.jsonlines\n squeeze_merge.py\n WikiEvent/\n data/\n dev.jsonl\n test.jsonl\n train.jsonl\n data_final/\n dev.jsonl\n test.jsonl\n train.jsonl\n split.py\n download_data.sh\n engine.py\n environment.sh\n exp/\n metric.py\n models/\n DEEIA.py\n __init__.py\n modeling_bart.py\n modeling_roberta_.py\n process_long.py\n single_prompt.py\n outputs_res/\n log.txt\n processors/\n __init__.py\n processor_base.py\n processor_multiarg.py\n README.md\n requirements.txt\n runner/\n evaluate.py\n __init__.py\n runner.py\n train.py\n scripts/\n train_mlee_roberta.sh\n train_rams_roberta.sh\n train_wikievent_roberta.sh\n utils.py\n", "latex_code_path": "Benchmark/6-DEEIA-master/arXiv-2405.01884v2", "task_details": [ { "task_id": 0, "indent": 2, "latex_code": "\n\\subsection{Event-specific Information Aggregation}\n\\label{Sec:Event-specific Information Aggregation}\nIn this section,\nwe design an event-specific information aggregation (EIA) module which adaptively aggregates useful information for specific events. \n{We hope the model can make use of the context information relevant to the specific event and the argument when extracting an argument. Therefore, we consider using triggers (representing the event) and slots (representing the argument) to measure the relevance between the target argument and context (prompt) information. }\n\nSpecifically, we utilize the attention heads of argument slots and their associated triggers, derived from the pre-trained transformer encoder, to calculate the attention product for the input sequence tokens (including both context and prompt). {The dot product of attention is designed to measure the degree of association between the current event's argument and every token of input context. }\n\nWe adopt an encoder-decoder architecture. The encoder is employed to encode the input text, while the decoder is tasked with deriving the event-oriented context and context-oriented prompt\nrepresentation $\\mathbf{H}_\\mathrm{de}$:\n\n\\begin{equation}\n \\begin{array}{c}\n[\\mathbf{A}; \\mathbf{H}_\\mathrm{en}] = \\mathrm{Encoder}_s(S), \\vspace{1.0ex} \\\\\n\\mathbf{H}_\\mathrm{de} = \\mathrm{Decoder} (\\mathbf{H}_\\mathrm{en}), \\vspace{1.0ex} \n\\end{array}\n\\end{equation}\nwhere the $\\mathrm{Encoder}_s$ is the dependency-guided encoder and the $\\mathrm{Decoder}$ is a transformer-based decoder.\n$S$ is the input of the concatenation of context $X$ and prompt $P$, and $\\mathbf{A} \\in \\mathbb{R}^{H \\times l_s \\times l_s}$ is the multi-head attention matrix and $\\mathbf{H}_\\mathrm{en}, \\mathbf{H}_\\mathrm{de} \\in \\mathbb{R}^{l_s \\times d}$. $H$ is the attention head numbers and $l_s$ is the length of input sequence $S$.\n\nFor the $k$-th argument slot $s_{k,i}$ to be predicted in the $i$-th event, we first get the contextual attention vectors $\\textbf{A}_{t_i} \\in \\mathbb{R}^{l_s}$ and $\\textbf{A}_{s_{k,i}} \\in \\mathbb{R}^{l_s}$ from $\\mathbf{A}$, corresponding to the trigger $t_i$ and the slot in the prompt respectively. These vectors are obtained by averaging across all attention heads and associated subtokens\\footnote{We only take the start token $\\left$ to represent the trigger.}.\nThen for the argument slot $s_{k,i}$, we obtain the context-enhanced vector $\\textbf{c}_{k,i} \\in \\mathbb{R}^{d}$ which adaptively aggregates useful \ncontext and prompt information for argument extraction. \n\n\\begin{equation}\n\\label{eq6}\n\\setlength\\abovedisplayskip{3pt plus 3pt minus 7pt}\n\\setlength\\belowdisplayskip{3pt plus 3pt minus 7pt}\n \\begin{array}{c}\n\\textbf{p}_k=\\mathrm{softmax}(\\textbf{A}_{t_i}\\cdot \\textbf{A}_{s_{k,i}}\\;)\\vspace{1.0ex}, \\\\\n \\textbf{c}_{k,i}={\\mathbf{H}_\\mathrm{en}}^T \\ \\textbf{p}_k,\n \\end{array}\n\\end{equation}%\nwhere $\\textbf{p}_k \\in \\mathbb{R}^{l_s}$ is the computed attention weight vector for argument slot $s_{k,i}$. Then $\\textbf{c}_{k,i}$ is subsequently incorporated into the decoder output $\\mathbf{h}_{s_{k,i}} \\in \\mathbb{R}^{d}$ of slot $s_{k,i}$ to get $\\tilde{\\mathbf{h}}_{s_{k,i}} \\in \\mathbb{R}^{d}$:\n\n\\begin{equation} \n\\tilde{\\mathbf{h}}_{s_{k,i}}=\\mathrm{tanh}(\\mathbf{W}_{1}[\\mathbf{h}_{s_{k,i}}; \\textbf{c}_{k,i}]),\n\\end{equation}\nwhere $\\mathbf{W}_{1} \\in \\mathbb{R}^{2d \\times d}$ is learnable parameter.\n", "completion_path": "./models/DEEIA.py", "namespace": "models.DEEIA.forward", "type": "method", "signature_position": [ 38, 52 ], "body_position": [ 53, 176 ], "script": "\npython engine.py --dataset_type=rams --model_name_or_path=roberta-large --role_path=./data/dset_meta/description_rams.csv --prompt_path=./data/prompts/prompts_rams_full.csv --seed=22 --output_dir=exp/rams_large/22 --learning_rate=2e-5 --max_steps=10000 --max_enc_seq_length=512 --bipartite --lamb=1e-5 \n", "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Perform dependency-guided encoding by running the backbone model on the full input.\n# The 'structural_mask' integrates pre-defined event dependencies into the self-attention mechanism.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\ncontext_outputs_ = self.roberta(\n input_ids=all_ids,\n attention_mask=all_mask_ids,\n output_hidden_states=True,\n fully_encode=True,\n output_attentions=True,\n return_dict=True,\n structural_mask=torch.stack(enc_attention_mask, dim=0) # DE module\n)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Retrieve hidden states from the encoder and select the decoder context layer.\n# This selection reflects the practice of using a specific encoder layer for downstream decoding.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nenc_outputs = context_outputs_.hidden_states\ndecoder_context = enc_outputs[self.decode_layer_start]\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Determine the final context representation based on the configuration.\n# The model can use either the designated decoder context or the final encoder layer output.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nif self.config.context_representation == 'decoder':\n context_outputs = enc_outputs[-1]\nelse:\n context_outputs = decoder_context\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Aggregate encoder attentions by averaging over attention heads from the designated decoder layer.\n# These attention maps are used later for event-specific information aggregation.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nencoder_attentions = context_outputs_.attentions[self.decode_layer_start].mean(1)\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Generate decoder prompt outputs by running the backbone model in cross-attention mode.\n# This produces context-enhanced prompt embeddings as required by the encoder-decoder architecture in the paper.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\ndecoder_prompt_outputs = self.roberta(\n input_ids=dec_prompt_ids,\n attention_mask=dec_prompt_mask_ids,\n encoder_hidden_states=decoder_context,\n encoder_attention_mask=all_mask_ids,\n cross_attention=True,\n).last_hidden_state\n# [End Snippet 5]\n\nlogit_lists = list()\ntotal_loss = 0.\n\nif len(event_triggers) == 0:\n print(len(event_triggers))\n\n# ---------------------------------------------------------------------------\n# Snippet 6: Iterate over each sample in the batch to process event-specific argument extraction.\n# For each sample, obtain the corresponding context output, prompt output, attention maps, and event triggers.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 6]\nfor i, (context_output, decoder_prompt_output, encoder_attention, arg_joint_prompt, \n old_tok_to_new_tok_index, event_trigger) in \\\n enumerate(zip(context_outputs, decoder_prompt_outputs, encoder_attentions, \n arg_joint_prompts, old_tok_to_new_tok_indexs, event_triggers)):\n\n\n batch_loss = list()\n cnt = 0\n list_output = list()\n # [End Snippet 6]\n\n for ii in range(len(event_trigger)):\n event_trigger_pos = event_trigger[ii]\n\n # ---------------------------------------------------------------------------\n # Snippet 7: Compute the event trigger attention vector by averaging encoder attention scores over the trigger token span.\n # This produces a representative attention profile for the event trigger.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 7]\n event_trigger_attention = torch.mean(\n encoder_attention[event_trigger_pos[0]:event_trigger_pos[1]], dim=0\n ).unsqueeze(0)\n # [End Snippet 7]\n\n output = dict()\n\n # ---------------------------------------------------------------------------\n # Snippet 8: For each argument role defined in the event prompt, compute span logits.\n # This corresponds to predicting the start and end positions for each argument slot.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 8]\n for arg_role in arg_joint_prompt[ii].keys():\n prompt_slots = arg_joint_prompt[ii][arg_role]\n\n start_logits_list = list()\n end_logits_list = list()\n # [End Snippet 8]\n\n # ---------------------------------------------------------------------------\n # Snippet 9: Iterate over each prompt slot instance for the current argument role.\n # construct the prompt query from either the decoder prompt outputs or the context output.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 9]\n for (p_start, p_end, p_start_off, p_end_off) in zip(\n prompt_slots['tok_s'], \n prompt_slots['tok_e'], \n prompt_slots['tok_s_off'], \n prompt_slots['tok_e_off']\n ):\n\n prompt_query_sub = context_output[p_start_off:p_end_off]\n # [End Snippet 9]\n\n # ---------------------------------------------------------------------------\n # Snippet 10: If the extracted prompt segment is empty, default to using the first token's representation.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 10]\n if prompt_query_sub.shape[0] == 0:\n prompt_query_sub = context_output[0].unsqueeze(0)\n # [End Snippet 10]\n\n # ---------------------------------------------------------------------------\n # Snippet 11: For indices exceeding the maximum allowed sequence length,\n # average the prompt tokens to create a simplified representation.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 11]\n if (p_start_off >= self.config.max_enc_seq_length or \n p_end_off >= self.config.max_enc_seq_length):\n # Simplify the representation in case of out-of-bounds\n prompt_query_sub = torch.mean(prompt_query_sub, dim=0).unsqueeze(0)\n else:\n # [End Snippet 11]\n # ---------------------------------------------------------------------------\n # Snippet 12: Compute the mean representations for both the prompt sub-sequence and its associated attention.\n # This prepares the data for event-specific aggregation.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 12]\n prompt_query_sub = torch.mean(prompt_query_sub, dim=0).unsqueeze(0)\n prompt_query_sub_attention = encoder_attention[p_start_off:p_end_off]\n if prompt_query_sub_attention.shape[0] == 0:\n prompt_query_sub_attention = encoder_attention[0]\n prompt_query_sub_attention = torch.mean(prompt_query_sub_attention, dim=0).unsqueeze(0)\n # [End Snippet 12]\n\n # ---------------------------------------------------------------------------\n # Snippet 13: Integrate event trigger information with the prompt query using attention.\n # Multiply the prompt's attention with the event trigger attention, normalize,\n # and aggregate the context representations via tensor contraction.\n # This mirrors the dot product and aggregation in Eq. (6) of the LaTeX.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 13]\n att = (prompt_query_sub_attention * event_trigger_attention)\n att = att / (att.sum(1, keepdim=True) + 1e-5) # Normalize attention weights\n context_rs = contract(\"ld,rl->rd\", decoder_context[i], att) # Aggregate hidden representations\n prompt_query_sub = torch.tanh(self.contextual_merger(torch.cat((prompt_query_sub, context_rs), dim=-1)))\n # [End Snippet 13]\n\n # ---------------------------------------------------------------------------\n # Snippet 14: Compute the start and end query vectors by element-wise multiplying the prompt query\n # with the corresponding learnable span selector parameters.\n # This is analogous to the transformation for span prediction in the LaTeX.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 14]\n start_query = (prompt_query_sub * self.w_prompt_start).unsqueeze(-1)\n end_query = (prompt_query_sub * self.w_prompt_end).unsqueeze(-1)\n # [End Snippet 14]\n\n # ---------------------------------------------------------------------------\n # Snippet 15: Compute raw start and end logits by performing batched matrix multiplications between\n # the context representations and the query vectors. This produces a score for each token position.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 15]\n start_logits = torch.bmm(context_output.unsqueeze(0), start_query).squeeze()\n end_logits = torch.bmm(context_output.unsqueeze(0), end_query).squeeze()\n # [End Snippet 15]\n\n start_logits_list.append(start_logits)\n end_logits_list.append(end_logits)\n\n output[arg_role] = [start_logits_list, end_logits_list]\n\n # ---------------------------------------------------------------------------\n # Snippet 16: In training mode, compute the loss for the current argument role by matching predicted spans\n # against ground-truth spans using either bipartite matching or direct index alignment.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 16]\n if self.training:\n target = target_info[i][ii][arg_role]\n predicted_spans = []\n for (start_logits, end_logits) in zip(start_logits_list, end_logits_list):\n if self.config.matching_method_train == 'accurate':\n predicted_spans.append(\n get_best_span(start_logits, end_logits, \n old_tok_to_new_tok_index, \n self.config.max_span_length)\n )\n elif self.config.matching_method_train == 'max':\n predicted_spans.append(\n get_best_span_simple(start_logits, end_logits)\n )\n else:\n raise AssertionError()\n # [End Snippet 16]\n\n # ---------------------------------------------------------------------------\n # Snippet 17: Match predicted spans with target spans using bipartite matching or direct index alignment.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 17]\n target_spans = [[s, e] for (s, e) in zip(target[\"span_s\"], target[\"span_e\"])]\n if len(target_spans) < len(predicted_spans):\n pad_len = len(predicted_spans) - len(target_spans)\n target_spans += [[0, 0]] * pad_len\n target[\"span_s\"] += [0] * pad_len\n target[\"span_e\"] += [0] * pad_len\n\n \n if self.config.bipartite:\n idx_preds, idx_targets = hungarian_matcher(predicted_spans, target_spans)\n else:\n idx_preds = list(range(len(predicted_spans)))\n idx_targets = list(range(len(target_spans)))\n if len(idx_targets) > len(idx_preds):\n idx_targets = idx_targets[0:len(idx_preds)]\n idx_preds = torch.as_tensor(idx_preds, dtype=torch.int64)\n idx_targets = torch.as_tensor(idx_targets, dtype=torch.int64)\n # [End Snippet 17]\n\n # ---------------------------------------------------------------------------\n # Snippet 18: Compute cross-entropy loss for the start and end logits based on the matched indices.\n # The total loss is accumulated and normalized by the number of matched spans.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 18]\n cnt += len(idx_preds)\n start_loss = self.loss_fct(\n torch.stack(start_logits_list)[idx_preds], \n torch.LongTensor(target[\"span_s\"]).to(self.config.device)[idx_targets]\n )\n end_loss = self.loss_fct(\n torch.stack(end_logits_list)[idx_preds], \n torch.LongTensor(target[\"span_e\"]).to(self.config.device)[idx_targets]\n )\n batch_loss.append((start_loss + end_loss) / 2)\n # [End Snippet 18]\n\n list_output.append(output)\n\n # ---------------------------------------------------------------------------\n # Snippet 19: Accumulate the loss for the current sample and collect the computed logits.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 19]\n logit_lists.append(list_output)\n if self.training:\n total_loss = total_loss + torch.sum(torch.stack(batch_loss)) / cnt\n # [End Snippet 19]\n\n# ---------------------------------------------------------------------------\n# Snippet 20: Return the final loss and logits. During evaluation, an empty loss list is returned.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 20]\nif self.training:\n loss = total_loss / len(context_outputs)\n return loss, logit_lists\nelse:\n loss = []\n return loss, logit_lists\n# [End Snippet 20]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The integration of event trigger information with the prompt query in the Python code uses a learned linear layer (contextual_merger) followed by a tanh activation, which, although conceptually similar to the LaTeX's combination of h_{s_{k,i}} and c_{k,i}, provides a more detailed implementation.\n - Dependency-Guided Structural Masking in Encoder: The LaTeX description omits the structural dependency mask utilized by the encoder self-attention mechanism. The reference Python implementation employs a dependency-based structural mask that constrains the self-attention mechanism to reflect syntactic or semantic dependencies among tokens. Omitting this step removes vital structural information from token representations, resulting in mismatched representations.\n - Decoder Prompt Encoding with Cross-Attention: The LaTeX description lacks details about how the decoder explicitly performs cross-attention with encoder outputs. In the reference code, decoder prompt embeddings are generated separately by a transformer decoder cross-attending to the context from the encoder outputs. The explicit cross-attention step is critical since it ensures prompts fully incorporate event-oriented context representations from the encoder.\n - Handling Special Cases in Prompt Representations: The LaTeX neglects the special handling of prompt subtokens when encountering edge cases such as empty token spans or tokens that exceed the maximum sequence length. The reference implementation specifically handles these cases by defaulting to the first token embedding or computing a simplified mean representation, ensuring stable behavior across inputs.\n - Bipartite Matching for Span Prediction and Loss Computation: While the LaTeX discusses the use of bipartite matching briefly, it misses the practical details involved in span prediction loss calculation. The reference code explicitly handles alignment between predicted and target spans, padding of unmatched spans, and the use of Hungarian matching for accurate training, which are essential for reproducing accurate results.\n - Layer-specific Attention Extraction: The LaTeX describes attention aggregation across attention heads without specifying the exact layer. The reference implementation explicitly selects and averages attention from a designated encoder layer (`self.decode_layer_start`).\n\n Mismatched Details:\n - Normalization in Attention Aggregation: The LaTeX formula (\\textbf{p}_k = softmax(\\textbf{A}_{t_i}\u00b7\\textbf{A}_{s_{k,i}})) implies a straightforward dot product followed by softmax. However, the reference code explicitly includes a normalization step to prevent numerical instability (`att = att / (att.sum(1, keepdim=True) + eps)`, eps=1e-5), a critical detail for achieving stable and consistent aggregation. \n - Prompt Slot Attention Aggregation: The LaTeX indicates attention vectors are simply obtained by averaging attention heads. The reference implementation clearly specifies averaging over both subtokens and heads for precise alignment. \n ", "Missing_details": [ "\n- The integration of event trigger information with the prompt query in the Python code uses a learned linear layer (contextual_merger) followed by a tanh activation, which, although conceptually similar to the LaTeX's combination of h_{s_{k,i}} and c_{k,i}, provides a more detailed implementation.\n", "\n- Dependency-Guided Structural Masking in Encoder: The LaTeX description omits the structural dependency mask utilized by the encoder self-attention mechanism. The reference Python implementation employs a dependency-based structural mask that constrains the self-attention mechanism to reflect syntactic or semantic dependencies among tokens. Omitting this step removes vital structural information from token representations, resulting in mismatched representations.\n", "\n- Decoder Prompt Encoding with Cross-Attention: The LaTeX description lacks details about how the decoder explicitly performs cross-attention with encoder outputs. In the reference code, decoder prompt embeddings are generated separately by a transformer decoder cross-attending to the context from the encoder outputs. The explicit cross-attention step is critical since it ensures prompts fully incorporate event-oriented context representations from the encoder.\n", "\n- Handling Special Cases in Prompt Representations: The LaTeX neglects the special handling of prompt subtokens when encountering edge cases such as empty token spans or tokens that exceed the maximum sequence length. The reference implementation specifically handles these cases by defaulting to the first token embedding or computing a simplified mean representation, ensuring stable behavior across inputs.\n", "\n- Bipartite Matching for Span Prediction and Loss Computation: While the LaTeX discusses the use of bipartite matching briefly, it misses the practical details involved in span prediction loss calculation. The reference code explicitly handles alignment between predicted and target spans, padding of unmatched spans, and the use of Hungarian matching for accurate training, which are essential for reproducing accurate results.\n", "\n- Layer-specific Attention Extraction: The LaTeX describes attention aggregation across attention heads without specifying the exact layer. The reference implementation explicitly selects and averages attention from a designated encoder layer (`self.decode_layer_start`).\n" ], "Mismatched_details": [ "\n- Normalization in Attention Aggregation: The LaTeX formula (\\textbf{p}_k = softmax(\\textbf{A}_{t_i}\u00b7\\textbf{A}_{s_{k,i}})) implies a straightforward dot product followed by softmax. However, the reference code explicitly includes a normalization step to prevent numerical instability (`att = att / (att.sum(1, keepdim=True) + eps)`, eps=1e-5), a critical detail for achieving stable and consistent aggregation.\n", "\n- Prompt Slot Attention Aggregation: The LaTeX indicates attention vectors are simply obtained by averaging attention heads. The reference implementation clearly specifies averaging over both subtokens and heads for precise alignment.\n" ] }, "Arguments": { "string": "\nArguments: \n - enc_input_ids (torch.Tensor, dtype=torch.int, shape=[batch_size \u00d7 seq_len]): Not used directly here, typically main text input to the encoder.\n - enc_mask_ids (torch.Tensor, dtype=torch.int, shape=[batch_size \u00d7 seq_len]): Not used directly here, typically attention mask for the encoder.\n - all_ids (torch.Tensor, dtype=torch.int, shape=[batch_size \u00d7 seq_len]): Full input IDs that combine context and prompts for multi-event scenarios.\n - all_mask_ids (torch.Tensor, dtype=torch.int, shape=[batch_size \u00d7 seq_len]): Corresponding attention masks for 'all_ids'.\n - dec_prompt_ids (torch.Tensor, dtype=torch.int, shape=[batch_size \u00d7 seq_len]): Input IDs for prompts in decoder (only used if the model uses separate decoder inputs).\n - dec_prompt_mask_ids (torch.Tensor, dtype=torch.int, shape=[batch_size \u00d7 seq_len]): Attention masks for 'dec_prompt_ids'.\n - arg_joint_prompts (list[Dict[Dict[list]]]): is a multi-level data structure that organizes event-level prompt information for each sample in a batch. At the outermost level, each element corresponds to one sample (i.e., one piece of text) that can contain one or more events. Within each sample:\n - Each event is represented as a dictionary of argument roles (e.g., 'injurer', 'instrument', 'place', etc.).\n - For each argument role, there are four lists that define the local and offset-based token boundaries of the corresponding prompt tokens:\n - 'tok_s', 'tok_e': Local start and end token indices within the prompt itself (often used when the dataset is 'wikievent' to slice the decoder prompt).\n - 'tok_s_off', 'tok_e_off': Offset-based start and end token indices referencing the same prompt tokens but indexed within the overall context (used when the prompt tokens are integrated into the broader encoder context).\n - target_info (list): is a multi-level data structure for storing ground-truth argument information in each sample. At the outermost level, each element corresponds to a single sample containing one or more events. Within each sample:\n - Each event is represented as a dictionary of argument roles (e.g., 'injurer', 'place', 'victim', etc.).\n - Each argument role dictionary contains three keys:\n - 'span_s' and 'span_e': Lists of start and end indices for each ground-truth argument span in the original text.\n - 'text': A list of the actual argument strings corresponding to those spans.\n - old_tok_to_new_tok_indexs (list[list[list]]): It is a multi-level data structure that maps original token indices to their new sub-token indices after text processing (e.g., subword tokenization). For each sample in the batch: \n - You have a list of index pairs\u2014each pair typically represents how a token in the original text corresponds to one or more sub-tokens in the processed text.\n - These mappings ensure that when the model computes or predicts spans in the new, sub-token space, it can correctly align them back to the original text boundaries.\n - arg_list (list[list]): is a nested list specifying the argument roles for each event in the batch. At the top level, each element corresponds to a single sample, which may contain one or more events. For each event, there is a list of argument roles (e.g., 'instrument', 'injurer', 'victim', 'place', 'recipient') that the model needs to extract.\n - event_triggers (list[list]): is a nested list that records the token spans of event triggers for each sample in the batch. At the highest level, each element corresponds to a single sample, which may contain one or more events. For each event, there is a pair of indices [start, end] that define the trigger token span in the context.\n - enc_attention_mask (list[torch.Tensor]): is a list of 3D PyTorch tensors, one per batch element, that encodes the structural or dependency-based attention patterns between tokens. Each tensor typically has a shape like [batch_size \u00d7 seq_len \u00d7 seq_len].\n The function also uses the following class attributes:\n - self.config (RobertaConfig): A configuration object that stores hyperparameters and model settings.\n - self.config.context_representation: A string indicating whether to use the encoder or decoder context representation.\n - self.config.max_enc_seq_length: An integer specifying the maximum sequence length for encoder inputs.\n - self.config.matching_method_train: A string indicating the method for matching predicted spans to ground truth during training.\n - 'accurate': Use accurate matching with token index alignment.\n - 'max': Use maximum span prediction without alignment.\n - self.config.bipartite: A boolean flag indicating whether to use bipartite matching for span prediction.\n - self.config.device (torch.device): The device (CPU or GPU) on which the model is running.\n - self.roberta (RobertaModel_, defined in ./models/modeling_roberta_.py): A pre-trained RoBERTa model used for encoding text inputs.\n - self.contextual_merger (torch.nn.Linear): A linear layer used to merge context and prompt representations.\n - self.w_prompt_start (torch.nn.Parameter): A learnable parameter for span start prediction.\n - self.w_prompt_end (torch.nn.Parameter): A learnable parameter for span end prediction.\n - self.loss_fct (torch.nn.CrossEntropyLoss): A loss function for computing the span prediction loss.\n - self.decode_layer_start (int): An integer specifying the decoder layer to use for context representation.\n - self.training (bool): A flag indicating whether the model is in training mode.\n \n", "Arguments_list": [ { "name": "enc_input_ids", "string": "- enc_input_ids (torch.Tensor, dtype=torch.int, shape=[batch_size \u00d7 seq_len]): Not used directly here, typically main text input to the encoder.", "dependency": null }, { "name": "enc_mask_ids", "string": "- enc_mask_ids (torch.Tensor, dtype=torch.int, shape=[batch_size \u00d7 seq_len]): Not used directly here, typically attention mask for the encoder.", "dependency": null }, { "name": "all_ids", "string": "- all_ids (torch.Tensor, dtype=torch.int, shape=[batch_size \u00d7 seq_len]): Full input IDs that combine context and prompts for multi-event scenarios.", "dependency": null }, { "name": "all_mask_ids", "string": "- all_mask_ids (torch.Tensor, dtype=torch.int, shape=[batch_size \u00d7 seq_len]): Corresponding attention masks for 'all_ids'.", "dependency": null }, { "name": "dec_prompt_ids", "string": "- dec_prompt_ids (torch.Tensor, dtype=torch.int, shape=[batch_size \u00d7 seq_len]): Input IDs for prompts in decoder (only used if the model uses separate decoder inputs).", "dependency": null }, { "name": "dec_prompt_mask_ids", "string": "- dec_prompt_mask_ids (torch.Tensor, dtype=torch.int, shape=[batch_size \u00d7 seq_len]): Attention masks for 'dec_prompt_ids'.", "dependency": null }, { "name": "arg_joint_prompts", "string": "\n- arg_joint_prompts (list[Dict[Dict[list]]]): is a multi-level data structure that organizes event-level prompt information for each sample in a batch. At the outermost level, each element corresponds to one sample (i.e., one piece of text) that can contain one or more events. Within each sample:\n - Each event is represented as a dictionary of argument roles (e.g., 'injurer', 'instrument', 'place', etc.).\n - For each argument role, there are four lists that define the local and offset-based token boundaries of the corresponding prompt tokens:\n - 'tok_s', 'tok_e': Local start and end token indices within the prompt itself (often used when the dataset is 'wikievent' to slice the decoder prompt).\n - 'tok_s_off', 'tok_e_off': Offset-based start and end token indices referencing the same prompt tokens but indexed within the overall context (used when the prompt tokens are integrated into the broader encoder context).\n", "dependency": null }, { "name": "target_info", "string": "\n- target_info (list): is a multi-level data structure for storing ground-truth argument information in each sample. At the outermost level, each element corresponds to a single sample containing one or more events. Within each sample:\n - Each event is represented as a dictionary of argument roles (e.g., 'injurer', 'place', 'victim', etc.).\n - Each argument role dictionary contains three keys:\n - 'span_s' and 'span_e': Lists of start and end indices for each ground-truth argument span in the original text.\n - 'text': A list of the actual argument strings corresponding to those spans.\n", "dependency": null }, { "name": "old_tok_to_new_tok_indexs", "string": "\n- old_tok_to_new_tok_indexs (list[list[list]]): It is a multi-level data structure that maps original token indices to their new sub-token indices after text processing (e.g., subword tokenization). For each sample in the batch:\n - You have a list of index pairs\u2014each pair typically represents how a token in the original text corresponds to one or more sub-tokens in the processed text.\n - These mappings ensure that when the model computes or predicts spans in the new, sub-token space, it can correctly align them back to the original text boundaries.\n", "dependency": null }, { "name": "arg_list", "string": "\n- arg_list (list[list]): is a nested list specifying the argument roles for each event in the batch. At the top level, each element corresponds to a single sample, which may contain one or more events. For each event, there is a list of argument roles (e.g., 'instrument', 'injurer', 'victim', 'place', 'recipient') that the model needs to extract.\n", "dependency": null }, { "name": "event_triggers", "string": "\n- event_triggers (list[list]): is a nested list that records the token spans of event triggers for each sample in the batch. At the highest level, each element corresponds to a single sample, which may contain one or more events. For each event, there is a pair of indices [start, end] that define the trigger token span in the context.\n", "dependency": null }, { "name": "enc_attention_mask", "string": "\n- enc_attention_mask (list[torch.Tensor]): is a list of 3D PyTorch tensors, one per batch element, that encodes the structural or dependency-based attention patterns between tokens. Each tensor typically has a shape like [batch_size \u00d7 seq_len \u00d7 seq_len].\n", "dependency": null }, { "name": "self.config", "string": "\n- self.config (RobertaConfig): A configuration object that stores hyperparameters and model settings.\n - self.config.context_representation: A string indicating whether to use the encoder or decoder context representation.\n - self.config.max_enc_seq_length: An integer specifying the maximum sequence length for encoder inputs.\n - self.config.matching_method_train: A string indicating the method for matching predicted spans to ground truth during training.\n - 'accurate': Use accurate matching with token index alignment.\n - 'max': Use maximum span prediction without alignment.\n - self.config.bipartite: A boolean flag indicating whether to use bipartite matching for span prediction.\n - self.config.device (torch.device): The device (CPU or GPU) on which the model is running.\n", "dependency": null }, { "name": "self.roberta", "string": "\n- self.roberta (RobertaModel_, defined in ./models/modeling_roberta_.py): A pre-trained RoBERTa model used for encoding text inputs.\n", "dependency": null }, { "name": "self.contextual_merger", "string": "\n- self.contextual_merger (torch.nn.Linear): A linear layer used to merge context and prompt representations.\n", "dependency": null }, { "name": "self.w_prompt_start", "string": "\n- self.w_prompt_start (torch.nn.Parameter): A learnable parameter for span start prediction.\n", "dependency": null }, { "name": "self.w_prompt_end", "string": "\n- self.w_prompt_end (torch.nn.Parameter): A learnable parameter for span end prediction.\n", "dependency": null }, { "name": "self.loss_fct", "string": "\n- self.loss_fct (torch.nn.CrossEntropyLoss): A loss function for computing the span prediction loss.\n", "dependency": null }, { "name": "self.decode_layer_start", "string": "\n- self.decode_layer_start (int): An integer specifying the decoder layer to use for context representation.\n", "dependency": null }, { "name": "self.training", "string": "\n- self.training (bool): A flag indicating whether the model is in training mode.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra File Dependencies: \n - None\n\n - Cross File Dependencies:\n - utils.hungarian_matcher\n - utils.get_best_span\n - utils.get_best_span_simple\n", "intra_file": [], "cross_file": [ "utils.hungarian_matcher", "utils.get_best_span", "utils.get_best_span_simple" ] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.stack\n - torch.mean\n - torch.tanh\n - torch.cat\n - torch.bmm\n - torch.sum\n - torch.as_tensor\n - opt_einsum.contract\n - torch.LongTensor\n", "list": [ "torch.stack", "torch.mean", "torch.tanh", "torch.cat", "torch.bmm", "torch.sum", "torch.as_tensor", "opt_einsum.contract", "torch.LongTensor" ] }, "Return": { "Return_String": "\nReturns:\n - loss (torch.Tensor, scalar): If is the training stage, It is the total loss over the batch. Otherwise, it is an empty list.\n - logit_lists (list(list(dict(list)))): It is a nested list that stores the predicted span selection logits. For each event in every sample of the input batch, its structure is as follows:\n - Outer List: Contains one element per sample in the batch.\n - For Each Sample: The corresponding element is a list where each entry represents one event.\n - For Each Event: The event-level element is a dictionary with keys corresponding to argument roles (e.g., \"injurer\", \"instrument\", etc.). Each key maps to a list containing two elements:\n A list of start logits for all prompt slot instances associated with that argument role.\n A list of end logits for those same prompt slot instances.\n", "Return_list": [ { "name": "loss", "string": "- loss (torch.Tensor, scalar): If is the training stage, It is the total loss over the batch. Otherwise, it is an empty list.", "dependency": null }, { "name": "logit_lists", "string": "\n- logit_lists (list(list(dict(list)))): It is a nested list that stores the predicted span selection logits. For each event in every sample of the input batch, its structure is as follows:\n - Outer List: Contains one element per sample in the batch.\n - For Each Sample: The corresponding element is a list where each entry represents one event.\n - For Each Event: The event-level element is a dictionary with keys corresponding to argument roles (e.g., \"injurer\", \"instrument\", etc.). Each key maps to a list containing two elements:\n A list of start logits for all prompt slot instances associated with that argument role.\n A list of end logits for those same prompt slot instances.\n\n", "dependency": null } ] }, "ori_python_file": "import torch\nimport pprint\nimport torch.nn as nn\nfrom models.modeling_bart import BartModel\nfrom utils import hungarian_matcher, get_best_span, get_best_span_simple\nfrom opt_einsum import contract\nfrom models.modeling_roberta_ import RobertaModel_, RobertaPreTrainedModel\nfrom models.modeling_roberta_ import *\nfrom models.process_long import process_long_input_decode, process_long_input\n\nclass DEEIA(RobertaPreTrainedModel):\n def __init__(self, config, decode_layer_start=17):\n super().__init__(config)\n self.config = config\n decode_layer_start = config.encoder_layers\n if self.config.architectures[0] == \"RobertaForMaskedLM\":\n self.roberta = RobertaModel_(\n config,\n decode_layer_start=decode_layer_start,\n structural_mask=config.structural_type\n )\n else:\n self.roberta = BartModel(\n config,\n structural_mask=config.structural_type\n )\n self.w_prompt_start = nn.Parameter(torch.rand(config.hidden_size, ))\n self.w_prompt_end = nn.Parameter(torch.rand(config.hidden_size, ))\n self.decode_layer_start = decode_layer_start\n self.loss_fct = nn.CrossEntropyLoss(reduction='sum')\n self.contextual_merger = nn.Linear(2 * config.hidden_size, config.hidden_size)\n \n def reset(self):\n self.w_prompt_start = nn.Parameter(torch.rand(self.config.hidden_size, ))\n self.w_prompt_end = nn.Parameter(torch.rand(self.config.hidden_size, ))\n self.roberta._init_weights(self.contextual_merger.weight)\n \n def forward(\n self,\n enc_input_ids=None,\n enc_mask_ids=None,\n all_ids=None,\n all_mask_ids=None,\n dec_prompt_ids=None,\n dec_prompt_mask_ids=None,\n arg_joint_prompts=None,\n target_info=None,\n old_tok_to_new_tok_indexs=None,\n arg_list=None,\n event_triggers=None,\n enc_attention_mask=None\n ):\n context_outputs_ = self.roberta(\n input_ids=all_ids,\n attention_mask=all_mask_ids,\n output_hidden_states=True,\n fully_encode=True,\n output_attentions=True,\n return_dict=True,\n structural_mask=torch.stack(enc_attention_mask, dim=0)\n )\n enc_outputs = context_outputs_.hidden_states\n decoder_context = enc_outputs[self.decode_layer_start]\n if self.config.context_representation == 'decoder':\n context_outputs = enc_outputs[-1]\n else:\n context_outputs = decoder_context\n encoder_attentions = context_outputs_.attentions[self.decode_layer_start].mean(1)\n decoder_prompt_outputs = self.roberta(\n input_ids=dec_prompt_ids,\n attention_mask=dec_prompt_mask_ids,\n encoder_hidden_states=decoder_context,\n encoder_attention_mask=all_mask_ids,\n cross_attention=True,\n ).last_hidden_state\n logit_lists = list()\n total_loss = 0.\n if len(event_triggers) == 0:\n print(len(event_triggers))\n for i, (context_output, decoder_prompt_output, encoder_attention, arg_joint_prompt,\n old_tok_to_new_tok_index, event_trigger) in \\\n enumerate(zip(context_outputs, decoder_prompt_outputs, encoder_attentions,\n arg_joint_prompts, old_tok_to_new_tok_indexs, event_triggers)):\n batch_loss = list()\n cnt = 0\n list_output = list()\n for ii in range(len(event_trigger)):\n event_trigger_pos = event_trigger[ii]\n event_trigger_attention = torch.mean(\n encoder_attention[event_trigger_pos[0]:event_trigger_pos[1]], dim=0\n ).unsqueeze(0)\n output = dict()\n for arg_role in arg_joint_prompt[ii].keys():\n prompt_slots = arg_joint_prompt[ii][arg_role]\n start_logits_list = list()\n end_logits_list = list()\n for (p_start, p_end, p_start_off, p_end_off) in zip(\n prompt_slots['tok_s'],\n prompt_slots['tok_e'],\n prompt_slots['tok_s_off'],\n prompt_slots['tok_e_off']\n ):\n prompt_query_sub = context_output[p_start_off:p_end_off]\n if prompt_query_sub.shape[0] == 0:\n prompt_query_sub = context_output[0].unsqueeze(0)\n if (p_start_off >= self.config.max_enc_seq_length or\n p_end_off >= self.config.max_enc_seq_length):\n prompt_query_sub = torch.mean(prompt_query_sub, dim=0).unsqueeze(0)\n else:\n prompt_query_sub = torch.mean(prompt_query_sub, dim=0).unsqueeze(0)\n prompt_query_sub_attention = encoder_attention[p_start_off:p_end_off]\n if prompt_query_sub_attention.shape[0] == 0:\n prompt_query_sub_attention = encoder_attention[0]\n prompt_query_sub_attention = torch.mean(prompt_query_sub_attention, dim=0).unsqueeze(0)\n att = (prompt_query_sub_attention * event_trigger_attention)\n att = att / (att.sum(1, keepdim=True) + 1e-5)\n context_rs = contract(\"ld,rl->rd\", decoder_context[i], att)\n prompt_query_sub = torch.tanh(self.contextual_merger(torch.cat((prompt_query_sub, context_rs), dim=-1)))\n start_query = (prompt_query_sub * self.w_prompt_start).unsqueeze(-1)\n end_query = (prompt_query_sub * self.w_prompt_end).unsqueeze(-1)\n start_logits = torch.bmm(context_output.unsqueeze(0), start_query).squeeze()\n end_logits = torch.bmm(context_output.unsqueeze(0), end_query).squeeze()\n start_logits_list.append(start_logits)\n end_logits_list.append(end_logits)\n output[arg_role] = [start_logits_list, end_logits_list]\n if self.training:\n target = target_info[i][ii][arg_role]\n predicted_spans = []\n for (start_logits, end_logits) in zip(start_logits_list, end_logits_list):\n if self.config.matching_method_train == 'accurate':\n predicted_spans.append(\n get_best_span(start_logits, end_logits,\n old_tok_to_new_tok_index,\n self.config.max_span_length)\n )\n elif self.config.matching_method_train == 'max':\n predicted_spans.append(\n get_best_span_simple(start_logits, end_logits)\n )\n else:\n raise AssertionError()\n target_spans = [[s, e] for (s, e) in zip(target[\"span_s\"], target[\"span_e\"])]\n if len(target_spans) < len(predicted_spans):\n pad_len = len(predicted_spans) - len(target_spans)\n target_spans += [[0, 0]] * pad_len\n target[\"span_s\"] += [0] * pad_len\n target[\"span_e\"] += [0] * pad_len\n if self.config.bipartite:\n idx_preds, idx_targets = hungarian_matcher(predicted_spans, target_spans)\n else:\n idx_preds = list(range(len(predicted_spans)))\n idx_targets = list(range(len(target_spans)))\n if len(idx_targets) > len(idx_preds):\n idx_targets = idx_targets[0:len(idx_preds)]\n idx_preds = torch.as_tensor(idx_preds, dtype=torch.int64)\n idx_targets = torch.as_tensor(idx_targets, dtype=torch.int64)\n cnt += len(idx_preds)\n start_loss = self.loss_fct(\n torch.stack(start_logits_list)[idx_preds],\n torch.LongTensor(target[\"span_s\"]).to(self.config.device)[idx_targets]\n )\n end_loss = self.loss_fct(\n torch.stack(end_logits_list)[idx_preds],\n torch.LongTensor(target[\"span_e\"]).to(self.config.device)[idx_targets]\n )\n batch_loss.append((start_loss + end_loss) / 2)\n list_output.append(output)\n logit_lists.append(list_output)\n if self.training:\n total_loss = total_loss + torch.sum(torch.stack(batch_loss)) / cnt\n if self.training:\n loss = total_loss / len(context_outputs)\n return loss, logit_lists\n else:\n loss = []\n return loss, logit_lists" } ] }, { "paper_id": 7, "paper_details": { "title": "Unifying Dual-Space Embedding for Entity Alignment via Contrastive Learning", "url": "https://arxiv.org/abs/2412.05028" }, "enviorment_name": "UniEA", "repo_original_url": "https://github.com/wonderCS1213/UniEA/tree/main", "project_path": "Benchmark/7-UniEA-main/UniEA-main", "file_organization": "\nUniEA-main/\n args/\n d_w_15k.json\n d_y_15k.json\n en_de_15k.json\n en_fr_15k.json\n data/\n OpenEA_dataset_v2.0/\n D_W_100K_V1/\n 721_5fold/\n 1/\n test_links\n train_links\n valid_links\n ...\n attr_triples_1\n attr_triples_2\n ent_links\n rel_triples_1\n rel_triples_2\n D_W_100K_V2/\n ...\n D_W_15K_V1/\n ...\n D_W_15K_V2/\n ...\n D_Y_100K_V1/\n ...\n D_Y_100K_V2/\n ...\n EN_DE_100K_V1/\n ...\n EN_DE_100K_V2/\n ...\n EN_FR_100K_V1/\n ...\n EN_FR_100K_V2/\n ...\n EN_DE_15K_V1/\n ...\n EN_DE_15K_V2/\n ...\n EN_FR_15K_V1/\n ...\n EN_FR_15K_V2/\n ...\n function_inputs.json\n manifolds/\n base.py\n euclidean.py\n hyperboloid.py\n __init__.py\n poincare.py\n README.md\n requirements.txt\n result/\n UniEA_lp.csv\n run_fold.py\n src/\n att_layers.py\n baselines.py\n dataset.py\n encoders.py\n hyp_layers.py\n layers.py\n loss.py\n model.py\n utils.py\n train.py\n utils/\n hyperbolicity.py\n __init__.py\n math_utils.py\n sinkhorn_cal.py\n", "latex_code_path": "Benchmark/7-UniEA-main/arXiv-2412.05028v1", "task_details": [ { "task_id": 0, "indent": 1, "script": "\npython train.py --task en_fr_15k\n", "latex_code": "\n\\subsection{Euclidean space embedding}\nThe ability of GAT to aggregate neighbor information in heterogeneous graphs has been well demonstrated \\citep{Meaformer,gsea}. We stack multiple layers of GAT to obtain Euclidean space embedding:\n% \\begin{small}\n\\begin{equation}\n\\begin{aligned}\n \\textbf{Z}^{\\mathbb{E}} &= [\\mathbf{z}^{(1)},...,\\mathbf{z}^{(L)}] \\\\\n &= GAT(\\textbf{W}_{m},\\textbf{M},\\textbf{z}^{\\mathbb{E},0}),\n\\end{aligned}\n\\end{equation}\n% \\end{small}\nwhere $ \\textbf{M} $ denotes the graph adjacency matrix, $\\textbf{W}_m \\in \\mathbb{R}^{d\\times d}$ is a diagonal weight matrix for linear transformation.\n\nDue to the varying importance of the neighborhoods aggregated by different layers of GAT.\nFor example, in Figure~\\ref{fig:des}, aggregating the first-order neighbors of ``Chris Evans'' is most beneficial. While aggregating higher-order neighbors can capture some implicit relationships of the entity, it often introduces noise.\nTherefore, \\citet{Xie2023ImprovingKG} introduce an attention mechanism \\citep{Vaswani2017AttentionIA} to assign different weights to the embeddings obtained from different layers:\n% \\begin{small}\n\\begin{equation}\n\\begin{aligned}\n&[\\hat{\\mathbf{z}}^{(1)},...,\\hat{\\mathbf{z}}^{(L)}]\\\\\n&=\\mathrm{softmax}(\\frac{(\\mathbf{Z}^{\\mathbb{E}}\\mathbf{W}_q)(\\mathbf{Z}^{\\mathbb{E}}\\mathbf{W}_k)^\\top}{\\sqrt{d_{e}}})\\mathbf{Z}^{\\mathbb{E}},\n\\end{aligned}\n\\end{equation}\n% \\end{small}\nwhere $ 1/\\sqrt{d_e} $ is the scaling factor, $\\mathbf{W}_q $ and $\\mathbf{W}_k$ are the learnable paramenter matrices. Finally, the Euclidean space embedding $\\overline{\\mathbf{z}^{\\mathbb{E}}} = \\frac1L\\sum_{l=1}^L\\hat{\\mathbf{z}}^{(l)} $.\n", "completion_path": "./src/model.py", "namespace": "src.model.euclidean_space_embedding", "type": "function", "signature_position": [ 67, 67 ], "body_position": [ 68, 84 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Apply dropout to the initial entity embeddings.\n# This corresponds to processing the initial embedding z^(E,0) before feeding it into GAT layers.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nembedding = dropout(entity_embedding)\n# [End Snippet 1]\n\n\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Iterate over each GAT layer in attentive_aggregators to aggregate neighbor information.\n# For each layer:\n# - Compute the new embedding using the GAT layer (which uses the graph adjacency matrix).\n# - Normalize the output to maintain a consistent scale.\n# - Apply dropout for regularization.\n# - Append the processed embedding to the list.\n# This process generates the set of embeddings that capture various orders of neighbor aggregation.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nembedding_list = []\nif res:\n embedding_list.append(embedding)\nfor layer in attentive_aggregators:\n embedding = layer(embedding, adj) # GraphMultiHeadAttLayer aggregates neighbor info using adj.\n embedding = F.normalize(embedding, dim=1, p=2)\n embedding_list.append(dropout(embedding))\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Apply the multi-head attention mechanism to the stacked embeddings. This computes weighted combinations of the layer embeddings, assigning different importance to each as described by the softmax attention mechanism in the LaTeX equation.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nif res:\n range_ = len(attentive_aggregators) + 1 # Include initial embedding if using residual connections\nelse:\n range_ = len(attentive_aggregators)\nembedding = torch.cat(embedding_list, dim=1).reshape(-1, range_, ent_dim)\nembedding, _ = multihead_attention(embedding, embedding, embedding)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Average the attended embeddings along the layer dimension to obtain a unified embedding. This operation reflects the final averaging (1/L \u2211 \ud835\udc67\u0302^(l)) step in the LaTeX formulation. Then return the final Euclidean space embedding.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nembedding = torch.mean(embedding, dim=1)\nembedding = embedding.squeeze(1)\n\nreturn embedding\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing/Mismatched Details:\n Missing in LaTeX:\n - Initial dropout on entity embeddings: Before entering the first GAT layer, the reference code applies dropout regularization. This dropout application reduces overfitting and enhances robustness but is absent from the LaTeX description.\n - Normalization of embeddings: After each GAT layer aggregation in the reference Python code, embeddings are explicitly L2-normalized to maintain consistent embedding scales.\n - Residual connection strategy: In the reference code, residual connections are handled explicitly by adding the initial embeddings separately into the embedding aggregation list when the residual option (res=True) is enabled.\n - Dimensionality handling for multi-head attention: The LaTeX description omits specifying how embeddings from multiple layers (with dimensions influenced by multiple attention heads, i.e., ent_dim * n_head) should be reshaped or concatenated before applying multi-head attention. The reference Python code explicitly reshapes concatenated embeddings into a three-dimensional tensor of shape (num_entities, num_layers, ent_dim) to align properly with multi-head attention computations.\n\n Mismatched with LaTeX:\n - Uses multi-head attention instead of single attention. \n", "Missing_details": [ "\n- Initial dropout on entity embeddings: Before entering the first GAT layer, the reference code applies dropout regularization. This dropout application reduces overfitting and enhances robustness but is absent from the LaTeX description. \n", "\n- Initial dropout on entity embeddings: Before entering the first GAT layer, the reference code applies dropout regularization. This dropout application reduces overfitting and enhances robustness but is absent from the LaTeX description. \n", "\n- Initial dropout on entity embeddings: Before entering the first GAT layer, the reference code applies dropout regularization. This dropout application reduces overfitting and enhances robustness but is absent from the LaTeX description. \n", "\n- Dimensionality handling for multi-head attention: The LaTeX description omits specifying how embeddings from multiple layers (with dimensions influenced by multiple attention heads, i.e., ent_dim * n_head) should be reshaped or concatenated before applying multi-head attention. The reference Python code explicitly reshapes concatenated embeddings into a three-dimensional tensor of shape (num_entities, num_layers, ent_dim) to align properly with multi-head attention computations.\n" ], "Mismatched_details": [ "\n- Uses multi-head attention instead of single attention.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - entity_embedding (torch.Tensor, Shape: [num_entities, embedding_dim]): Initial entity embeddings. \n - adj (torch.Tensor, shape: [num_entities, num_entities]): Adjacency matrix of the graph, representing connections between entities. \n - attentive_aggregators (nn.ModuleList): A list of GAT layers (GraphMultiHeadAttLayer instances). Each layer aggregates information from neighbors in the graph.\n - multihead_attention (MultiHeadAttention): A multi-head attention layer (MultiHeadAttention instance) used to weigh the importance of embeddings from different GAT layers.\n - n_head (int): Number of attention heads in the GAT layers and the multi-head attention layer.\n - ent_dim (int): The dimensionality of the entity embeddings.\n - dropout (torch.nn.Dropout): Dropout layer used for regularization.\n - res (bool): A flag indicating whether to use residual connections between GAT layers.\n", "Arguments_list": [ { "name": "entity_embedding", "string": "- entity_embedding (torch.Tensor, Shape: [num_entities, embedding_dim]): Initial entity embeddings. ", "dependency": null }, { "name": "adj", "string": "- adj (torch.Tensor, shape: [num_entities, num_entities]): Adjacency matrix of the graph, representing connections between entities. ", "dependency": null }, { "name": "attentive_aggregators", "string": "- attentive_aggregators (nn.ModuleList): A list of GAT layers (GraphMultiHeadAttLayer instances). Each layer aggregates information from neighbors in the graph.", "dependency": "src.layers.GraphMultiHeadAttLayer" }, { "name": "multihead_attention", "string": "- multihead_attention (MultiHeadAttention): A multi-head attention layer (MultiHeadAttention instance) used to weigh the importance of embeddings from different GAT layers.", "dependency": "src.layers.MultiHeadAttention" }, { "name": "n_head", "string": "- n_head (int): Number of attention heads in the GAT layers and the multi-head attention layer.", "dependency": null }, { "name": "ent_dim", "string": "- ent_dim (int): The dimensionality of the entity embeddings.", "dependency": null }, { "name": "dropout", "string": "- dropout (torch.nn.Dropout): Dropout layer used for regularization.", "dependency": null }, { "name": "res", "string": "- res (bool): A flag indicating whether to use residual connections between GAT layers.", "dependency": null } ] }, "dependency": { "string": "\nRepository Dependencies:\n Intra-File dependency: \n - None\n \n Cross-File dependency: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.cat\n - torch.mean\n - torch.nn.functional.normalize\n", "list": [ "torch.cat", "torch.mean", "torch.nn.functional.normalize" ] }, "Return": { "Return_String": "\nOutput Variables:\n - embedding (torch.Tensor): The final Euclidean space embedding after aggregating information from multiple GAT layers and applying the attention mechanism. Shape: (num_entities, ent_dim * n_head)\n", "Return_list": [ { "name": "embedding", "string": "- embedding (torch.Tensor): The final Euclidean space embedding after aggregating information from multiple GAT layers and applying the attention mechanism. Shape: (num_entities, ent_dim * n_head)", "dependency": null } ] }, "ori_python_file": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport manifolds\nfrom src.att_layers import GraphAttentionLayer\nimport src.hyp_layers as hyp_layers\nfrom src.layers import GraphConvolution, Linear, get_dim_act, GraphMultiHeadAttLayer, MultiHeadAttention\nfrom utils.sinkhorn_cal import sinkhorn\nfrom src.layers import DoubleEmbedding, GraphMultiHeadAttLayer, MultiHeadAttention\nfrom src.utils import set_random_seed\nimport numpy as np\nimport os, random\nos.environ['PYTHONHASHSEED'] = str(42)\nos.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\nnp.random.seed(42)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\ntorch.use_deterministic_algorithms(True)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nrandom.seed(42)\ntorch.cuda.synchronize()\ndef margin_based_loss(embeddings1, embeddings2, a1_align, a2_align, neg1_left, neg1_right, neg2_left, neg2_right, neg_samples_size, loss_norm, pos_margin=0.01, neg_margin=3, neg_param=0.2, only_pos=False):\n a1_align = np.array(a1_align)\n a2_align = np.array(a2_align)\n t = len(a1_align)\n L = np.ones((t, neg_samples_size)) * (a1_align.reshape((t,1)))\n a1_align = L.reshape((t*neg_samples_size,))\n R = np.ones((t, neg_samples_size)) * (a2_align.reshape((t,1)))\n a2_align = R.reshape((t*neg_samples_size,))\n a1_align = torch.tensor(a1_align, device=embeddings1.device)\n a2_align = torch.tensor(a2_align, device=embeddings1.device)\n neg1_left = torch.tensor(neg1_left, device=embeddings1.device)\n neg1_right = torch.tensor(neg1_right, device=embeddings1.device)\n neg2_left = torch.tensor(neg2_left, device=embeddings1.device)\n neg2_right = torch.tensor(neg2_right, device=embeddings1.device)\n left_x = embeddings1[a1_align.long()]\n right_x = embeddings2[a2_align.long()]\n if loss_norm == \"l1\":\n pos_loss = torch.abs(left_x - right_x)\n elif loss_norm == 'l2':\n pos_loss = torch.square(left_x - right_x)\n pos_loss = torch.sum(pos_loss, dim=1)\n left_x = embeddings1[neg1_left.long()]\n right_x = embeddings2[neg1_right.long()]\n if loss_norm == \"l1\":\n neg_loss_1 = torch.abs(left_x - right_x)\n elif loss_norm == 'l2':\n neg_loss_1 = torch.square(left_x - right_x)\n neg_loss_1 = torch.sum(neg_loss_1, dim=1)\n left_x = embeddings1[neg2_left.long()]\n right_x = embeddings2[neg2_right.long()]\n if loss_norm == \"l1\":\n neg_loss_2 = torch.abs(left_x - right_x)\n elif loss_norm == 'l2':\n neg_loss_2 = torch.square(left_x - right_x)\n neg_loss_2 = torch.sum(neg_loss_2, dim=1)\n loss1 = F.relu(pos_loss + neg_margin - neg_loss_1)\n loss2 = F.relu(pos_loss + neg_margin - neg_loss_2)\n loss1 = torch.sum(loss1)\n loss2 = torch.sum(loss2)\n loss = loss1 + loss2\n return loss\n\ndef euclidean_space_embedding(entity_embedding, adj, attentive_aggregators, multihead_attention, n_head, ent_dim, dropout, res):\n embedding = dropout(entity_embedding)\n embedding_list = []\n if res:\n embedding_list.append(embedding)\n for layer in attentive_aggregators:\n embedding = layer(embedding, adj)\n embedding = F.normalize(embedding, dim=1, p=2)\n embedding_list.append(dropout(embedding))\n if res:\n range_ = len(attentive_aggregators) + 1\n else:\n range_ = len(attentive_aggregators)\n embedding = torch.cat(embedding_list, dim=1).reshape(-1, range_, ent_dim)\n embedding, _ = multihead_attention(embedding, embedding, embedding)\n embedding = torch.mean(embedding, dim=1)\n embedding = embedding.squeeze(1)\n return embedding\n\ndef hyperbolic_space_embedding(entity_embedding, adj, manifold, curvatures, layers):\n x_tan = manifold.proj_tan0(entity_embedding, curvatures[0])\n x_hyp = manifold.expmap0(x_tan, c=curvatures[0])\n input_ = (x_hyp, adj)\n output, _ = layers.forward(input_)\n output = manifold.logmap0(output, c=curvatures[0])\n return output\n\ndef relation_encoding_and_fusion(rel_adj_sr, rel_adj_tg, sr_rel_embedding, tg_rel_embedding, direct):\n if direct:\n rel_adj_sr_in, rel_adj_sr_out = rel_adj_sr[0], rel_adj_sr[1]\n rel_rowsum_sr_in = torch.sum(rel_adj_sr_in.to_dense(), dim=-1).unsqueeze(-1)\n rel_rowsum_sr_out = torch.sum(rel_adj_sr_out.to_dense(), dim=-1).unsqueeze(-1)\n sr_rel_embedding_in = torch.mm(rel_adj_sr_in, sr_rel_embedding)\n sr_rel_embedding_in = sr_rel_embedding_in.div(rel_rowsum_sr_in + 1e-5)\n sr_rel_embedding_out = torch.mm(rel_adj_sr_out, sr_rel_embedding)\n sr_rel_embedding_out = sr_rel_embedding_out.div(rel_rowsum_sr_out + 1e-5)\n sr_rel_embedding = torch.cat([sr_rel_embedding_in, sr_rel_embedding_out], dim=-1)\n rel_adj_tg_in, rel_adj_tg_out = rel_adj_tg[0], rel_adj_tg[1]\n rel_rowsum_tg_in = torch.sum(rel_adj_tg_in.to_dense(), dim=-1).unsqueeze(-1)\n rel_rowsum_tg_out = torch.sum(rel_adj_tg_out.to_dense(), dim=-1).unsqueeze(-1)\n tg_rel_embedding_in = torch.mm(rel_adj_tg_in, tg_rel_embedding)\n tg_rel_embedding_in = tg_rel_embedding_in.div(rel_rowsum_tg_in + 1e-5)\n tg_rel_embedding_out = torch.mm(rel_adj_tg_out, tg_rel_embedding)\n tg_rel_embedding_out = tg_rel_embedding_out.div(rel_rowsum_tg_out + 1e-5)\n tg_rel_embedding = torch.cat([tg_rel_embedding_in, tg_rel_embedding_out], dim=-1)\n else:\n rel_rowsum_sr = torch.sum(rel_adj_sr.to_dense(), dim=-1).unsqueeze(-1)\n rel_rowsum_tg = torch.sum(rel_adj_tg.to_dense(), dim=-1).unsqueeze(-1)\n sr_rel_embedding = torch.mm(rel_adj_sr, sr_rel_embedding)\n tg_rel_embedding = torch.mm(rel_adj_tg, tg_rel_embedding)\n sr_rel_embedding = sr_rel_embedding.div(rel_rowsum_sr)\n tg_rel_embedding = tg_rel_embedding.div(rel_rowsum_tg)\n return sr_rel_embedding, tg_rel_embedding\n\nclass UniEA(nn.Module):\n def __init__(self, num_sr, num_tg, adj_sr, adj_tg, rel_num, rel_adj_sr, rel_adj_tg, args) -> None:\n super().__init__()\n self.num_sr = num_sr\n self.num_tg = num_tg\n self.adj_sr = adj_sr\n self.adj_tg = adj_tg\n self.rel_num = rel_num\n self.rel_adj_sr = rel_adj_sr\n self.rel_adj_tg = rel_adj_tg\n self.ent_dim = args.ent_dim\n self.rel_dim = args.rel_dim\n self.n_head = args.n_head\n self.layer = args.layer\n self.direct = args.direct\n self.res = args.res\n self.manifold_name = args.manifold\n if args.c is not None:\n self.c = torch.tensor([args.c])\n if not args.device == 'cuda':\n self.c = self.c.to(args.device)\n else:\n self.c = nn.Parameter(torch.Tensor([1.]))\n self.manifold = getattr(manifolds, self.manifold_name)()\n assert args.layer > 1\n dims, acts, self.curvatures = hyp_layers.get_dim_act_curv(args)\n self.curvatures.append(self.c)\n hgc_layers = []\n for i in range(len(dims) - 1):\n c_in, c_out = self.curvatures[i], self.curvatures[i + 1]\n in_dim, out_dim = dims[i], dims[i + 1]\n act = acts[i]\n hgc_layers.append(\n hyp_layers.HyperbolicGraphConvolution(\n self.manifold, in_dim, out_dim, c_in, c_out, args.dropout, act, args.bias, args.use_att,\n args.local_agg\n )\n )\n self.layers = nn.Sequential(*hgc_layers)\n self.encode_graph = True\n self.scale = 300\n self.mats_hyper = nn.Parameter(torch.Tensor(args.dim, self.ent_dim), requires_grad=True)\n torch.manual_seed(42)\n nn.init.xavier_uniform_(self.mats_hyper)\n self.mats_hyper2 = nn.Parameter(torch.Tensor(args.dim, self.ent_dim), requires_grad=True)\n torch.manual_seed(42)\n nn.init.xavier_uniform_(self.mats_hyper2)\n self.dropout = nn.Dropout(args.dropout)\n self.entity_embedding = DoubleEmbedding(num_sr=self.num_sr, num_tg=self.num_tg, embedding_dim=self.ent_dim, init_type=args.init_type)\n self.hyper_entity_embedding = DoubleEmbedding(num_sr=self.num_sr, num_tg=self.num_tg, embedding_dim=args.dim,\n init_type=args.init_type)\n self.relation_embedding = DoubleEmbedding(num_sr=self.rel_num, num_tg=self.rel_num, embedding_dim=self.rel_dim, init_type=args.init_type)\n self.attentive_aggregators = nn.ModuleList([GraphMultiHeadAttLayer(in_features=self.ent_dim, out_features=self.ent_dim, n_head=self.n_head, dropout=args.dropout) for i in range(self.layer)])\n self.multihead_attention = MultiHeadAttention(\n n_head=self.n_head,\n d_model=self.ent_dim,\n d_k=self.ent_dim,\n d_v=self.ent_dim,\n dropout=args.dropout\n )\n if self.direct:\n self.proj_head = nn.Sequential(\n nn.Linear(self.ent_dim*self.n_head + self.rel_dim*2, self.ent_dim),\n nn.ReLU(),\n )\n else:\n self.proj_head = nn.Sequential(\n nn.Linear(self.ent_dim*self.n_head + self.rel_dim, self.ent_dim),\n nn.ReLU(),\n )\n \n def cal_ot(self, mm_embeddings, st_embeddings, delta_ot):\n device = delta_ot.device\n number = 10\n mm_dim = mm_embeddings.shape[-1]\n st_dim = st_embeddings.shape[-1]\n mm_dis = torch.ones_like(mm_embeddings[0, :])\n mm_dis = mm_dis / mm_dis.shape[-1]\n st_dis = torch.ones_like(st_embeddings[0, :])\n st_dis = st_dis / st_dis.shape[-1]\n matrix_temp = torch.zeros((number, mm_dim, st_dim))\n with torch.no_grad():\n for i in range(number):\n cost = (mm_embeddings[i, :].reshape(-1, mm_dim) - st_embeddings[i, :].reshape(st_dim,\n -1)) ** 2 * self.scale\n matrix_temp[i, :, :] = sinkhorn(mm_dis, st_dis, cost.t())[0].t()\n return matrix_temp.mean(dim=0).to(device) * st_dim * self.scale + delta_ot\n \n def forward(self, aug_adj1=None, aug_rel_adj1=None, aug_adj2=None, aug_rel_adj2=None, phase=\"norm\"):\n if phase in [\"norm\", \"eval\"]:\n adj_sr, adj_tg, rel_adj_sr, rel_adj_tg = self.adj_sr, self.adj_tg, self.rel_adj_sr, self.rel_adj_tg\n elif phase == \"augment\":\n adj_sr, adj_tg, rel_adj_sr, rel_adj_tg = aug_adj1, aug_adj2, aug_rel_adj1, aug_rel_adj2\n sr_embedding, tg_embedding = self.entity_embedding.weight\n sr_embedding, tg_embedding = self.dropout(sr_embedding), self.dropout(tg_embedding)\n hyper_sr_embedding, hyper_tg_embedding = self.entity_embedding.weight\n sr_rel_embedding, tg_rel_embedding = self.relation_embedding.weight\n sr_rel_embedding, tg_rel_embedding = self.dropout(sr_rel_embedding), self.dropout(tg_rel_embedding)\n sr_rel_embedding, tg_rel_embedding = relation_encoding_and_fusion(rel_adj_sr, rel_adj_tg, sr_rel_embedding, tg_rel_embedding, self.direct)\n sr_embedding = euclidean_space_embedding(sr_embedding, adj_sr, self.attentive_aggregators, self.multihead_attention, self.n_head, self.ent_dim, self.dropout, self.res)\n tg_embedding = euclidean_space_embedding(tg_embedding, adj_tg, self.attentive_aggregators, self.multihead_attention, self.n_head, self.ent_dim, self.dropout, self.res)\n hyper_sr_embedding = hyperbolic_space_embedding(hyper_sr_embedding, adj_sr, self.manifold, self.curvatures, self.layers)\n hyper_tg_embedding = hyperbolic_space_embedding(hyper_tg_embedding, adj_tg, self.manifold, self.curvatures, self.layers)\n sr_embedding = torch.cat([sr_embedding, sr_rel_embedding], dim=-1)\n tg_embedding = torch.cat([tg_embedding, tg_rel_embedding], dim=-1)\n hyper_sr_embedding = torch.cat([hyper_sr_embedding, sr_rel_embedding], dim=-1)\n hyper_tg_embedding = torch.cat([hyper_tg_embedding, tg_rel_embedding], dim=-1)\n return sr_embedding, tg_embedding, hyper_sr_embedding, hyper_tg_embedding\n \n def contrastive_loss(self, embeddings1, embeddings2, ent_num, sim_method=\"cosine\", t=0.08):\n if sim_method == \"cosine\":\n embeddings1_abs = embeddings1.norm(dim=1)\n embeddings2_abs = embeddings2.norm(dim=1)\n logits = torch.einsum('ik,jk->ij', embeddings1, embeddings2) / (\n torch.einsum('i,j->ij', embeddings1_abs, embeddings2_abs) + 1e-5\n )\n logits = logits / t\n elif sim_method == \"inner\":\n logits = torch.mm(embeddings1, embeddings2.T)\n labels = torch.arange(ent_num).to(embeddings1.device)\n loss_1 = F.cross_entropy(logits, labels)\n loss_2 = F.cross_entropy(logits.T, labels)\n loss = (loss_1 + loss_2) / 2\n return loss" }, { "task_id": 1, "indent": 1, "script": "\npython train.py --task en_fr_15k\n", "latex_code": "\n\\subsection{Hyperbolic Space embedding}\nOur method equips HGCN \\citep{hgcn} to learn the hierarchical structure of graphs in hyperbolic space.\n% We map the initialized Euclidean entity embeddings $ z^{\\mathbb{E}} $ to hyperbolic space, followed by feature transformation, feature aggregation, and non-linear activation in hyperbolic space. \n% Finally, the hyperbolic embeddings are mapped back to Euclidean space.\n\nSpecifically, we project Euclidean space embeddings $ \\mathbf{z}^{\\mathbb{E}} $ to hyperbolic space using exponential map (Equation \\ref{exp}):\n\\begin{equation}\n \\mathbf{z}^{\\mathbb{H}} = \\exp^c_o(\\mathbf{z}^{\\mathbb{E}}),\n\\end{equation}\nwhere $\\mathbf{z}^{\\mathbb{H}} \\in H^{(d,c)}$, in other words, we obtain the first layer of embedding $ \\mathbf{z}^{\\mathbb{H},{0}}$ in hyperbolic space.\n\nFor the hyperbolic space embedding of the $l$-th layer, by hyperbolic feature aggregation, we can get the hyperbolic embedding of the next layer.\nThe hyperbolic aggregation process is as follows:\n\\begin{equation}\n\\label{agg}\n \\mathbf{z}^{\\mathbb{H},{l+1}}=\\exp_o^{c}(\\sigma({\\textbf{A}} \\log_o^{c}(\\mathbf{z}^{\\mathbb{H},{l}})\\textbf{W}_{l})).\n\\end{equation}\n\\textbf{A} represents the symmetric normalized adjacency matrix, $ \\sigma $ is $ReLU(\\cdot)$ and $\\textbf{W}_l$ is a trainable weight matrix.\n\nFor example, for the input $ \\mathbf{z}^{\\mathbb{H},{0}}$ in $0$-th layer, we can get $ \\mathbf{z}^{\\mathbb{H},{1}}$ using Equation \\ref{agg}.\n\nFinally, we can obtain the final output $\\mathbf{z}^{\\mathbb{H},{L}}$ in Hyperbolic Space.\nThe `$L$' is a hyper-parameter denoting the number of layers of the HGCN.\n", "completion_path": "./src/model.py", "namespace": "src.model.hyperbolic_space_embedding", "type": "function", "signature_position": [ 86, 86 ], "body_position": [ 87, 92 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: This line projects the Euclidean embeddings to the tangent space at the origin, aligning with the preliminary step before applying the exponential map in the LaTeX snippet. This tangent projection step is an additional safeguard to ensure valid curvature-based operations.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nx_tan = manifold.proj_tan0(entity_embedding, curvatures[0])\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Applies the exponential map to project the tangent space representation x_tan to the hyperbolic space. This corresponds to \\(\\mathbf{z}^{\\mathbb{H}} = \\exp^c_o(\\mathbf{z}^{\\mathbb{E}})\\).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nx_hyp = manifold.expmap0(x_tan, c=curvatures[0])\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Feeds (x_hyp, adj) into the sequence of hyperbolic GCN layers. These layers\n# implement the hyperbolic feature aggregation, i.e., \\(\\mathbf{z}^{\\mathbb{H},{l+1}} = \\exp_o^{c}(\\sigma(\\textbf{A}\\,\\log_o^{c}(\\mathbf{z}^{\\mathbb{H},{l}})\\textbf{W}_{l}))\\).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\ninput_ = (x_hyp, adj)\noutput, _ = layers.forward(input_)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Maps the final hyperbolic embeddings back to a Euclidean representation using the logarithmic map. This corresponds to the final step in the LaTeX description, ensuring that the output can be processed with conventional Euclidean operations.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\noutput = manifold.logmap0(output, c=curvatures[0])\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Returns the final hyperbolic embeddings (in Euclidean representation).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nreturn output\n# [End Snippet 5]\n", "Missing_Mismatched_details": { "string": "\nMissing/Mismatched Details:\n Missing in LaTeX:\n - The LaTeX description omits the critical step of projecting the initial Euclidean embeddings onto the tangent space at the origin using the tangent space projection. The reference Python code explicitly includes this step:\n 1. Take the initial Euclidean embeddings.\n 2. Project these embeddings onto the tangent space at the origin using the manifold-specific tangent projection.\n 3. After obtaining the tangent space representation, apply the exponential map to correctly position these embeddings within hyperbolic space.\n - The LaTeX description does not explicitly state the final step of mapping the embeddings from hyperbolic space back to Euclidean space using the logarithmic map. Although briefly mentioned in a commented-out section, this final mapping is essential to match the reference implementation's results precisely:\n 1. After processing through all HGCN layers, take the final embeddings in hyperbolic space.\n 2. Apply the logarithmic map to project embeddings back to the Euclidean space for compatibility with Euclidean-based downstream tasks.\n\n Mismatched with LaTeX:\n - None\n", "Missing_details": [ "\n- The LaTeX description omits the critical step of projecting the initial Euclidean embeddings onto the tangent space at the origin using the tangent space projection. The reference Python code explicitly includes this step:\n 1. Take the initial Euclidean embeddings.\n 2. Project these embeddings onto the tangent space at the origin using the manifold-specific tangent projection.\n 3. After obtaining the tangent space representation, apply the exponential map to correctly position these embeddings within hyperbolic space. \n", "\n- The LaTeX description does not explicitly state the final step of mapping the embeddings from hyperbolic space back to Euclidean space using the logarithmic map. Although briefly mentioned in a commented-out section, this final mapping is essential to match the reference implementation's results precisely:\n 1. After processing through all HGCN layers, take the final embeddings in hyperbolic space.\n 2. Apply the logarithmic map to project embeddings back to the Euclidean space for compatibility with Euclidean-based downstream tasks.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - entity_embedding (torch.Tensor, shape: [num_entities, embedding_dim]): Initial entity embeddings in Euclidean space. \n - adj (torch.Tensor, shape:[num_entities, num_entities]): Adjacency matrix of the graph.\n - manifold (manifolds.poincare.poincareBall): The hyperbolic manifold object.\n - curvatures (list[torch.Tensor]): A list of curvature values (floats) for each layer of the HGCN.\n - layers (nn.Sequential): A sequence of HGCN layers (instances of hyp_layers.HyperbolicGraphConvolution).\n", "Arguments_list": [ { "name": "entity_embedding", "string": "- entity_embedding (torch.Tensor, shape: [num_entities, embedding_dim]): Initial entity embeddings in Euclidean space.", "dependency": null }, { "name": "adj", "string": "- adj (torch.Tensor, shape:[num_entities, num_entities]): Adjacency matrix of the graph.", "dependency": null }, { "name": "manifold", "string": "- manifold (manifolds.poincare.poincareBall): The hyperbolic manifold object.", "dependency": "manifolds.poincare.poincareBall" }, { "name": "curvatures", "string": "- curvatures (list[torch.Tensor]): A list of curvature values (floats) for each layer of the HGCN.", "dependency": null }, { "name": "layers", "string": "- layers (nn.Sequential): A sequence of HGCN layers (instances of hyp_layers.HyperbolicGraphConvolution).", "dependency": "src.hyp_layers.HyperbolicGraphConvolution" } ] }, "dependency": { "string": "\nDependencies:\n Intra-File dependency:\n - None\n \n Cross-File dependency:\n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs: \n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - output (torch.Tensor, Shape: [num_entities, output_dim]): The final hyperbolic space embedding, projected back to a Euclidean representation.\n", "Return_list": [ { "name": "output", "string": "- output (torch.Tensor, Shape: [num_entities, output_dim]): The final hyperbolic space embedding, projected back to a Euclidean representation.", "dependency": null } ] }, "ori_python_file": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport manifolds\nfrom src.att_layers import GraphAttentionLayer\nimport src.hyp_layers as hyp_layers\nfrom src.layers import GraphConvolution, Linear, get_dim_act, GraphMultiHeadAttLayer, MultiHeadAttention\nfrom utils.sinkhorn_cal import sinkhorn\nfrom src.layers import DoubleEmbedding, GraphMultiHeadAttLayer, MultiHeadAttention\nfrom src.utils import set_random_seed\nimport numpy as np\nimport os, random\nos.environ['PYTHONHASHSEED'] = str(42)\nos.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\nnp.random.seed(42)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\ntorch.use_deterministic_algorithms(True)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nrandom.seed(42)\ntorch.cuda.synchronize()\ndef margin_based_loss(embeddings1, embeddings2, a1_align, a2_align, neg1_left, neg1_right, neg2_left, neg2_right, neg_samples_size, loss_norm, pos_margin=0.01, neg_margin=3, neg_param=0.2, only_pos=False):\n a1_align = np.array(a1_align)\n a2_align = np.array(a2_align)\n t = len(a1_align)\n L = np.ones((t, neg_samples_size)) * (a1_align.reshape((t,1)))\n a1_align = L.reshape((t*neg_samples_size,))\n R = np.ones((t, neg_samples_size)) * (a2_align.reshape((t,1)))\n a2_align = R.reshape((t*neg_samples_size,))\n a1_align = torch.tensor(a1_align, device=embeddings1.device)\n a2_align = torch.tensor(a2_align, device=embeddings1.device)\n neg1_left = torch.tensor(neg1_left, device=embeddings1.device)\n neg1_right = torch.tensor(neg1_right, device=embeddings1.device)\n neg2_left = torch.tensor(neg2_left, device=embeddings1.device)\n neg2_right = torch.tensor(neg2_right, device=embeddings1.device)\n left_x = embeddings1[a1_align.long()]\n right_x = embeddings2[a2_align.long()]\n if loss_norm == \"l1\":\n pos_loss = torch.abs(left_x - right_x)\n elif loss_norm == 'l2':\n pos_loss = torch.square(left_x - right_x)\n pos_loss = torch.sum(pos_loss, dim=1)\n left_x = embeddings1[neg1_left.long()]\n right_x = embeddings2[neg1_right.long()]\n if loss_norm == \"l1\":\n neg_loss_1 = torch.abs(left_x - right_x)\n elif loss_norm == 'l2':\n neg_loss_1 = torch.square(left_x - right_x)\n neg_loss_1 = torch.sum(neg_loss_1, dim=1)\n left_x = embeddings1[neg2_left.long()]\n right_x = embeddings2[neg2_right.long()]\n if loss_norm == \"l1\":\n neg_loss_2 = torch.abs(left_x - right_x)\n elif loss_norm == 'l2':\n neg_loss_2 = torch.square(left_x - right_x)\n neg_loss_2 = torch.sum(neg_loss_2, dim=1)\n loss1 = F.relu(pos_loss + neg_margin - neg_loss_1)\n loss2 = F.relu(pos_loss + neg_margin - neg_loss_2)\n loss1 = torch.sum(loss1)\n loss2 = torch.sum(loss2)\n loss = loss1 + loss2\n return loss\n\ndef euclidean_space_embedding(entity_embedding, adj, attentive_aggregators, multihead_attention, n_head, ent_dim, dropout, res):\n embedding = dropout(entity_embedding)\n embedding_list = []\n if res:\n embedding_list.append(embedding)\n for layer in attentive_aggregators:\n embedding = layer(embedding, adj)\n embedding = F.normalize(embedding, dim=1, p=2)\n embedding_list.append(dropout(embedding))\n if res:\n range_ = len(attentive_aggregators) + 1\n else:\n range_ = len(attentive_aggregators)\n embedding = torch.cat(embedding_list, dim=1).reshape(-1, range_, ent_dim)\n embedding, _ = multihead_attention(embedding, embedding, embedding)\n embedding = torch.mean(embedding, dim=1)\n embedding = embedding.squeeze(1)\n return embedding\n\ndef hyperbolic_space_embedding(entity_embedding, adj, manifold, curvatures, layers):\n x_tan = manifold.proj_tan0(entity_embedding, curvatures[0])\n x_hyp = manifold.expmap0(x_tan, c=curvatures[0])\n input_ = (x_hyp, adj)\n output, _ = layers.forward(input_)\n output = manifold.logmap0(output, c=curvatures[0])\n return output\n\ndef relation_encoding_and_fusion(rel_adj_sr, rel_adj_tg, sr_rel_embedding, tg_rel_embedding, direct):\n if direct:\n rel_adj_sr_in, rel_adj_sr_out = rel_adj_sr[0], rel_adj_sr[1]\n rel_rowsum_sr_in = torch.sum(rel_adj_sr_in.to_dense(), dim=-1).unsqueeze(-1)\n rel_rowsum_sr_out = torch.sum(rel_adj_sr_out.to_dense(), dim=-1).unsqueeze(-1)\n sr_rel_embedding_in = torch.mm(rel_adj_sr_in, sr_rel_embedding)\n sr_rel_embedding_in = sr_rel_embedding_in.div(rel_rowsum_sr_in + 1e-5)\n sr_rel_embedding_out = torch.mm(rel_adj_sr_out, sr_rel_embedding)\n sr_rel_embedding_out = sr_rel_embedding_out.div(rel_rowsum_sr_out + 1e-5)\n sr_rel_embedding = torch.cat([sr_rel_embedding_in, sr_rel_embedding_out], dim=-1)\n rel_adj_tg_in, rel_adj_tg_out = rel_adj_tg[0], rel_adj_tg[1]\n rel_rowsum_tg_in = torch.sum(rel_adj_tg_in.to_dense(), dim=-1).unsqueeze(-1)\n rel_rowsum_tg_out = torch.sum(rel_adj_tg_out.to_dense(), dim=-1).unsqueeze(-1)\n tg_rel_embedding_in = torch.mm(rel_adj_tg_in, tg_rel_embedding)\n tg_rel_embedding_in = tg_rel_embedding_in.div(rel_rowsum_tg_in + 1e-5)\n tg_rel_embedding_out = torch.mm(rel_adj_tg_out, tg_rel_embedding)\n tg_rel_embedding_out = tg_rel_embedding_out.div(rel_rowsum_tg_out + 1e-5)\n tg_rel_embedding = torch.cat([tg_rel_embedding_in, tg_rel_embedding_out], dim=-1)\n else:\n rel_rowsum_sr = torch.sum(rel_adj_sr.to_dense(), dim=-1).unsqueeze(-1)\n rel_rowsum_tg = torch.sum(rel_adj_tg.to_dense(), dim=-1).unsqueeze(-1)\n sr_rel_embedding = torch.mm(rel_adj_sr, sr_rel_embedding)\n tg_rel_embedding = torch.mm(rel_adj_tg, tg_rel_embedding)\n sr_rel_embedding = sr_rel_embedding.div(rel_rowsum_sr)\n tg_rel_embedding = tg_rel_embedding.div(rel_rowsum_tg)\n return sr_rel_embedding, tg_rel_embedding\n\nclass UniEA(nn.Module):\n def __init__(self, num_sr, num_tg, adj_sr, adj_tg, rel_num, rel_adj_sr, rel_adj_tg, args) -> None:\n super().__init__()\n self.num_sr = num_sr\n self.num_tg = num_tg\n self.adj_sr = adj_sr\n self.adj_tg = adj_tg\n self.rel_num = rel_num\n self.rel_adj_sr = rel_adj_sr\n self.rel_adj_tg = rel_adj_tg\n self.ent_dim = args.ent_dim\n self.rel_dim = args.rel_dim\n self.n_head = args.n_head\n self.layer = args.layer\n self.direct = args.direct\n self.res = args.res\n self.manifold_name = args.manifold\n if args.c is not None:\n self.c = torch.tensor([args.c])\n if not args.device == 'cuda':\n self.c = self.c.to(args.device)\n else:\n self.c = nn.Parameter(torch.Tensor([1.]))\n self.manifold = getattr(manifolds, self.manifold_name)()\n assert args.layer > 1\n dims, acts, self.curvatures = hyp_layers.get_dim_act_curv(args)\n self.curvatures.append(self.c)\n hgc_layers = []\n for i in range(len(dims) - 1):\n c_in, c_out = self.curvatures[i], self.curvatures[i + 1]\n in_dim, out_dim = dims[i], dims[i + 1]\n act = acts[i]\n hgc_layers.append(\n hyp_layers.HyperbolicGraphConvolution(\n self.manifold, in_dim, out_dim, c_in, c_out, args.dropout, act, args.bias, args.use_att,\n args.local_agg\n )\n )\n self.layers = nn.Sequential(*hgc_layers)\n self.encode_graph = True\n self.scale = 300\n self.mats_hyper = nn.Parameter(torch.Tensor(args.dim, self.ent_dim), requires_grad=True)\n torch.manual_seed(42)\n nn.init.xavier_uniform_(self.mats_hyper)\n self.mats_hyper2 = nn.Parameter(torch.Tensor(args.dim, self.ent_dim), requires_grad=True)\n torch.manual_seed(42)\n nn.init.xavier_uniform_(self.mats_hyper2)\n self.dropout = nn.Dropout(args.dropout)\n self.entity_embedding = DoubleEmbedding(num_sr=self.num_sr, num_tg=self.num_tg, embedding_dim=self.ent_dim, init_type=args.init_type)\n self.hyper_entity_embedding = DoubleEmbedding(num_sr=self.num_sr, num_tg=self.num_tg, embedding_dim=args.dim,\n init_type=args.init_type)\n self.relation_embedding = DoubleEmbedding(num_sr=self.rel_num, num_tg=self.rel_num, embedding_dim=self.rel_dim, init_type=args.init_type)\n self.attentive_aggregators = nn.ModuleList([GraphMultiHeadAttLayer(in_features=self.ent_dim, out_features=self.ent_dim, n_head=self.n_head, dropout=args.dropout) for i in range(self.layer)])\n self.multihead_attention = MultiHeadAttention(\n n_head=self.n_head,\n d_model=self.ent_dim,\n d_k=self.ent_dim,\n d_v=self.ent_dim,\n dropout=args.dropout\n )\n if self.direct:\n self.proj_head = nn.Sequential(\n nn.Linear(self.ent_dim*self.n_head + self.rel_dim*2, self.ent_dim),\n nn.ReLU(),\n )\n else:\n self.proj_head = nn.Sequential(\n nn.Linear(self.ent_dim*self.n_head + self.rel_dim, self.ent_dim),\n nn.ReLU(),\n )\n \n def cal_ot(self, mm_embeddings, st_embeddings, delta_ot):\n device = delta_ot.device\n number = 10\n mm_dim = mm_embeddings.shape[-1]\n st_dim = st_embeddings.shape[-1]\n mm_dis = torch.ones_like(mm_embeddings[0, :])\n mm_dis = mm_dis / mm_dis.shape[-1]\n st_dis = torch.ones_like(st_embeddings[0, :])\n st_dis = st_dis / st_dis.shape[-1]\n matrix_temp = torch.zeros((number, mm_dim, st_dim))\n with torch.no_grad():\n for i in range(number):\n cost = (mm_embeddings[i, :].reshape(-1, mm_dim) - st_embeddings[i, :].reshape(st_dim,\n -1)) ** 2 * self.scale\n matrix_temp[i, :, :] = sinkhorn(mm_dis, st_dis, cost.t())[0].t()\n return matrix_temp.mean(dim=0).to(device) * st_dim * self.scale + delta_ot\n \n def forward(self, aug_adj1=None, aug_rel_adj1=None, aug_adj2=None, aug_rel_adj2=None, phase=\"norm\"):\n if phase in [\"norm\", \"eval\"]:\n adj_sr, adj_tg, rel_adj_sr, rel_adj_tg = self.adj_sr, self.adj_tg, self.rel_adj_sr, self.rel_adj_tg\n elif phase == \"augment\":\n adj_sr, adj_tg, rel_adj_sr, rel_adj_tg = aug_adj1, aug_adj2, aug_rel_adj1, aug_rel_adj2\n sr_embedding, tg_embedding = self.entity_embedding.weight\n sr_embedding, tg_embedding = self.dropout(sr_embedding), self.dropout(tg_embedding)\n hyper_sr_embedding, hyper_tg_embedding = self.entity_embedding.weight\n sr_rel_embedding, tg_rel_embedding = self.relation_embedding.weight\n sr_rel_embedding, tg_rel_embedding = self.dropout(sr_rel_embedding), self.dropout(tg_rel_embedding)\n sr_rel_embedding, tg_rel_embedding = relation_encoding_and_fusion(rel_adj_sr, rel_adj_tg, sr_rel_embedding, tg_rel_embedding, self.direct)\n sr_embedding = euclidean_space_embedding(sr_embedding, adj_sr, self.attentive_aggregators, self.multihead_attention, self.n_head, self.ent_dim, self.dropout, self.res)\n tg_embedding = euclidean_space_embedding(tg_embedding, adj_tg, self.attentive_aggregators, self.multihead_attention, self.n_head, self.ent_dim, self.dropout, self.res)\n hyper_sr_embedding = hyperbolic_space_embedding(hyper_sr_embedding, adj_sr, self.manifold, self.curvatures, self.layers)\n hyper_tg_embedding = hyperbolic_space_embedding(hyper_tg_embedding, adj_tg, self.manifold, self.curvatures, self.layers)\n sr_embedding = torch.cat([sr_embedding, sr_rel_embedding], dim=-1)\n tg_embedding = torch.cat([tg_embedding, tg_rel_embedding], dim=-1)\n hyper_sr_embedding = torch.cat([hyper_sr_embedding, sr_rel_embedding], dim=-1)\n hyper_tg_embedding = torch.cat([hyper_tg_embedding, tg_rel_embedding], dim=-1)\n return sr_embedding, tg_embedding, hyper_sr_embedding, hyper_tg_embedding\n \n def contrastive_loss(self, embeddings1, embeddings2, ent_num, sim_method=\"cosine\", t=0.08):\n if sim_method == \"cosine\":\n embeddings1_abs = embeddings1.norm(dim=1)\n embeddings2_abs = embeddings2.norm(dim=1)\n logits = torch.einsum('ik,jk->ij', embeddings1, embeddings2) / (\n torch.einsum('i,j->ij', embeddings1_abs, embeddings2_abs) + 1e-5\n )\n logits = logits / t\n elif sim_method == \"inner\":\n logits = torch.mm(embeddings1, embeddings2.T)\n labels = torch.arange(ent_num).to(embeddings1.device)\n loss_1 = F.cross_entropy(logits, labels)\n loss_2 = F.cross_entropy(logits.T, labels)\n loss = (loss_1 + loss_2) / 2\n return loss" }, { "task_id": 2, "indent": 1, "script": "\npython train.py --task en_fr_15k\n", "latex_code": "\n\\subsection{Relation encoding and fusion}\nThe same entities often share similar relations, and relational semantic information is also highly beneficial for EA.\n\\citet{Mao2020MRAEAAE} reveals that relying solely on the inflow direction to accumulate neighboring information through directed edges is insufficient. Accumulating information from the outflow direction as well would be highly beneficial.\nThis idea facilitates the bridging and propagation of more information in such a sparse graph.\nHence, following this work, we use both in-degree and out-degree relation encoders to learn the representation of relations:\n\\begin{equation}\n\\overline{r}_{e_i}=\\frac{\\textbf{A}_{e_i}^{rel_{in}}\\textbf{r}}{|N_{{e_i}}^{in}|}\\oplus\\frac{\\textbf{A}_{e_i}^{rel_{out}}\\textbf{r}}{|N_{{e_i}}^{out}|},\n\\end{equation}\nwhere $ |N_{e_i}^{in}| $ and $|N_{e_i}^{out}|$ are the in-degree and out-degree of $e_i$, respectively. $\\textbf{A}^{rel_{in}}$ denotes the adjacency matrix for in-degrees, $ \\textbf{r} $ represents relation embedding.\n\nPlease note that before fusion, the hyperbolic space embedding are projected to Euclidean space $ \\overline{\\mathbf{z}^{\\mathbb{H}}} = \\log_o^{L}(\\mathbf{z}^{\\mathbb{H},{L}}) $.\nThrough the steps above, we concatenate the entity-level and relation-level features in Euclidean space to obtain the final output. \n\\begin{equation}\n \\tilde{\\mathbf{z}^{\\mathbb{H}}} =\\overline{\\mathbf{z}^{\\mathbb{H}}} \\oplus \\overline{r}, \\tilde{\\mathbf{z}^{\\mathbb{E}}} =\\overline{\\mathbf{z}^{\\mathbb{E}}} \\oplus \\overline{r}.\n\\end{equation}\nHere, $\\tilde{\\mathbf{z}^{\\mathbb{H}}}$ and $\\tilde{\\mathbf{z}^{\\mathbb{E}}}$ denote final embedding in hyperbolic space and Euclidean space, respectively.\n", "completion_path": "./src/model.py", "namespace": "src.model.relation_encoding_and_fusion", "type": "function", "signature_position": [ 94, 94 ], "body_position": [ 95, 119 ], "ReferenceCode_With_Comments": "\nif direct:\n # ---------------------------------------------------------------------------\n # Snippet 1: If the 'direct' flag is True, split source relation adjacency into in/out matrices\n # Implements adjacency matrix separation described in LaTeX: \\textbf{A}^{rel_{in}} and \\textbf{A}^{rel_{out}}\n # ---------------------------------------------------------------------------\n # [Begin Snippet 1]\n rel_adj_sr_in, rel_adj_sr_out = rel_adj_sr[0], rel_adj_sr[1]\n # [End Snippet 1]\n\n # ---------------------------------------------------------------------------\n # Snippet 2: Aggregate and normalize in-degree relations for source.\n # It Implements \\textbf{A}_{e_i}^{rel_{in}}\\textbf{r}/|N_{e_i}^{in}| portion\n # ---------------------------------------------------------------------------\n # [Begin Snippet 2]\n rel_rowsum_sr_in = torch.sum(rel_adj_sr_in.to_dense(), dim=-1).unsqueeze(-1)\n sr_rel_embedding_in = torch.mm(rel_adj_sr_in, sr_rel_embedding)\n sr_rel_embedding_in = sr_rel_embedding_in.div(rel_rowsum_sr_in + 1e-5)\n # [End Snippet 2]\n\n # ---------------------------------------------------------------------------\n # Snippet 3: Aggregate and normalize out-degree relations for source graph which implements \\textbf{A}_{e_i}^{rel_{out}}\\textbf{r}/|N_{e_i}^{out}| portion.\n # Concatenate in/out embeddings for source graph.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 3]\n rel_rowsum_sr_out = torch.sum(rel_adj_sr_out.to_dense(), dim=-1).unsqueeze(-1)\n sr_rel_embedding_out = torch.mm(rel_adj_sr_out, sr_rel_embedding)\n sr_rel_embedding_out = sr_rel_embedding_out.div(rel_rowsum_sr_out + 1e-5)\n sr_rel_embedding = torch.cat([sr_rel_embedding_in, sr_rel_embedding_out], dim=-1)\n rel_adj_tg_in, rel_adj_tg_out = rel_adj_tg[0], rel_adj_tg[1]\n # [End Snippet 3]\n\n # ---------------------------------------------------------------------------\n # Snippet 4: Aggregate the relation embeddings using the in-degree adjacency matrix for target graph.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 4]\n rel_rowsum_tg_in = torch.sum(rel_adj_tg_in.to_dense(), dim=-1).unsqueeze(-1)\n tg_rel_embedding_in = torch.mm(rel_adj_tg_in, tg_rel_embedding)\n tg_rel_embedding_in = tg_rel_embedding_in.div(rel_rowsum_tg_in + 1e-5)\n # [End Snippet 4]\n\n # ---------------------------------------------------------------------------\n # Snippet 5: Aggregate the relation embeddings using the out-degree adjacency matrix for target graph.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 5]\n rel_rowsum_tg_out = torch.sum(rel_adj_tg_out.to_dense(), dim=-1).unsqueeze(-1)\n tg_rel_embedding_out = torch.mm(rel_adj_tg_out, tg_rel_embedding)\n tg_rel_embedding_out = tg_rel_embedding_out.div(rel_rowsum_tg_out + 1e-5)\n tg_rel_embedding = torch.cat([tg_rel_embedding_in, tg_rel_embedding_out], dim=-1)\n # [End Snippet 5]\nelse:\n # ---------------------------------------------------------------------------\n # Snippet 6: Compute degree sums for undirected case.\n # Simplified version of degree calculation without direction separation\u3002\n # Then, perform a single aggregation pass for undirected relations on both the source and target graphs.\n # Finally, Normalize aggregated embeddings. Applies degree normalization without direction separation\n # ---------------------------------------------------------------------------\n # [Begin Snippet 6]\n rel_rowsum_sr = torch.sum(rel_adj_sr.to_dense(), dim=-1).unsqueeze(-1)\n rel_rowsum_tg = torch.sum(rel_adj_tg.to_dense(), dim=-1).unsqueeze(-1)\n sr_rel_embedding = torch.mm(rel_adj_sr, sr_rel_embedding)\n tg_rel_embedding = torch.mm(rel_adj_tg, tg_rel_embedding)\n sr_rel_embedding = sr_rel_embedding.div(rel_rowsum_sr)\n tg_rel_embedding = tg_rel_embedding.div(rel_rowsum_tg)\n # [End Snippet 6]\n\n# ---------------------------------------------------------------------------\n# Snippet 7: Return the final relation embeddings for the source and target graphs,\n# ---------------------------------------------------------------------------\n# [Begin Snippet 7]\nreturn sr_rel_embedding, tg_rel_embedding\n# [End Snippet 7]\n", "Missing_Mismatched_details": { "string": "\nMissing/Mismatched Details:\n Missing Details:\n - Explicit Numerical Stability Handling:\n The LaTeX description does not mention any epsilon value (e.g., $1e^{-5}$) used in the denominator during the normalization step to prevent division by zero.\n - After summing adjacency matrix rows, add a small epsilon value explicitly during normalization:\n \\[ \\frac{\\textbf{A}_{e_i}^{rel}\\textbf{r}}{|N_{e_i}| + \\epsilon} \\]\n - Sparse Matrix Conversion:\n The LaTeX description omits the explicit step of converting sparse adjacency matrices (\\textbf{A}^{rel_{in}} and \\textbf{A}^{rel_{out}}) to dense format before aggregation. \n Workflow:\n - Check adjacency matrices for sparsity.\n - Convert sparse adjacency matrices explicitly to dense tensors (e.g., `.to_dense()`) to ensure correct subsequent matrix operations.\n - Proceed with the aggregation and normalization steps using the dense matrices.\n - Degree Sum Calculation Method: The LaTeX description does not clearly specify the method of summing degrees (i.e., row-wise summation with `.sum(dim=-1)` and subsequent unsqueeze operations). The reference Python code explicitly calculates degrees with `.sum(dim=-1).unsqueeze(-1)`, ensuring a specific tensor dimension alignment essential for correct normalization.\n - Concatenation Dimension Clarification: The LaTeX code uses a general concatenation operator ($\\oplus$) without explicitly defining the dimension along which concatenation occurs. For the generated code, the concatenation is explicitly performed along the last dimension (`dim=-1`). This detail significantly impacts tensor shape and aggregation behavior.\n\n Mismatched Details:\n - None\n", "Missing_details": [ "\n- Explicit Numerical Stability Handling:\n The LaTeX description does not mention any epsilon value (e.g., $1e^{-5}$) used in the denominator during the normalization step to prevent division by zero.\n - After summing adjacency matrix rows, add a small epsilon value explicitly during normalization:\n \\[ \\frac{\\textbf{A}_{e_i}^{rel}\\textbf{r}}{|N_{e_i}| + \\epsilon} \\]\n", "\n- Sparse Matrix Conversion:\n The LaTeX description omits the explicit step of converting sparse adjacency matrices (\\textbf{A}^{rel_{in}} and \\textbf{A}^{rel_{out}}) to dense format before aggregation. \n Workflow:\n - Check adjacency matrices for sparsity.\n - Convert sparse adjacency matrices explicitly to dense tensors (e.g., `.to_dense()`) to ensure correct subsequent matrix operations.\n - Proceed with the aggregation and normalization steps using the dense matrices.\n", "\n- Degree Sum Calculation Method: The LaTeX description does not clearly specify the method of summing degrees (i.e., row-wise summation with `.sum(dim=-1)` and subsequent unsqueeze operations). The reference Python code explicitly calculates degrees with `.sum(dim=-1).unsqueeze(-1)`, ensuring a specific tensor dimension alignment essential for correct normalization.\n", "\n- Concatenation Dimension Clarification: The LaTeX code uses a general concatenation operator ($\\oplus$) without explicitly defining the dimension along which concatenation occurs. For the generated code, the concatenation is explicitly performed along the last dimension (`dim=-1`). This detail significantly impacts tensor shape and aggregation behavior.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - rel_adj_sr (torch.Tensor, Shape: (num_entities_sr, num_relations) if `direct` is false, [(num_entities_sr, num_relations), (num_entities_sr, num_relations)] otherwise): \n Relation adjacency matrix for the source graph. \n If `direct` is True, it's expected to be a list containing two tensors:\n rel_adj_sr = (\n in_degree_adj, # Shape: (num_entities_sr, num_relations)\n out_degree_adj # Shape: (num_entities_sr, num_relations)\n ) \n If `direct` is False, it should be a single tensor representing the undirected adjacency matrix.\n - rel_adj_tg (torch.Tensor, Shape: (num_entities_tg, num_relations) if `direct` is false, [(num_entities_tg, num_relations), (num_entities_tg, num_relations)] otherwise): \n Relation adjacency matrix for the target graph. Similar structure to `rel_adj_sr`. \n - sr_rel_embedding (torch.Tensor, Shape: (num_relations, rel_dim)): \n Relation embeddings for the source graph. \n - tg_rel_embedding (torch.Tensor,Shape: (num_relations, rel_dim)): \n Relation embeddings for the target graph. \n - direct (bool): \n A flag indicating whether to consider the direction of relations during aggregation.\n If True, the function uses in-degree and out-degree information separately.\n If False, it treats relations as undirected.\n", "Arguments_list": [ { "name": "rel_adj_sr", "string": "\n- rel_adj_sr (torch.Tensor, Shape: (num_entities_sr, num_relations) if `direct` is false, [(num_entities_sr, num_relations), (num_entities_sr, num_relations)] otherwise): \n Relation adjacency matrix for the source graph. \n If `direct` is True, it's expected to be a list containing two tensors:\n rel_adj_sr = (\n in_degree_adj, # Shape: (num_entities_sr, num_relations)\n out_degree_adj # Shape: (num_entities_sr, num_relations)\n ) \n If `direct` is False, it should be a single tensor representing the undirected adjacency matrix.\n", "dependency": null }, { "name": "rel_adj_tg", "string": "\n- rel_adj_tg (torch.Tensor, Shape: (num_entities_tg, num_relations) if `direct` is false, [(num_entities_tg, num_relations), (num_entities_tg, num_relations)] otherwise): \n Relation adjacency matrix for the target graph. Similar structure to `rel_adj_sr`. \n", "dependency": null }, { "name": "sr_rel_embedding", "string": "\n- sr_rel_embedding (torch.Tensor, Shape: (num_relations, rel_dim)): \n Relation embeddings for the source graph. \n", "dependency": null }, { "name": "tg_rel_embedding", "string": "\n- tg_rel_embedding (torch.Tensor,Shape: (num_relations, rel_dim)): \n Relation embeddings for the target graph. \n", "dependency": null }, { "name": "direct", "string": "\n- direct (bool): \n A flag indicating whether to consider the direction of relations during aggregation.\n If True, the function uses in-degree and out-degree information separately.\n If False, it treats relations as undirected.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File dependency: \n - None\n\n Cross-File dependency: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.sum\n - torch.mm\n - torch.cat\n", "list": [ "torch.sum", "torch.mm", "torch.cat" ] }, "Return": { "Return_String": "\nOutput Variables:\n - sr_rel_embedding (torch.Tensor, Shape: (num_entities_sr, 2 * rel_dim) if `direct` is True, (num_entities_sr, rel_dim) otherwise.): \n Encoded relation embeddings for the source graph, aggregated based on neighboring entity relations. \n - tg_rel_embedding (torch.Tensor, Shape: (num_entities_tg, 2 * rel_dim) if `direct` is True, (num_entities_tg, rel_dim) otherwise.): \n Encoded relation embeddings for the target graph, aggregated based on neighboring entity relations.\n", "Return_list": [ { "name": "sr_rel_embedding", "string": "\n- sr_rel_embedding (torch.Tensor, Shape: (num_entities_sr, 2 * rel_dim) if `direct` is True, (num_entities_sr, rel_dim) otherwise.): \n Encoded relation embeddings for the source graph, aggregated based on neighboring entity relations. \n", "dependency": null }, { "name": "tg_rel_embedding", "string": "\n- tg_rel_embedding (torch.Tensor, Shape: (num_entities_tg, 2 * rel_dim) if `direct` is True, (num_entities_tg, rel_dim) otherwise.): \n Encoded relation embeddings for the target graph, aggregated based on neighboring entity relations.\n", "dependency": null } ] }, "ori_python_file": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport manifolds\nfrom src.att_layers import GraphAttentionLayer\nimport src.hyp_layers as hyp_layers\nfrom src.layers import GraphConvolution, Linear, get_dim_act, GraphMultiHeadAttLayer, MultiHeadAttention\nfrom utils.sinkhorn_cal import sinkhorn\nfrom src.layers import DoubleEmbedding, GraphMultiHeadAttLayer, MultiHeadAttention\nfrom src.utils import set_random_seed\nimport numpy as np\nimport os, random\nos.environ['PYTHONHASHSEED'] = str(42)\nos.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\nnp.random.seed(42)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\ntorch.use_deterministic_algorithms(True)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nrandom.seed(42)\ntorch.cuda.synchronize()\ndef margin_based_loss(embeddings1, embeddings2, a1_align, a2_align, neg1_left, neg1_right, neg2_left, neg2_right, neg_samples_size, loss_norm, pos_margin=0.01, neg_margin=3, neg_param=0.2, only_pos=False):\n a1_align = np.array(a1_align)\n a2_align = np.array(a2_align)\n t = len(a1_align)\n L = np.ones((t, neg_samples_size)) * (a1_align.reshape((t,1)))\n a1_align = L.reshape((t*neg_samples_size,))\n R = np.ones((t, neg_samples_size)) * (a2_align.reshape((t,1)))\n a2_align = R.reshape((t*neg_samples_size,))\n a1_align = torch.tensor(a1_align, device=embeddings1.device)\n a2_align = torch.tensor(a2_align, device=embeddings1.device)\n neg1_left = torch.tensor(neg1_left, device=embeddings1.device)\n neg1_right = torch.tensor(neg1_right, device=embeddings1.device)\n neg2_left = torch.tensor(neg2_left, device=embeddings1.device)\n neg2_right = torch.tensor(neg2_right, device=embeddings1.device)\n left_x = embeddings1[a1_align.long()]\n right_x = embeddings2[a2_align.long()]\n if loss_norm == \"l1\":\n pos_loss = torch.abs(left_x - right_x)\n elif loss_norm == 'l2':\n pos_loss = torch.square(left_x - right_x)\n pos_loss = torch.sum(pos_loss, dim=1)\n left_x = embeddings1[neg1_left.long()]\n right_x = embeddings2[neg1_right.long()]\n if loss_norm == \"l1\":\n neg_loss_1 = torch.abs(left_x - right_x)\n elif loss_norm == 'l2':\n neg_loss_1 = torch.square(left_x - right_x)\n neg_loss_1 = torch.sum(neg_loss_1, dim=1)\n left_x = embeddings1[neg2_left.long()]\n right_x = embeddings2[neg2_right.long()]\n if loss_norm == \"l1\":\n neg_loss_2 = torch.abs(left_x - right_x)\n elif loss_norm == 'l2':\n neg_loss_2 = torch.square(left_x - right_x)\n neg_loss_2 = torch.sum(neg_loss_2, dim=1)\n loss1 = F.relu(pos_loss + neg_margin - neg_loss_1)\n loss2 = F.relu(pos_loss + neg_margin - neg_loss_2)\n loss1 = torch.sum(loss1)\n loss2 = torch.sum(loss2)\n loss = loss1 + loss2\n return loss\n\ndef euclidean_space_embedding(entity_embedding, adj, attentive_aggregators, multihead_attention, n_head, ent_dim, dropout, res):\n embedding = dropout(entity_embedding)\n embedding_list = []\n if res:\n embedding_list.append(embedding)\n for layer in attentive_aggregators:\n embedding = layer(embedding, adj)\n embedding = F.normalize(embedding, dim=1, p=2)\n embedding_list.append(dropout(embedding))\n if res:\n range_ = len(attentive_aggregators) + 1\n else:\n range_ = len(attentive_aggregators)\n embedding = torch.cat(embedding_list, dim=1).reshape(-1, range_, ent_dim)\n embedding, _ = multihead_attention(embedding, embedding, embedding)\n embedding = torch.mean(embedding, dim=1)\n embedding = embedding.squeeze(1)\n return embedding\n\ndef hyperbolic_space_embedding(entity_embedding, adj, manifold, curvatures, layers):\n x_tan = manifold.proj_tan0(entity_embedding, curvatures[0])\n x_hyp = manifold.expmap0(x_tan, c=curvatures[0])\n input_ = (x_hyp, adj)\n output, _ = layers.forward(input_)\n output = manifold.logmap0(output, c=curvatures[0])\n return output\n\ndef relation_encoding_and_fusion(rel_adj_sr, rel_adj_tg, sr_rel_embedding, tg_rel_embedding, direct):\n if direct:\n rel_adj_sr_in, rel_adj_sr_out = rel_adj_sr[0], rel_adj_sr[1]\n rel_rowsum_sr_in = torch.sum(rel_adj_sr_in.to_dense(), dim=-1).unsqueeze(-1)\n rel_rowsum_sr_out = torch.sum(rel_adj_sr_out.to_dense(), dim=-1).unsqueeze(-1)\n sr_rel_embedding_in = torch.mm(rel_adj_sr_in, sr_rel_embedding)\n sr_rel_embedding_in = sr_rel_embedding_in.div(rel_rowsum_sr_in + 1e-5)\n sr_rel_embedding_out = torch.mm(rel_adj_sr_out, sr_rel_embedding)\n sr_rel_embedding_out = sr_rel_embedding_out.div(rel_rowsum_sr_out + 1e-5)\n sr_rel_embedding = torch.cat([sr_rel_embedding_in, sr_rel_embedding_out], dim=-1)\n rel_adj_tg_in, rel_adj_tg_out = rel_adj_tg[0], rel_adj_tg[1]\n rel_rowsum_tg_in = torch.sum(rel_adj_tg_in.to_dense(), dim=-1).unsqueeze(-1)\n rel_rowsum_tg_out = torch.sum(rel_adj_tg_out.to_dense(), dim=-1).unsqueeze(-1)\n tg_rel_embedding_in = torch.mm(rel_adj_tg_in, tg_rel_embedding)\n tg_rel_embedding_in = tg_rel_embedding_in.div(rel_rowsum_tg_in + 1e-5)\n tg_rel_embedding_out = torch.mm(rel_adj_tg_out, tg_rel_embedding)\n tg_rel_embedding_out = tg_rel_embedding_out.div(rel_rowsum_tg_out + 1e-5)\n tg_rel_embedding = torch.cat([tg_rel_embedding_in, tg_rel_embedding_out], dim=-1)\n else:\n rel_rowsum_sr = torch.sum(rel_adj_sr.to_dense(), dim=-1).unsqueeze(-1)\n rel_rowsum_tg = torch.sum(rel_adj_tg.to_dense(), dim=-1).unsqueeze(-1)\n sr_rel_embedding = torch.mm(rel_adj_sr, sr_rel_embedding)\n tg_rel_embedding = torch.mm(rel_adj_tg, tg_rel_embedding)\n sr_rel_embedding = sr_rel_embedding.div(rel_rowsum_sr)\n tg_rel_embedding = tg_rel_embedding.div(rel_rowsum_tg)\n return sr_rel_embedding, tg_rel_embedding\n\nclass UniEA(nn.Module):\n def __init__(self, num_sr, num_tg, adj_sr, adj_tg, rel_num, rel_adj_sr, rel_adj_tg, args) -> None:\n super().__init__()\n self.num_sr = num_sr\n self.num_tg = num_tg\n self.adj_sr = adj_sr\n self.adj_tg = adj_tg\n self.rel_num = rel_num\n self.rel_adj_sr = rel_adj_sr\n self.rel_adj_tg = rel_adj_tg\n self.ent_dim = args.ent_dim\n self.rel_dim = args.rel_dim\n self.n_head = args.n_head\n self.layer = args.layer\n self.direct = args.direct\n self.res = args.res\n self.manifold_name = args.manifold\n if args.c is not None:\n self.c = torch.tensor([args.c])\n if not args.device == 'cuda':\n self.c = self.c.to(args.device)\n else:\n self.c = nn.Parameter(torch.Tensor([1.]))\n self.manifold = getattr(manifolds, self.manifold_name)()\n assert args.layer > 1\n dims, acts, self.curvatures = hyp_layers.get_dim_act_curv(args)\n self.curvatures.append(self.c)\n hgc_layers = []\n for i in range(len(dims) - 1):\n c_in, c_out = self.curvatures[i], self.curvatures[i + 1]\n in_dim, out_dim = dims[i], dims[i + 1]\n act = acts[i]\n hgc_layers.append(\n hyp_layers.HyperbolicGraphConvolution(\n self.manifold, in_dim, out_dim, c_in, c_out, args.dropout, act, args.bias, args.use_att,\n args.local_agg\n )\n )\n self.layers = nn.Sequential(*hgc_layers)\n self.encode_graph = True\n self.scale = 300\n self.mats_hyper = nn.Parameter(torch.Tensor(args.dim, self.ent_dim), requires_grad=True)\n torch.manual_seed(42)\n nn.init.xavier_uniform_(self.mats_hyper)\n self.mats_hyper2 = nn.Parameter(torch.Tensor(args.dim, self.ent_dim), requires_grad=True)\n torch.manual_seed(42)\n nn.init.xavier_uniform_(self.mats_hyper2)\n self.dropout = nn.Dropout(args.dropout)\n self.entity_embedding = DoubleEmbedding(num_sr=self.num_sr, num_tg=self.num_tg, embedding_dim=self.ent_dim, init_type=args.init_type)\n self.hyper_entity_embedding = DoubleEmbedding(num_sr=self.num_sr, num_tg=self.num_tg, embedding_dim=args.dim,\n init_type=args.init_type)\n self.relation_embedding = DoubleEmbedding(num_sr=self.rel_num, num_tg=self.rel_num, embedding_dim=self.rel_dim, init_type=args.init_type)\n self.attentive_aggregators = nn.ModuleList([GraphMultiHeadAttLayer(in_features=self.ent_dim, out_features=self.ent_dim, n_head=self.n_head, dropout=args.dropout) for i in range(self.layer)])\n self.multihead_attention = MultiHeadAttention(\n n_head=self.n_head,\n d_model=self.ent_dim,\n d_k=self.ent_dim,\n d_v=self.ent_dim,\n dropout=args.dropout\n )\n if self.direct:\n self.proj_head = nn.Sequential(\n nn.Linear(self.ent_dim*self.n_head + self.rel_dim*2, self.ent_dim),\n nn.ReLU(),\n )\n else:\n self.proj_head = nn.Sequential(\n nn.Linear(self.ent_dim*self.n_head + self.rel_dim, self.ent_dim),\n nn.ReLU(),\n )\n \n def cal_ot(self, mm_embeddings, st_embeddings, delta_ot):\n device = delta_ot.device\n number = 10\n mm_dim = mm_embeddings.shape[-1]\n st_dim = st_embeddings.shape[-1]\n mm_dis = torch.ones_like(mm_embeddings[0, :])\n mm_dis = mm_dis / mm_dis.shape[-1]\n st_dis = torch.ones_like(st_embeddings[0, :])\n st_dis = st_dis / st_dis.shape[-1]\n matrix_temp = torch.zeros((number, mm_dim, st_dim))\n with torch.no_grad():\n for i in range(number):\n cost = (mm_embeddings[i, :].reshape(-1, mm_dim) - st_embeddings[i, :].reshape(st_dim,\n -1)) ** 2 * self.scale\n matrix_temp[i, :, :] = sinkhorn(mm_dis, st_dis, cost.t())[0].t()\n return matrix_temp.mean(dim=0).to(device) * st_dim * self.scale + delta_ot\n \n def forward(self, aug_adj1=None, aug_rel_adj1=None, aug_adj2=None, aug_rel_adj2=None, phase=\"norm\"):\n if phase in [\"norm\", \"eval\"]:\n adj_sr, adj_tg, rel_adj_sr, rel_adj_tg = self.adj_sr, self.adj_tg, self.rel_adj_sr, self.rel_adj_tg\n elif phase == \"augment\":\n adj_sr, adj_tg, rel_adj_sr, rel_adj_tg = aug_adj1, aug_adj2, aug_rel_adj1, aug_rel_adj2\n sr_embedding, tg_embedding = self.entity_embedding.weight\n sr_embedding, tg_embedding = self.dropout(sr_embedding), self.dropout(tg_embedding)\n hyper_sr_embedding, hyper_tg_embedding = self.entity_embedding.weight\n sr_rel_embedding, tg_rel_embedding = self.relation_embedding.weight\n sr_rel_embedding, tg_rel_embedding = self.dropout(sr_rel_embedding), self.dropout(tg_rel_embedding)\n sr_rel_embedding, tg_rel_embedding = relation_encoding_and_fusion(rel_adj_sr, rel_adj_tg, sr_rel_embedding, tg_rel_embedding, self.direct)\n sr_embedding = euclidean_space_embedding(sr_embedding, adj_sr, self.attentive_aggregators, self.multihead_attention, self.n_head, self.ent_dim, self.dropout, self.res)\n tg_embedding = euclidean_space_embedding(tg_embedding, adj_tg, self.attentive_aggregators, self.multihead_attention, self.n_head, self.ent_dim, self.dropout, self.res)\n hyper_sr_embedding = hyperbolic_space_embedding(hyper_sr_embedding, adj_sr, self.manifold, self.curvatures, self.layers)\n hyper_tg_embedding = hyperbolic_space_embedding(hyper_tg_embedding, adj_tg, self.manifold, self.curvatures, self.layers)\n sr_embedding = torch.cat([sr_embedding, sr_rel_embedding], dim=-1)\n tg_embedding = torch.cat([tg_embedding, tg_rel_embedding], dim=-1)\n hyper_sr_embedding = torch.cat([hyper_sr_embedding, sr_rel_embedding], dim=-1)\n hyper_tg_embedding = torch.cat([hyper_tg_embedding, tg_rel_embedding], dim=-1)\n return sr_embedding, tg_embedding, hyper_sr_embedding, hyper_tg_embedding\n \n def contrastive_loss(self, embeddings1, embeddings2, ent_num, sim_method=\"cosine\", t=0.08):\n if sim_method == \"cosine\":\n embeddings1_abs = embeddings1.norm(dim=1)\n embeddings2_abs = embeddings2.norm(dim=1)\n logits = torch.einsum('ik,jk->ij', embeddings1, embeddings2) / (\n torch.einsum('i,j->ij', embeddings1_abs, embeddings2_abs) + 1e-5\n )\n logits = logits / t\n elif sim_method == \"inner\":\n logits = torch.mm(embeddings1, embeddings2.T)\n labels = torch.arange(ent_num).to(embeddings1.device)\n loss_1 = F.cross_entropy(logits, labels)\n loss_2 = F.cross_entropy(logits.T, labels)\n loss = (loss_1 + loss_2) / 2\n return loss" }, { "task_id": 3, "indent": 2, "script": "\npython train.py --task en_fr_15k\n", "latex_code": "\n\\subsubsection{Contrastive learning}\nTo ensure that the Euclidean space embedding retain their structure without distortion, we first use contrastive learning $ \\mathcal{L}_{inter} $ to maximize the consistency \\citep{Xie2023ImprovingKG, aug} between the Euclidean and hyperbolic space embedding.\nMoreover, previous methods suggest that similar entity embedding should be closer \\citep{cl}, but being too close can negatively affect the results of EA.\nTherefore, we employ contrastive learning $ \\mathcal{L}_{intra} $, aiming to push the distances between all entities within a graph further apart. We define the contrastive learning formula as follows:\n\\begin{equation} \\label{lc}\n \\mathcal{L}_{c,i}^{(G^\\mathbb{E},G^{\\mathbb{H}})}=-\\mathrm{log}\\frac{\\exp(\\langle \\tilde{\\mathbf{z}^{\\mathbb{E}}_i},\\tilde{\\mathbf{z}^{\\mathbb{H}}_i\\rangle)}} {\\sum_{k\\in \\mathcal{E}}\\exp(\\langle \\tilde{\\mathbf{z}^{\\mathbb{E}}_i},\\tilde{\\mathbf{z}^{\\mathbb{H}}_k}\\rangle)},\n\\end{equation}\n\\begin{equation}\n \\mathcal{L}_{inter}=\\sum_{n=\\{1,2\\}}\\frac{1}{2|\\mathcal{E}_n|}\\sum_{i\\in \\mathcal{E}_n}(\\mathcal{L}_{c,i}^{(\\tilde{G^{\\mathbb{E}}_n},\\tilde{G^{\\mathbb{H}}_n})}+\\mathcal{L}_{c,i}^{(\\tilde{G^{\\mathbb{H}}_n},\\tilde{G^{\\mathbb{E}}_n})}),\n\\end{equation}\n\\begin{equation}\n \\mathcal{L}_{intra}=\\sum_{i\\in \\mathcal{E}}\\mathcal{L}_{c,i}^{(\\tilde{G^{\\mathbb{E}}_1},\\tilde{G^{\\mathbb{E}}_1})}\n\\end{equation}\nHere, $ \\mathcal{L}_{intra} $ and $ \\mathcal{L}_{inter} $ can be calculated using the Equation~\\ref{lc}.\n", "completion_path": "./src/model.py", "namespace": "src.model.UniEA.contrastive_loss", "type": "method", "signature_position": [ 230, 230 ], "body_position": [ 231, 244 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: For \"cosine\" similarity, the code calculates the normalized dot product between each pair of embeddings (referencing log-terms in Equation (8) of the LaTeX, where embeddings from two spaces are scored). This ensures entities corresponding to the same index align more closely than others.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nif sim_method == \"cosine\":\n embeddings1_abs = embeddings1.norm(dim=1)\n embeddings2_abs = embeddings2.norm(dim=1)\n logits = torch.einsum('ik,jk->ij', embeddings1, embeddings2) / (\n torch.einsum('i,j->ij', embeddings1_abs, embeddings2_abs) + 1e-5\n )\n logits = logits / t\n# [End Snippet 1]\n\n\nelif sim_method == \"inner\":\n # ---------------------------------------------------------------------------\n # Snippet 2: For \"inner\" similarity, the code directly computes the inner product of the embedding pairs, reflecting an alternative approach to measure alignment.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 2]\n logits = torch.mm(embeddings1, embeddings2.T)\n # [End Snippet 2]\n\nlabels = torch.arange(ent_num).to(embeddings1.device)\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Computes cross-entropy losses in both directions (embeddings1 vs. embeddings2, and embeddings2 vs. embeddings1).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nloss_1 = F.cross_entropy(logits, labels)\nloss_2 = F.cross_entropy(logits.T, labels)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: The final contrastive loss is the average of the two directional losses, approximating \\(\\mathcal{L}_{c,i}^{(G^{\\mathbb{E}},G^{\\mathbb{H}})}\\) and \\(\\mathcal{L}_{c,i}^{(G^{\\mathbb{H}},G^{\\mathbb{E}})}\\).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nloss = (loss_1 + loss_2) / 2\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Returns the final contrastive loss value.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nreturn loss\n# [End Snippet 5]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing:\n - The LaTeX description neglects to specify handling numerical stability explicitly, such as adding a small epsilon (e.g., `1e-5`) when computing cosine similarities. This numerical stability step is essential in the reference Python implementation to avoid potential division-by-zero errors or unstable training behaviors.\n - The LaTeX code does not explicitly mention the necessity of symmetric contrastive loss computation (i.e., computing the loss from embeddings1 to embeddings2 and vice versa separately, then averaging). The reference Python code clearly performs two separate cross-entropy calculations (`loss_1` and `loss_2`) for embeddings in both directions to enforce symmetrical alignment, a critical step omitted in the LaTeX description.\n - Explicit temperature parameter in the cosine similarity calculation.\n - Implementation uses bidirectional loss averaging.\n\n - Mismatched:\n - The LaTeX definition uses inner product similarity (`\\langle \\cdot, \\cdot \\rangle`) without explicitly clarifying if embeddings should be normalized (cosine similarity) or not (inner product). The reference Python code explicitly supports both cosine and inner-product similarity methods, clearly differentiating them.\n\n", "Missing_details": [ "\n- The LaTeX description neglects to specify handling numerical stability explicitly, such as adding a small epsilon (e.g., `1e-5`) when computing cosine similarities. This numerical stability step is essential in the reference Python implementation to avoid potential division-by-zero errors or unstable training behaviors.\n", "\n- The LaTeX code does not explicitly mention the necessity of symmetric contrastive loss computation (i.e., computing the loss from embeddings1 to embeddings2 and vice versa separately, then averaging). The reference Python code clearly performs two separate cross-entropy calculations (`loss_1` and `loss_2`) for embeddings in both directions to enforce symmetrical alignment, a critical step omitted in the LaTeX description.\n", "\n- Explicit temperature parameter in the cosine similarity calculation.\n", "\n- Implementation uses bidirectional loss averaging.\n" ], "Mismatched_details": [ "\n- The LaTeX definition uses inner product similarity (`\\langle \\cdot, \\cdot \\rangle`) without explicitly clarifying if embeddings should be normalized (cosine similarity) or not (inner product). The reference Python code explicitly supports both cosine and inner-product similarity methods, clearly differentiating them.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - embeddings1 (torch.Tensor, Shape: [num_entities, embedding_dim]): The first set of embeddings. \n - embeddings2 (torch.Tensor, Shape: [num_entities, embedding_dim]): The second set of embeddings. \n - ent_num (int): The number of entities.\n - sim_method (str): The similarity metric to use. Can be either \"cosine\" for cosine similarity or \"inner\" for inner product. Default is \"cosine\".\n - t (float): The temperature parameter for scaling the logits in the cosine similarity case. Default is 0.08.\n", "Arguments_list": [ { "name": "embeddings1", "string": "\n- embeddings1 (torch.Tensor, Shape: [num_entities, embedding_dim]): The first set of embeddings.\n", "dependency": null }, { "name": "embeddings2", "string": "\n- embeddings2 (torch.Tensor, Shape: [num_entities, embedding_dim]): The second set of embeddings.\n", "dependency": null }, { "name": "ent_num", "string": "\n- ent_num (int): The number of entities.\n", "dependency": null }, { "name": "sim_method", "string": "\n- sim_method (str): The similarity metric to use. Can be either \"cosine\" for cosine similarity or \"inner\" for inner product. Default is \"cosine\".\n", "dependency": null }, { "name": "t", "string": "\n- t (float): The temperature parameter for scaling the logits in the cosine similarity case. Default is 0.08.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File dependency: \n - None\n \n Cross-File dependency: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.nn.functional.cross_entropy\n - torch.einsum\n - torch.mm\n - torch.arange\n", "list": [ "torch.nn.functional.cross_entropy", "torch.einsum", "torch.mm", "torch.arange" ] }, "Return": { "Return_String": "\nOutput Variables:\n - loss (torch.Tensor): The calculated contrastive loss (a scalar value).\n", "Return_list": [ { "name": "loss", "string": "\n- loss (torch.Tensor): The calculated contrastive loss (a scalar value).\n", "dependency": null } ] }, "ori_python_file": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport manifolds\nfrom src.att_layers import GraphAttentionLayer\nimport src.hyp_layers as hyp_layers\nfrom src.layers import GraphConvolution, Linear, get_dim_act, GraphMultiHeadAttLayer, MultiHeadAttention\nfrom utils.sinkhorn_cal import sinkhorn\nfrom src.layers import DoubleEmbedding, GraphMultiHeadAttLayer, MultiHeadAttention\nfrom src.utils import set_random_seed\nimport numpy as np\nimport os, random\nos.environ['PYTHONHASHSEED'] = str(42)\nos.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\nnp.random.seed(42)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\ntorch.use_deterministic_algorithms(True)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nrandom.seed(42)\ntorch.cuda.synchronize()\ndef margin_based_loss(embeddings1, embeddings2, a1_align, a2_align, neg1_left, neg1_right, neg2_left, neg2_right, neg_samples_size, loss_norm, pos_margin=0.01, neg_margin=3, neg_param=0.2, only_pos=False):\n a1_align = np.array(a1_align)\n a2_align = np.array(a2_align)\n t = len(a1_align)\n L = np.ones((t, neg_samples_size)) * (a1_align.reshape((t,1)))\n a1_align = L.reshape((t*neg_samples_size,))\n R = np.ones((t, neg_samples_size)) * (a2_align.reshape((t,1)))\n a2_align = R.reshape((t*neg_samples_size,))\n a1_align = torch.tensor(a1_align, device=embeddings1.device)\n a2_align = torch.tensor(a2_align, device=embeddings1.device)\n neg1_left = torch.tensor(neg1_left, device=embeddings1.device)\n neg1_right = torch.tensor(neg1_right, device=embeddings1.device)\n neg2_left = torch.tensor(neg2_left, device=embeddings1.device)\n neg2_right = torch.tensor(neg2_right, device=embeddings1.device)\n left_x = embeddings1[a1_align.long()]\n right_x = embeddings2[a2_align.long()]\n if loss_norm == \"l1\":\n pos_loss = torch.abs(left_x - right_x)\n elif loss_norm == 'l2':\n pos_loss = torch.square(left_x - right_x)\n pos_loss = torch.sum(pos_loss, dim=1)\n left_x = embeddings1[neg1_left.long()]\n right_x = embeddings2[neg1_right.long()]\n if loss_norm == \"l1\":\n neg_loss_1 = torch.abs(left_x - right_x)\n elif loss_norm == 'l2':\n neg_loss_1 = torch.square(left_x - right_x)\n neg_loss_1 = torch.sum(neg_loss_1, dim=1)\n left_x = embeddings1[neg2_left.long()]\n right_x = embeddings2[neg2_right.long()]\n if loss_norm == \"l1\":\n neg_loss_2 = torch.abs(left_x - right_x)\n elif loss_norm == 'l2':\n neg_loss_2 = torch.square(left_x - right_x)\n neg_loss_2 = torch.sum(neg_loss_2, dim=1)\n loss1 = F.relu(pos_loss + neg_margin - neg_loss_1)\n loss2 = F.relu(pos_loss + neg_margin - neg_loss_2)\n loss1 = torch.sum(loss1)\n loss2 = torch.sum(loss2)\n loss = loss1 + loss2\n return loss\n\ndef euclidean_space_embedding(entity_embedding, adj, attentive_aggregators, multihead_attention, n_head, ent_dim, dropout, res):\n embedding = dropout(entity_embedding)\n embedding_list = []\n if res:\n embedding_list.append(embedding)\n for layer in attentive_aggregators:\n embedding = layer(embedding, adj)\n embedding = F.normalize(embedding, dim=1, p=2)\n embedding_list.append(dropout(embedding))\n if res:\n range_ = len(attentive_aggregators) + 1\n else:\n range_ = len(attentive_aggregators)\n embedding = torch.cat(embedding_list, dim=1).reshape(-1, range_, ent_dim)\n embedding, _ = multihead_attention(embedding, embedding, embedding)\n embedding = torch.mean(embedding, dim=1)\n embedding = embedding.squeeze(1)\n return embedding\n\ndef hyperbolic_space_embedding(entity_embedding, adj, manifold, curvatures, layers):\n x_tan = manifold.proj_tan0(entity_embedding, curvatures[0])\n x_hyp = manifold.expmap0(x_tan, c=curvatures[0])\n input_ = (x_hyp, adj)\n output, _ = layers.forward(input_)\n output = manifold.logmap0(output, c=curvatures[0])\n return output\n\ndef relation_encoding_and_fusion(rel_adj_sr, rel_adj_tg, sr_rel_embedding, tg_rel_embedding, direct):\n if direct:\n rel_adj_sr_in, rel_adj_sr_out = rel_adj_sr[0], rel_adj_sr[1]\n rel_rowsum_sr_in = torch.sum(rel_adj_sr_in.to_dense(), dim=-1).unsqueeze(-1)\n rel_rowsum_sr_out = torch.sum(rel_adj_sr_out.to_dense(), dim=-1).unsqueeze(-1)\n sr_rel_embedding_in = torch.mm(rel_adj_sr_in, sr_rel_embedding)\n sr_rel_embedding_in = sr_rel_embedding_in.div(rel_rowsum_sr_in + 1e-5)\n sr_rel_embedding_out = torch.mm(rel_adj_sr_out, sr_rel_embedding)\n sr_rel_embedding_out = sr_rel_embedding_out.div(rel_rowsum_sr_out + 1e-5)\n sr_rel_embedding = torch.cat([sr_rel_embedding_in, sr_rel_embedding_out], dim=-1)\n rel_adj_tg_in, rel_adj_tg_out = rel_adj_tg[0], rel_adj_tg[1]\n rel_rowsum_tg_in = torch.sum(rel_adj_tg_in.to_dense(), dim=-1).unsqueeze(-1)\n rel_rowsum_tg_out = torch.sum(rel_adj_tg_out.to_dense(), dim=-1).unsqueeze(-1)\n tg_rel_embedding_in = torch.mm(rel_adj_tg_in, tg_rel_embedding)\n tg_rel_embedding_in = tg_rel_embedding_in.div(rel_rowsum_tg_in + 1e-5)\n tg_rel_embedding_out = torch.mm(rel_adj_tg_out, tg_rel_embedding)\n tg_rel_embedding_out = tg_rel_embedding_out.div(rel_rowsum_tg_out + 1e-5)\n tg_rel_embedding = torch.cat([tg_rel_embedding_in, tg_rel_embedding_out], dim=-1)\n else:\n rel_rowsum_sr = torch.sum(rel_adj_sr.to_dense(), dim=-1).unsqueeze(-1)\n rel_rowsum_tg = torch.sum(rel_adj_tg.to_dense(), dim=-1).unsqueeze(-1)\n sr_rel_embedding = torch.mm(rel_adj_sr, sr_rel_embedding)\n tg_rel_embedding = torch.mm(rel_adj_tg, tg_rel_embedding)\n sr_rel_embedding = sr_rel_embedding.div(rel_rowsum_sr)\n tg_rel_embedding = tg_rel_embedding.div(rel_rowsum_tg)\n return sr_rel_embedding, tg_rel_embedding\n\nclass UniEA(nn.Module):\n def __init__(self, num_sr, num_tg, adj_sr, adj_tg, rel_num, rel_adj_sr, rel_adj_tg, args) -> None:\n super().__init__()\n self.num_sr = num_sr\n self.num_tg = num_tg\n self.adj_sr = adj_sr\n self.adj_tg = adj_tg\n self.rel_num = rel_num\n self.rel_adj_sr = rel_adj_sr\n self.rel_adj_tg = rel_adj_tg\n self.ent_dim = args.ent_dim\n self.rel_dim = args.rel_dim\n self.n_head = args.n_head\n self.layer = args.layer\n self.direct = args.direct\n self.res = args.res\n self.manifold_name = args.manifold\n if args.c is not None:\n self.c = torch.tensor([args.c])\n if not args.device == 'cuda':\n self.c = self.c.to(args.device)\n else:\n self.c = nn.Parameter(torch.Tensor([1.]))\n self.manifold = getattr(manifolds, self.manifold_name)()\n assert args.layer > 1\n dims, acts, self.curvatures = hyp_layers.get_dim_act_curv(args)\n self.curvatures.append(self.c)\n hgc_layers = []\n for i in range(len(dims) - 1):\n c_in, c_out = self.curvatures[i], self.curvatures[i + 1]\n in_dim, out_dim = dims[i], dims[i + 1]\n act = acts[i]\n hgc_layers.append(\n hyp_layers.HyperbolicGraphConvolution(\n self.manifold, in_dim, out_dim, c_in, c_out, args.dropout, act, args.bias, args.use_att,\n args.local_agg\n )\n )\n self.layers = nn.Sequential(*hgc_layers)\n self.encode_graph = True\n self.scale = 300\n self.mats_hyper = nn.Parameter(torch.Tensor(args.dim, self.ent_dim), requires_grad=True)\n torch.manual_seed(42)\n nn.init.xavier_uniform_(self.mats_hyper)\n self.mats_hyper2 = nn.Parameter(torch.Tensor(args.dim, self.ent_dim), requires_grad=True)\n torch.manual_seed(42)\n nn.init.xavier_uniform_(self.mats_hyper2)\n self.dropout = nn.Dropout(args.dropout)\n self.entity_embedding = DoubleEmbedding(num_sr=self.num_sr, num_tg=self.num_tg, embedding_dim=self.ent_dim, init_type=args.init_type)\n self.hyper_entity_embedding = DoubleEmbedding(num_sr=self.num_sr, num_tg=self.num_tg, embedding_dim=args.dim,\n init_type=args.init_type)\n self.relation_embedding = DoubleEmbedding(num_sr=self.rel_num, num_tg=self.rel_num, embedding_dim=self.rel_dim, init_type=args.init_type)\n self.attentive_aggregators = nn.ModuleList([GraphMultiHeadAttLayer(in_features=self.ent_dim, out_features=self.ent_dim, n_head=self.n_head, dropout=args.dropout) for i in range(self.layer)])\n self.multihead_attention = MultiHeadAttention(\n n_head=self.n_head,\n d_model=self.ent_dim,\n d_k=self.ent_dim,\n d_v=self.ent_dim,\n dropout=args.dropout\n )\n if self.direct:\n self.proj_head = nn.Sequential(\n nn.Linear(self.ent_dim*self.n_head + self.rel_dim*2, self.ent_dim),\n nn.ReLU(),\n )\n else:\n self.proj_head = nn.Sequential(\n nn.Linear(self.ent_dim*self.n_head + self.rel_dim, self.ent_dim),\n nn.ReLU(),\n )\n \n def cal_ot(self, mm_embeddings, st_embeddings, delta_ot):\n device = delta_ot.device\n number = 10\n mm_dim = mm_embeddings.shape[-1]\n st_dim = st_embeddings.shape[-1]\n mm_dis = torch.ones_like(mm_embeddings[0, :])\n mm_dis = mm_dis / mm_dis.shape[-1]\n st_dis = torch.ones_like(st_embeddings[0, :])\n st_dis = st_dis / st_dis.shape[-1]\n matrix_temp = torch.zeros((number, mm_dim, st_dim))\n with torch.no_grad():\n for i in range(number):\n cost = (mm_embeddings[i, :].reshape(-1, mm_dim) - st_embeddings[i, :].reshape(st_dim,\n -1)) ** 2 * self.scale\n matrix_temp[i, :, :] = sinkhorn(mm_dis, st_dis, cost.t())[0].t()\n return matrix_temp.mean(dim=0).to(device) * st_dim * self.scale + delta_ot\n \n def forward(self, aug_adj1=None, aug_rel_adj1=None, aug_adj2=None, aug_rel_adj2=None, phase=\"norm\"):\n if phase in [\"norm\", \"eval\"]:\n adj_sr, adj_tg, rel_adj_sr, rel_adj_tg = self.adj_sr, self.adj_tg, self.rel_adj_sr, self.rel_adj_tg\n elif phase == \"augment\":\n adj_sr, adj_tg, rel_adj_sr, rel_adj_tg = aug_adj1, aug_adj2, aug_rel_adj1, aug_rel_adj2\n sr_embedding, tg_embedding = self.entity_embedding.weight\n sr_embedding, tg_embedding = self.dropout(sr_embedding), self.dropout(tg_embedding)\n hyper_sr_embedding, hyper_tg_embedding = self.entity_embedding.weight\n sr_rel_embedding, tg_rel_embedding = self.relation_embedding.weight\n sr_rel_embedding, tg_rel_embedding = self.dropout(sr_rel_embedding), self.dropout(tg_rel_embedding)\n sr_rel_embedding, tg_rel_embedding = relation_encoding_and_fusion(rel_adj_sr, rel_adj_tg, sr_rel_embedding, tg_rel_embedding, self.direct)\n sr_embedding = euclidean_space_embedding(sr_embedding, adj_sr, self.attentive_aggregators, self.multihead_attention, self.n_head, self.ent_dim, self.dropout, self.res)\n tg_embedding = euclidean_space_embedding(tg_embedding, adj_tg, self.attentive_aggregators, self.multihead_attention, self.n_head, self.ent_dim, self.dropout, self.res)\n hyper_sr_embedding = hyperbolic_space_embedding(hyper_sr_embedding, adj_sr, self.manifold, self.curvatures, self.layers)\n hyper_tg_embedding = hyperbolic_space_embedding(hyper_tg_embedding, adj_tg, self.manifold, self.curvatures, self.layers)\n sr_embedding = torch.cat([sr_embedding, sr_rel_embedding], dim=-1)\n tg_embedding = torch.cat([tg_embedding, tg_rel_embedding], dim=-1)\n hyper_sr_embedding = torch.cat([hyper_sr_embedding, sr_rel_embedding], dim=-1)\n hyper_tg_embedding = torch.cat([hyper_tg_embedding, tg_rel_embedding], dim=-1)\n return sr_embedding, tg_embedding, hyper_sr_embedding, hyper_tg_embedding\n \n def contrastive_loss(self, embeddings1, embeddings2, ent_num, sim_method=\"cosine\", t=0.08):\n if sim_method == \"cosine\":\n embeddings1_abs = embeddings1.norm(dim=1)\n embeddings2_abs = embeddings2.norm(dim=1)\n logits = torch.einsum('ik,jk->ij', embeddings1, embeddings2) / (\n torch.einsum('i,j->ij', embeddings1_abs, embeddings2_abs) + 1e-5\n )\n logits = logits / t\n elif sim_method == \"inner\":\n logits = torch.mm(embeddings1, embeddings2.T)\n labels = torch.arange(ent_num).to(embeddings1.device)\n loss_1 = F.cross_entropy(logits, labels)\n loss_2 = F.cross_entropy(logits.T, labels)\n loss = (loss_1 + loss_2) / 2\n return loss" }, { "task_id": 4, "indent": 1, "script": "\npython train.py --task en_fr_15k\n", "latex_code": "\n\\subsubsection{Margin-based alignment loss}\nWe use the pre-aligned entity pairs $\\mathcal{S}$ to bring the embeddings of the same entities in $\\mathcal{G}_1$ and $\\mathcal{G}_2$ closer, while pushing the embeddings of different entities further apart.\nWe choose to use Euclidean space embedding for the margin-based alignment loss:\n\\begin{equation}\n\\begin{aligned}\n \\mathcal{L}_{ea}= & \\sum_{(e_i,e_j)\\in S}\\sum_{({e}_a,{e}_b)\\in\\bar{S}_{(e_i,e_j)}} [||\\tilde{\\mathbf{z}^{\\mathbb{E}}_{e_i}}-\\tilde{\\mathbf{z}^{\\mathbb{E}}_{e_j}}||_{L2}+\\\\ & \n \\gamma - \n ||\\tilde{\\mathbf{z}^{\\mathbb{E}}_{{e_a}}}-\\tilde{\\mathbf{z}^{\\mathbb{E}}_{{e_b}}}||_{L2}]_{+},\n\\end{aligned}\n\\end{equation}\nwhere $\\gamma $ is a hyper-parameter of margin, $ [x]_+ = max\\{0,x\\} $ is to ensure non-negative output. $ \\bar{S}_{(e_i,e_j)} $ is a collection of negative samples composed of randomly replaced entities $e_i$ and $e_j$ from the seed set $\\mathcal{S}$.\n", "completion_path": "./src/model.py", "namespace": "src.model.margin_based_loss", "type": "function", "signature_position": [ 25, 25 ], "body_position": [ 26, 65 ], "ReferenceCode_With_Comments": "\na1_align = np.array(a1_align)\na2_align = np.array(a2_align)\n\nt = len(a1_align)\nL = np.ones((t, neg_samples_size)) * (a1_align.reshape((t,1)))\na1_align = L.reshape((t*neg_samples_size,))\nR = np.ones((t, neg_samples_size)) * (a2_align.reshape((t,1)))\na2_align = R.reshape((t*neg_samples_size,))\n\na1_align = torch.tensor(a1_align, device=embeddings1.device)\na2_align = torch.tensor(a2_align, device=embeddings1.device)\nneg1_left = torch.tensor(neg1_left, device=embeddings1.device)\nneg1_right = torch.tensor(neg1_right, device=embeddings1.device)\nneg2_left = torch.tensor(neg2_left, device=embeddings1.device)\nneg2_right = torch.tensor(neg2_right, device=embeddings1.device)\n\nleft_x = embeddings1[a1_align.long()]\nright_x = embeddings2[a2_align.long()]\n\n# ---------------------------------------------------------------------------\n# Snippet 1: Compute the positive pair distances using the specified norm (L1 or L2).\n# This corresponds to calculating ||z\u0303^E_(e_i) - z\u0303^E_(e_j)|| in the LaTeX equation.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nif loss_norm == \"l1\": # L1 norm\n pos_loss = torch.abs(left_x - right_x)\nelif loss_norm == 'l2': # L2 norm\n pos_loss = torch.square(left_x - right_x)\n\npos_loss = torch.sum(pos_loss, dim=1)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Compute the loss for the first set of negative pairs.\n# Retrieve the negative sample embeddings from embeddings1 and embeddings2 using neg1_left and neg1_right.\n# Then calculate their pairwise distances, analogous to computing ||z\u0303^E_(e_a) - z\u0303^E_(e_b)|| for negatives.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nleft_x = embeddings1[neg1_left.long()]\nright_x = embeddings2[neg1_right.long()]\nif loss_norm == \"l1\":\n neg_loss_1 = torch.abs(left_x - right_x)\nelif loss_norm == 'l2':\n neg_loss_1 = torch.square(left_x - right_x)\nneg_loss_1 = torch.sum(neg_loss_1, dim=1)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Compute the loss for the second set of negative pairs.\n# This mirrors the previous negative computation but uses the second set of negative indices (neg2_left and neg2_right).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nleft_x = embeddings1[neg2_left.long()]\nright_x = embeddings2[neg2_right.long()]\nif loss_norm == \"l1\":\n neg_loss_2 = torch.abs(left_x - right_x)\nelif loss_norm == 'l2':\n neg_loss_2 = torch.square(left_x - right_x)\n\nneg_loss_2 = torch.sum(neg_loss_2, dim=1)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Apply the margin-based hinge loss.\n# For each positive pair, add the margin (\u03b3, represented by neg_margin) and subtract the corresponding negative loss.\n# Then, apply a ReLU to ensure that only positive differences contribute, reflecting the [x]_+ operator in the LaTeX.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nloss1 = F.relu(pos_loss + neg_margin - neg_loss_1)\nloss2 = F.relu(pos_loss + neg_margin - neg_loss_2)\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Sum the loss values from both negative samples to obtain the total margin-based alignment loss.\n# This summation aggregates the loss over all positive-negative sample pairs as described in the paper.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nloss1 = torch.sum(loss1)\nloss2 = torch.sum(loss2)\nloss = loss1 + loss2\n# [End Snippet 5]\n\n# ---------------------------------------------------------------------------\n# Snippet 6: Return the final computed loss.\n# This final value represents the margin-based alignment loss to be minimized during training.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 6]\nreturn loss\n# [End Snippet 6]\n", "Missing_Mismatched_details": { "string": "\nMissing/Mismatched Details:\n Missing Details:\n - The LaTeX description does not explicitly mention that for each positive pair (aligned entities), the embeddings should be replicated multiple times (equal to the negative sample size) to correctly match the dimensions of the negative samples. The reference Python code explicitly reshapes and duplicates the indices of positive samples so that each positive pair aligns correctly with multiple negative samples.\n - The code implments both l1 and l2 norms for distance calculation, but the LaTeX description does not specify the norm used for distance calculation.\n\n Mismatched Details:\n - The LaTeX description specifies using the standard Euclidean distance (L2 norm), represented explicitly as \\|\\|x - y\\|\\|_{L2}, but does not clarify whether the distance calculation involves squared distances or direct Euclidean distances. The reference Python code computes squared Euclidean distances (element-wise squared differences summed).\n - The LaTeX describes a single collection of negative samples (S\u0304), but the reference code uses two separate negative sample groups (neg1_left/right and neg2_left/right) with independent distance calculations.\n", "Missing_details": [ "\n- The LaTeX description does not explicitly mention that for each positive pair (aligned entities), the embeddings should be replicated multiple times (equal to the negative sample size) to correctly match the dimensions of the negative samples. The reference Python code explicitly reshapes and duplicates the indices of positive samples so that each positive pair aligns correctly with multiple negative samples.\n", "\n- The code implments both l1 and l2 norms for distance calculation, but the LaTeX description does not specify the norm used for distance calculation.\n" ], "Mismatched_details": [ "\n- The LaTeX description specifies using the standard Euclidean distance (L2 norm), represented explicitly as \\|\\|x - y\\|\\|_{L2}, but does not clarify whether the distance calculation involves squared distances or direct Euclidean distances. The reference Python code computes squared Euclidean distances (element-wise squared differences summed).\n", "\n- The LaTeX describes a single collection of negative samples (S\u0304), but the reference code uses two separate negative sample groups (neg1_left/right and neg2_left/right) with independent distance calculations.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - embeddings1 (torch.Tensor, Shape: [num_entities_sr, embedding_dim]): Embeddings of entities in the source graph (G1).\n - embeddings2 (torch.Tensor, Shape: [num_entities_tg, embedding_dim]): Embeddings of entities in the target graph (G2).\n - a1_align (np.array, Shape: [num_aligned_pairs,]): Indices of aligned entities in the source graph (G1).\n - a2_align (np.array, Shape: [num_aligned_pairs,]): Indices of aligned entities in the target graph (G2).\n - neg1_left (np.array, Shape: [num_aligned_pairs * neg_samples_size,]): Indices of negative samples for the left side of the first negative sampling strategy.\n - neg1_right (np.array, Shape: [num_aligned_pairs * neg_samples_size,]): Indices of negative samples for the right side of the first negative sampling strategy.\n - neg2_left (np.array, Shape: [num_aligned_pairs * neg_samples_size,]): Indices of negative samples for the left side of the second negative sampling strategy.\n - neg2_right (np.array, Shape: [num_aligned_pairs * neg_samples_size,]): Indices of negative samples for the right side of the second negative sampling strategy.\n - neg_samples_size (int): The number of negative samples per positive sample. \n - loss_norm (str): The norm to use for distance calculation ('l1' or 'l2').\n - pos_margin (float, optional): The positive margin. Defaults to 0.01. (Not used in the current implementation)\n - neg_margin (float, optional): The negative margin (gamma in the paper). Defaults to 3.\n - neg_param (float, optional): Parameter for balancing positive and negative loss. Defaults to 0.2. (Not used in the current implementation)\n - only_pos (bool, optional): Whether to only consider positive loss. Defaults to False. (Not used in the current implementation)\n", "Arguments_list": [ { "name": "embeddings1", "string": "\n- embeddings1 (torch.Tensor, Shape: [num_entities_sr, embedding_dim]): Embeddings of entities in the source graph (G1).\n", "dependency": null }, { "name": "embeddings2", "string": "\n- embeddings2 (torch.Tensor, Shape: [num_entities_tg, embedding_dim]): Embeddings of entities in the target graph (G2).\n", "dependency": null }, { "name": "a1_align", "string": "\n- a1_align (np.array, Shape: [num_aligned_pairs,]): Indices of aligned entities in the source graph (G1).\n", "dependency": null }, { "name": "a2_align", "string": "\n- a2_align (np.array, Shape: [num_aligned_pairs,]): Indices of aligned entities in the target graph (G2).\n", "dependency": null }, { "name": "neg1_left", "string": "\n- neg1_left (np.array, Shape: [num_aligned_pairs * neg_samples_size,]): Indices of negative samples for the left side of the first negative sampling strategy.\n", "dependency": null }, { "name": "neg1_right", "string": "\n- neg1_right (np.array, Shape: [num_aligned_pairs * neg_samples_size,]): Indices of negative samples for the right side of the first negative sampling strategy.\n", "dependency": null }, { "name": "neg2_left", "string": "\n- neg2_left (np.array, Shape: [num_aligned_pairs * neg_samples_size,]): Indices of negative samples for the left side of the second negative sampling strategy.\n", "dependency": null }, { "name": "neg2_right", "string": "\n- neg2_right (np.array, Shape: [num_aligned_pairs * neg_samples_size,]): Indices of negative samples for the right side of the second negative sampling strategy.\n", "dependency": null }, { "name": "neg_samples_size", "string": "\n- neg_samples_size (int): The number of negative samples per positive sample.\n", "dependency": null }, { "name": "loss_norm", "string": "\n- loss_norm (str): The norm to use for distance calculation ('l1' or 'l2').\n", "dependency": null }, { "name": "pos_margin", "string": "\n- pos_margin (float, optional): The positive margin. Defaults to 0.01. (Not used in the current implementation)\n", "dependency": null }, { "name": "neg_margin", "string": "\n- neg_margin (float, optional): The negative margin (gamma in the paper). Defaults to 3.\n", "dependency": null }, { "name": "neg_param", "string": "\n- neg_param (float, optional): Parameter for balancing positive and negative loss. Defaults to 0.2. (Not used in the current implementation)\n", "dependency": null }, { "name": "only_pos", "string": "\n- only_pos (bool, optional): Whether to only consider positive loss. Defaults to False. (Not used in the current implementation)\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File dependency: \n - None\n \n Cross-File dependency: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.sum\n - torch.abs\n - torch.square\n - torch.nn.functional.relu\n - numpy.array\n - numpy.ones\n - torch.tensor\n", "list": [ "torch.tensor", "torch.sum", "torch.abs", "torch.square", "torch.nn.functional.relu", "numpy.array", "numpy.ones" ] }, "Return": { "Return_String": "\nReturns:\n loss (torch.Tensor): The margin-based alignment loss (a scalar value).\n", "Return_list": [ { "name": "loss", "string": "\n- loss (torch.Tensor): The margin-based alignment loss (a scalar value).\n", "dependency": null } ] }, "ori_python_file": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport manifolds\nfrom src.att_layers import GraphAttentionLayer\nimport src.hyp_layers as hyp_layers\nfrom src.layers import GraphConvolution, Linear, get_dim_act, GraphMultiHeadAttLayer, MultiHeadAttention\nfrom utils.sinkhorn_cal import sinkhorn\nfrom src.layers import DoubleEmbedding, GraphMultiHeadAttLayer, MultiHeadAttention\nfrom src.utils import set_random_seed\nimport numpy as np\nimport os, random\nos.environ['PYTHONHASHSEED'] = str(42)\nos.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\nnp.random.seed(42)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\ntorch.use_deterministic_algorithms(True)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nrandom.seed(42)\ntorch.cuda.synchronize()\ndef margin_based_loss(embeddings1, embeddings2, a1_align, a2_align, neg1_left, neg1_right, neg2_left, neg2_right, neg_samples_size, loss_norm, pos_margin=0.01, neg_margin=3, neg_param=0.2, only_pos=False):\n a1_align = np.array(a1_align)\n a2_align = np.array(a2_align)\n t = len(a1_align)\n L = np.ones((t, neg_samples_size)) * (a1_align.reshape((t,1)))\n a1_align = L.reshape((t*neg_samples_size,))\n R = np.ones((t, neg_samples_size)) * (a2_align.reshape((t,1)))\n a2_align = R.reshape((t*neg_samples_size,))\n a1_align = torch.tensor(a1_align, device=embeddings1.device)\n a2_align = torch.tensor(a2_align, device=embeddings1.device)\n neg1_left = torch.tensor(neg1_left, device=embeddings1.device)\n neg1_right = torch.tensor(neg1_right, device=embeddings1.device)\n neg2_left = torch.tensor(neg2_left, device=embeddings1.device)\n neg2_right = torch.tensor(neg2_right, device=embeddings1.device)\n left_x = embeddings1[a1_align.long()]\n right_x = embeddings2[a2_align.long()]\n if loss_norm == \"l1\":\n pos_loss = torch.abs(left_x - right_x)\n elif loss_norm == 'l2':\n pos_loss = torch.square(left_x - right_x)\n pos_loss = torch.sum(pos_loss, dim=1)\n left_x = embeddings1[neg1_left.long()]\n right_x = embeddings2[neg1_right.long()]\n if loss_norm == \"l1\":\n neg_loss_1 = torch.abs(left_x - right_x)\n elif loss_norm == 'l2':\n neg_loss_1 = torch.square(left_x - right_x)\n neg_loss_1 = torch.sum(neg_loss_1, dim=1)\n left_x = embeddings1[neg2_left.long()]\n right_x = embeddings2[neg2_right.long()]\n if loss_norm == \"l1\":\n neg_loss_2 = torch.abs(left_x - right_x)\n elif loss_norm == 'l2':\n neg_loss_2 = torch.square(left_x - right_x)\n neg_loss_2 = torch.sum(neg_loss_2, dim=1)\n loss1 = F.relu(pos_loss + neg_margin - neg_loss_1)\n loss2 = F.relu(pos_loss + neg_margin - neg_loss_2)\n loss1 = torch.sum(loss1)\n loss2 = torch.sum(loss2)\n loss = loss1 + loss2\n return loss\n\ndef euclidean_space_embedding(entity_embedding, adj, attentive_aggregators, multihead_attention, n_head, ent_dim, dropout, res):\n embedding = dropout(entity_embedding)\n embedding_list = []\n if res:\n embedding_list.append(embedding)\n for layer in attentive_aggregators:\n embedding = layer(embedding, adj)\n embedding = F.normalize(embedding, dim=1, p=2)\n embedding_list.append(dropout(embedding))\n if res:\n range_ = len(attentive_aggregators) + 1\n else:\n range_ = len(attentive_aggregators)\n embedding = torch.cat(embedding_list, dim=1).reshape(-1, range_, ent_dim)\n embedding, _ = multihead_attention(embedding, embedding, embedding)\n embedding = torch.mean(embedding, dim=1)\n embedding = embedding.squeeze(1)\n return embedding\n\ndef hyperbolic_space_embedding(entity_embedding, adj, manifold, curvatures, layers):\n x_tan = manifold.proj_tan0(entity_embedding, curvatures[0])\n x_hyp = manifold.expmap0(x_tan, c=curvatures[0])\n input_ = (x_hyp, adj)\n output, _ = layers.forward(input_)\n output = manifold.logmap0(output, c=curvatures[0])\n return output\n\ndef relation_encoding_and_fusion(rel_adj_sr, rel_adj_tg, sr_rel_embedding, tg_rel_embedding, direct):\n if direct:\n rel_adj_sr_in, rel_adj_sr_out = rel_adj_sr[0], rel_adj_sr[1]\n rel_rowsum_sr_in = torch.sum(rel_adj_sr_in.to_dense(), dim=-1).unsqueeze(-1)\n rel_rowsum_sr_out = torch.sum(rel_adj_sr_out.to_dense(), dim=-1).unsqueeze(-1)\n sr_rel_embedding_in = torch.mm(rel_adj_sr_in, sr_rel_embedding)\n sr_rel_embedding_in = sr_rel_embedding_in.div(rel_rowsum_sr_in + 1e-5)\n sr_rel_embedding_out = torch.mm(rel_adj_sr_out, sr_rel_embedding)\n sr_rel_embedding_out = sr_rel_embedding_out.div(rel_rowsum_sr_out + 1e-5)\n sr_rel_embedding = torch.cat([sr_rel_embedding_in, sr_rel_embedding_out], dim=-1)\n rel_adj_tg_in, rel_adj_tg_out = rel_adj_tg[0], rel_adj_tg[1]\n rel_rowsum_tg_in = torch.sum(rel_adj_tg_in.to_dense(), dim=-1).unsqueeze(-1)\n rel_rowsum_tg_out = torch.sum(rel_adj_tg_out.to_dense(), dim=-1).unsqueeze(-1)\n tg_rel_embedding_in = torch.mm(rel_adj_tg_in, tg_rel_embedding)\n tg_rel_embedding_in = tg_rel_embedding_in.div(rel_rowsum_tg_in + 1e-5)\n tg_rel_embedding_out = torch.mm(rel_adj_tg_out, tg_rel_embedding)\n tg_rel_embedding_out = tg_rel_embedding_out.div(rel_rowsum_tg_out + 1e-5)\n tg_rel_embedding = torch.cat([tg_rel_embedding_in, tg_rel_embedding_out], dim=-1)\n else:\n rel_rowsum_sr = torch.sum(rel_adj_sr.to_dense(), dim=-1).unsqueeze(-1)\n rel_rowsum_tg = torch.sum(rel_adj_tg.to_dense(), dim=-1).unsqueeze(-1)\n sr_rel_embedding = torch.mm(rel_adj_sr, sr_rel_embedding)\n tg_rel_embedding = torch.mm(rel_adj_tg, tg_rel_embedding)\n sr_rel_embedding = sr_rel_embedding.div(rel_rowsum_sr)\n tg_rel_embedding = tg_rel_embedding.div(rel_rowsum_tg)\n return sr_rel_embedding, tg_rel_embedding\n\nclass UniEA(nn.Module):\n def __init__(self, num_sr, num_tg, adj_sr, adj_tg, rel_num, rel_adj_sr, rel_adj_tg, args) -> None:\n super().__init__()\n self.num_sr = num_sr\n self.num_tg = num_tg\n self.adj_sr = adj_sr\n self.adj_tg = adj_tg\n self.rel_num = rel_num\n self.rel_adj_sr = rel_adj_sr\n self.rel_adj_tg = rel_adj_tg\n self.ent_dim = args.ent_dim\n self.rel_dim = args.rel_dim\n self.n_head = args.n_head\n self.layer = args.layer\n self.direct = args.direct\n self.res = args.res\n self.manifold_name = args.manifold\n if args.c is not None:\n self.c = torch.tensor([args.c])\n if not args.device == 'cuda':\n self.c = self.c.to(args.device)\n else:\n self.c = nn.Parameter(torch.Tensor([1.]))\n self.manifold = getattr(manifolds, self.manifold_name)()\n assert args.layer > 1\n dims, acts, self.curvatures = hyp_layers.get_dim_act_curv(args)\n self.curvatures.append(self.c)\n hgc_layers = []\n for i in range(len(dims) - 1):\n c_in, c_out = self.curvatures[i], self.curvatures[i + 1]\n in_dim, out_dim = dims[i], dims[i + 1]\n act = acts[i]\n hgc_layers.append(\n hyp_layers.HyperbolicGraphConvolution(\n self.manifold, in_dim, out_dim, c_in, c_out, args.dropout, act, args.bias, args.use_att,\n args.local_agg\n )\n )\n self.layers = nn.Sequential(*hgc_layers)\n self.encode_graph = True\n self.scale = 300\n self.mats_hyper = nn.Parameter(torch.Tensor(args.dim, self.ent_dim), requires_grad=True)\n torch.manual_seed(42)\n nn.init.xavier_uniform_(self.mats_hyper)\n self.mats_hyper2 = nn.Parameter(torch.Tensor(args.dim, self.ent_dim), requires_grad=True)\n torch.manual_seed(42)\n nn.init.xavier_uniform_(self.mats_hyper2)\n self.dropout = nn.Dropout(args.dropout)\n self.entity_embedding = DoubleEmbedding(num_sr=self.num_sr, num_tg=self.num_tg, embedding_dim=self.ent_dim, init_type=args.init_type)\n self.hyper_entity_embedding = DoubleEmbedding(num_sr=self.num_sr, num_tg=self.num_tg, embedding_dim=args.dim,\n init_type=args.init_type)\n self.relation_embedding = DoubleEmbedding(num_sr=self.rel_num, num_tg=self.rel_num, embedding_dim=self.rel_dim, init_type=args.init_type)\n self.attentive_aggregators = nn.ModuleList([GraphMultiHeadAttLayer(in_features=self.ent_dim, out_features=self.ent_dim, n_head=self.n_head, dropout=args.dropout) for i in range(self.layer)])\n self.multihead_attention = MultiHeadAttention(\n n_head=self.n_head,\n d_model=self.ent_dim,\n d_k=self.ent_dim,\n d_v=self.ent_dim,\n dropout=args.dropout\n )\n if self.direct:\n self.proj_head = nn.Sequential(\n nn.Linear(self.ent_dim*self.n_head + self.rel_dim*2, self.ent_dim),\n nn.ReLU(),\n )\n else:\n self.proj_head = nn.Sequential(\n nn.Linear(self.ent_dim*self.n_head + self.rel_dim, self.ent_dim),\n nn.ReLU(),\n )\n \n def cal_ot(self, mm_embeddings, st_embeddings, delta_ot):\n device = delta_ot.device\n number = 10\n mm_dim = mm_embeddings.shape[-1]\n st_dim = st_embeddings.shape[-1]\n mm_dis = torch.ones_like(mm_embeddings[0, :])\n mm_dis = mm_dis / mm_dis.shape[-1]\n st_dis = torch.ones_like(st_embeddings[0, :])\n st_dis = st_dis / st_dis.shape[-1]\n matrix_temp = torch.zeros((number, mm_dim, st_dim))\n with torch.no_grad():\n for i in range(number):\n cost = (mm_embeddings[i, :].reshape(-1, mm_dim) - st_embeddings[i, :].reshape(st_dim,\n -1)) ** 2 * self.scale\n matrix_temp[i, :, :] = sinkhorn(mm_dis, st_dis, cost.t())[0].t()\n return matrix_temp.mean(dim=0).to(device) * st_dim * self.scale + delta_ot\n \n def forward(self, aug_adj1=None, aug_rel_adj1=None, aug_adj2=None, aug_rel_adj2=None, phase=\"norm\"):\n if phase in [\"norm\", \"eval\"]:\n adj_sr, adj_tg, rel_adj_sr, rel_adj_tg = self.adj_sr, self.adj_tg, self.rel_adj_sr, self.rel_adj_tg\n elif phase == \"augment\":\n adj_sr, adj_tg, rel_adj_sr, rel_adj_tg = aug_adj1, aug_adj2, aug_rel_adj1, aug_rel_adj2\n sr_embedding, tg_embedding = self.entity_embedding.weight\n sr_embedding, tg_embedding = self.dropout(sr_embedding), self.dropout(tg_embedding)\n hyper_sr_embedding, hyper_tg_embedding = self.entity_embedding.weight\n sr_rel_embedding, tg_rel_embedding = self.relation_embedding.weight\n sr_rel_embedding, tg_rel_embedding = self.dropout(sr_rel_embedding), self.dropout(tg_rel_embedding)\n sr_rel_embedding, tg_rel_embedding = relation_encoding_and_fusion(rel_adj_sr, rel_adj_tg, sr_rel_embedding, tg_rel_embedding, self.direct)\n sr_embedding = euclidean_space_embedding(sr_embedding, adj_sr, self.attentive_aggregators, self.multihead_attention, self.n_head, self.ent_dim, self.dropout, self.res)\n tg_embedding = euclidean_space_embedding(tg_embedding, adj_tg, self.attentive_aggregators, self.multihead_attention, self.n_head, self.ent_dim, self.dropout, self.res)\n hyper_sr_embedding = hyperbolic_space_embedding(hyper_sr_embedding, adj_sr, self.manifold, self.curvatures, self.layers)\n hyper_tg_embedding = hyperbolic_space_embedding(hyper_tg_embedding, adj_tg, self.manifold, self.curvatures, self.layers)\n sr_embedding = torch.cat([sr_embedding, sr_rel_embedding], dim=-1)\n tg_embedding = torch.cat([tg_embedding, tg_rel_embedding], dim=-1)\n hyper_sr_embedding = torch.cat([hyper_sr_embedding, sr_rel_embedding], dim=-1)\n hyper_tg_embedding = torch.cat([hyper_tg_embedding, tg_rel_embedding], dim=-1)\n return sr_embedding, tg_embedding, hyper_sr_embedding, hyper_tg_embedding\n \n def contrastive_loss(self, embeddings1, embeddings2, ent_num, sim_method=\"cosine\", t=0.08):\n if sim_method == \"cosine\":\n embeddings1_abs = embeddings1.norm(dim=1)\n embeddings2_abs = embeddings2.norm(dim=1)\n logits = torch.einsum('ik,jk->ij', embeddings1, embeddings2) / (\n torch.einsum('i,j->ij', embeddings1_abs, embeddings2_abs) + 1e-5\n )\n logits = logits / t\n elif sim_method == \"inner\":\n logits = torch.mm(embeddings1, embeddings2.T)\n labels = torch.arange(ent_num).to(embeddings1.device)\n loss_1 = F.cross_entropy(logits, labels)\n loss_2 = F.cross_entropy(logits.T, labels)\n loss = (loss_1 + loss_2) / 2\n return loss" } ] }, { "paper_id": 8, "paper_details": { "title": "Exploring Concept Depth: How Large Language Models Acquire Knowledge and Concepts at Different Layers?", "url": "https://arxiv.org/abs/2404.07066" }, "enviorment_name": "CD", "repo_original_url": "https://github.com/luckfort/cd", "project_path": "Benchmark/8-CD/CD-main", "file_organization": "\nCD-main/\n baukit/\n imgsave.py\n __init__.py\n labwidget.py\n nethook.py\n paintwidget.py\n parallelfolder.py\n pbar.py\n pidfile.py\n plotwidget.py\n README.md\n renormalize.py\n runningstats.py\n show.py\n tokendataset.py\n workerpool.py\n dataset/\n cities.csv\n coin_flip.json\n common_claim.csv\n counterfact.csv\n hateeval.tsv\n sarcasm.json\n StrategyQA_task.json\n stsa.binary.test\n stsa.binary.train\n dataset_anchor.py\n dataset.py\n lab_rs/\n Readme.md\n STSA_Llama-7b_32_non-noise_LR.json\n main_anchor.py\n main.py\n models--meta-llama--Llama-2-7b-chat-hf/\n blobs/\n 0fd6895090da1b2ccffdb93964847709a3b31e6b69fe7dc5a480dce37c811b1d\n 451134b2ddc2e78555d1e857518c54b4bdc2e87d\n 54ca0443a890c461f0d7b05fa06ff7a3ed6e1edc\n 66dec18c9f1705b9387d62f8485f4e7d871ca388718786737ed3c72dbfaac9fb\n 9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347\n a0024735c8dd7afe47fe72792b2c4edaff63bd3b\n a6e931b92caff4c79c5c56282f1e89569a0ae558\n cbe75f3ff6fdfd5c5e084d6a4968e6d10ce0490d\n e0cf7ed0d308d91b704d3652d4c2632144035cdd\n refs/\n main\n snapshots/\n f5db02db724555f92da89c216ac04704f23d4590/\n config.json -> ../../blobs/54ca0443a890c461f0d7b05fa06ff7a3ed6e1edc\n generation_config.json -> ../../blobs/e0cf7ed0d308d91b704d3652d4c2632144035cdd\n model-00001-of-00002.safetensors -> ../../blobs/66dec18c9f1705b9387d62f8485f4e7d871ca388718786737ed3c72dbfaac9fb\n model-00002-of-00002.safetensors -> ../../blobs/0fd6895090da1b2ccffdb93964847709a3b31e6b69fe7dc5a480dce37c811b1d\n model.safetensors.index.json -> ../../blobs/cbe75f3ff6fdfd5c5e084d6a4968e6d10ce0490d\n special_tokens_map.json -> ../../blobs/451134b2ddc2e78555d1e857518c54b4bdc2e87d\n tokenizer_config.json -> ../../blobs/a0024735c8dd7afe47fe72792b2c4edaff63bd3b\n tokenizer.json -> ../../blobs/a6e931b92caff4c79c5c56282f1e89569a0ae558\n tokenizer.model -> ../../blobs/9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347\n README.md\n requirements.txt\n run_anchor.py\n run.ipynb\n run.py\n SavedReferenceRun/\n task1/\n output_0.pickle\n utils.py\n", "latex_code_path": "Benchmark/8-CD/arXiv-2404.07066v5", "task_details": [ { "task_id": 0, "indent": 1, "script": "\npython main.py\n", "latex_code": "\n\\section{Analyzing Method}\n\nIn this paper, we design a probing framework to understand how concepts at various levels are encoded within LLMs and investigate whether the internal representations are robust to concepts. For instance, \\autoref{fig:overall} demonstrates the representation project of the Counterfact dataset.\n\n\\subsection{Linear Classifier Probing}\nProbe technology~\\cite{alain2016understanding} is a method for analyzing and evaluating the internal representations of a neural network by applying a specific probe task, typically a classification or regression task, to a particular layer of the model. This technique measures the layer's ability to represent information for the given task, thereby revealing the features and information captured by different layers of the model. Our approach involves extracting the representations from each layer of the large model, training a binary classifier on these representations, and validating its accuracy.\n\nFor one specific task $w$ that contains $n$ questions, the hidden feature set in LLMs is $x \\in \\mathbb{R}^{n \\times d_{model}}$, where $n$ denotes number of samples, and $x^{(i)} \\in \\mathbb{R}^{1\\times d_{model}}$ represent the representation at a certain layer, where $d_{model}$ donate the dimension for the hidden layer representation. Binary label $y^{(i)}$ is set as 0 or 1. The objective function of such a binary Logistic regression classifier probes with L2 regularization can be written as:\n\\begin{equation}\n\\scriptsize\n J(\\theta) = -\\frac{1}{n} \\sum_{i=1}^{n} Cost(\\sigma(x^{(i)}),y^{(i)})+\\frac{\\lambda}{2n}\\sum_{j=1}^{m}\\theta_{j}^2\n\\end{equation}\n\\begin{equation}\n\\scriptsize\n\\begin{array}{cc}\n &Cost(\\sigma(x^{(i)}),y^{(i)}) = y^{(i)} \\log \\left( \\sigma(\\theta^T x^{(i)}) \\right) \\\\\n & + (1 - y^{(i)}) \\log \\left(1 - \\sigma(\\theta^T x^{(i)}) \\right) \n\\end{array}\n\\end{equation}\nwhere $\\theta$ is the parameter in this Logistic regression model, $\\lambda$ is the regularization parameter. The linear model predicts LLM's response to the test set, compared with the true label. This yields a quantification of how well LLMs understand the current depth. If the binary model gets good accuracy at a certain layer, that means the LLM can distinguish true or false in this layer.\n\n", "completion_path": "./main.py", "namespace": "main.analyzing_method", "type": "function", "signature_position": [ 77, 77 ], "body_position": [ 78, 135 ], "ReferenceCode_With_Comments": "\nlist_acc = []\nlist_f1 = []\nlist_auc = []\nrp_logs = [[] for _ in range(tot_layer)]\nrp_questions = [[] for _ in range(tot_layer)]\n\nrp_log_data_list = []\nrp_question_data_list = []\n\n# ---------------------------------------------------------------------------\n# Snippet 1: Collect hidden representations x^{(i)} for positively labeled samples (p_question). The LaTeX snippet specifically references extracting x^{(i)} from a neural model. This code extracts the hidden state of the final token from each layer and stores it for classification.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nfor q in tqdm(p_question):\n input_text = DP.get_prompt(prompt, cot, q)\n with torch.no_grad():\n input_ids = tokenizer(input_text, return_tensors=\"pt\").input_ids\n hs = Model.get_hidden_states(model, tokenizer, input_text)\n\n for i in range(tot_layer):\n hs_i = hs[i, :, :]\n hs_i = hs_i[-1, :].cpu()\n try:\n hs_i = hs_i.numpy()\n except:\n hs_i = hs_i.float().numpy()\n rp_logs[i].append(hs_i)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Similarly, gather hidden representations for negatively labeled samples (n_question). These correspond to x^{(i)} with a binary label y^{(i)}=0 or 1. \n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nfor q in tqdm(n_question):\n input_text = DP.get_prompt(prompt, cot, q)\n with torch.no_grad():\n input_ids = tokenizer(input_text, return_tensors=\"pt\").input_ids\n hs = Model.get_hidden_states(model, tokenizer, input_text)\n\n for i in range(tot_layer):\n hs_i = hs[i, :, :]\n hs_i = hs_i[-1, :].cpu()\n try:\n hs_i = hs_i.numpy()\n except:\n hs_i = hs_i.float().numpy()\n rp_questions[i].append(hs_i)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Convert the stored lists of representations into NumPy arrays for subsequent classification. This operationalizes x in the LaTeX notation, ensuring each element is an array of shape [num_samples, d_model].\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nfor i in range(tot_layer):\n rp_log_data_list.append(np.array([tensor for tensor in rp_logs[i]]))\n rp_question_data_list.append(np.array([tensor for tensor in rp_questions[i]]))\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: For each layer, combine representations from both classes, split the data into training/testing sets, fit a binary classifier, and compute performance metrics (accuracy, F1, and ROC-AUC). This aligns with the LaTeX description of applying a linear probe, but includes an optional Random Forest classifier for comparison.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nlabels_log = np.zeros(len(rp_log_data_list[0]))\nlabels_question = np.ones(len(rp_question_data_list[0]))\nfor i in range(tot_layer):\n rp_log_data_i = rp_log_data_list[i]\n rp_question_data_i = rp_question_data_list[i]\n\n X = np.concatenate((rp_log_data_i, rp_question_data_i), axis=0)\n y = np.concatenate((labels_log, labels_question), axis=0)\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=42)\n\n if args.clf == 'LR':\n classifier = LogisticRegression(penalty='l2')\n elif args.clf == 'RF':\n classifier = RandomForestClassifier(random_state=42)\n\n classifier.fit(X_train, y_train)\n y_pred = classifier.predict(X_test)\n\n accuracy = accuracy_score(y_test, y_pred)\n f1 = f1_score(y_test, y_pred, average='binary')\n y_prob = classifier.predict_proba(X_test)[:, 1] \n roc_auc = roc_auc_score(y_test, y_prob)\n list_acc.append(accuracy)\n list_f1.append(f1)\n list_auc.append(roc_auc)\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Return the evaluation metrics for each layer, reflecting the probing performance. \n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nreturn list_acc, list_f1, list_auc\n# [End Snippet 5]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The hidden representations x^{(i)} are last token's representation in the squence.\n - Data splitting protocol: The LaTeX does not mention splitting data into training/testing sets (60-40 split) using function train_test_split with a random seed of 42.\n - Token position specification: The LaTeX mentions \"hidden feature set x\" but does not specify that only the last token's hidden state should be used.\n - Label assignment convention: The LaTeX states \"binary label y^{(i)} is set as 0 or 1\" but does not specify which class (positive/negative samples) corresponds to 0/1. The reference code uses 0 for p_question (positive) and 1 for n_question (negative).\n\n Mismatched Details:\n - Additional evaluation metrics (F1 and ROC-AUC) are computed, even though the paper only mentions accuracy. \n - The LaTeX snippet focuses only on a Logistic Regression probe with L2 regularization. However. However, the reference Python code includes an optional Random Forest classifier as an alternative for comparison.\n\n", "Missing_details": [ "\n- The hidden representations x^{(i)} are last token's representation in the squence.\n", "\n- Data splitting protocol: The LaTeX does not mention splitting data into training/testing sets (60-40 split) using function train_test_split with a random seed of 42.\n", "\n- Token position specification: The LaTeX mentions \"hidden feature set x\" but does not specify that only the last token's hidden state should be used.\n", "\n- Label assignment convention: The LaTeX states \"binary label y^{(i)} is set as 0 or 1\" but does not specify which class (positive/negative samples) corresponds to 0/1. The reference code uses 0 for p_question (positive) and 1 for n_question (negative).\n" ], "Mismatched_details": [ "\n- Additional evaluation metrics (F1 and ROC-AUC) are computed, even though the paper only mentions accuracy. \n", "\n- The LaTeX snippet focuses only on a Logistic Regression probe with L2 regularization. However. However, the reference Python code includes an optional Random Forest classifier as an alternative for comparison.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - Model (an obeject of the LLM class, defined in utils.py): An instance of the LLM class responsible for handling model-related operations.\n - DP (an obeject of the DataProcessing, defined in dataset.py): Handles dataset-specific preprocessing and prompt generation.\n - tokenizer (AutoTokenizer): Tokenizer instance from the Transformers library for text encoding.\n - p_question (list[String]): List of positive sample questions for probing.\n - n_question (list[String]): List of negative sample questions for probing.\n - tot_layer (int): Total number of layers in the model to be analyzed.\n - cot (str): Chain-of-thought parameter to adjust the style of prompts.\n - model (LLamaForCausalLM): The pre-trained language model instance.\n - args (argparse.Namespace, defined in args_define function in main.py): Arguments specifying configurations such as classifier type, dataset paths, etc.\n", "Arguments_list": [ { "name": "Model", "string": "- Model (an obeject of the LLM class, defined in utils.py): An instance of the LLM class responsible for handling model-related operations.", "dependency": "utils.LLM" }, { "name": "DP", "string": "- DP (an obeject of the DataProcessing, defined in dataset.py): Handles dataset-specific preprocessing and prompt generation.", "dependency": "dataset.DataProcessing" }, { "name": "tokenizer", "string": "- tokenizer (AutoTokenizer): Tokenizer instance from the Transformers library for text encoding.", "dependency": "transformers.AutoTokenizer" }, { "name": "p_question", "string": "- p_question (list[String]): List of positive sample questions for probing.", "dependency": "list" }, { "name": "n_question", "string": "- n_question (list[String]): List of negative sample questions for probing.", "dependency": "list" }, { "name": "tot_layer", "string": "- tot_layer (int): Total number of layers in the model to be analyzed.", "dependency": "int" }, { "name": "cot", "string": "- cot (str): Chain-of-thought parameter to adjust the style of prompts.", "dependency": "str" }, { "name": "model", "string": "- model (LLamaForCausalLM): The pre-trained language model instance.", "dependency": "transformers.LLamaForCausalLM" }, { "name": "args", "string": "- args (argparse.Namespace, defined in args_define() function in main.py): Arguments specifying configurations such as classifier type, dataset paths, etc.", "dependency": "args_define(), main.py" } ] }, "dependency": { "string": "\nDependencies:\n Intra-File:\n - None\n\n Cross-File:\n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - sklearn.metrics.f1_score\n - sklearn.model_selection.train_test_split\n - sklearn.ensemble.RandomForestClassifier\n - numpy.concatenate\n - numpy.array\n - sklearn.linear_model.LogisticRegression\n - numpy.zeros\n - numpy.ones\n - torch.no_grad\n - sklearn.metrics.accuracy_score\n - sklearn.metrics.roc_auc_score\n", "list": [ "sklearn.metrics.f1_score", "sklearn.model_selection.train_test_split", "sklearn.ensemble.RandomForestClassifier", "numpy.concatenate", "numpy.array", "sklearn.linear_model.LogisticRegression", "numpy.zeros", "numpy.ones", "torch.no_grad", "sklearn.metrics.accuracy_score", "sklearn.metrics.roc_auc_score" ] }, "Return": { "Return_String": "\nOutput Variables:\n - list_acc (list[float]): A list containing accuracy scores for each layer's classifier.\n - list_f1 (list[float]): A list containing F1-scores for each layer's classifier.\n - list_auc (list[float]): A list containing ROC-AUC scores for each layer's classifier.\n", "Return_list": [ { "name": "list_acc", "string": "- list_acc (list[float]): A list containing accuracy scores for each layer's classifier." }, { "name": "list_f1", "string": "- list_f1 (list[float]): A list containing F1-scores for each layer's classifier." }, { "name": "list_auc", "string": "- list_auc (list[float]): A list containing ROC-AUC scores for each layer's classifier." } ] }, "ori_python_file": "from dataset import DataProcessing\nimport json\nfrom utils import add_noise, LLM\nimport argparse\nimport os\nimport torch\nfrom transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig\nimport shutil\nimport numpy as np\nimport os, torch\nimport random\nos.environ['PYTHONHASHSEED'] = str(42)\nos.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\nnp.random.seed(42)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\ntorch.use_deterministic_algorithms(True)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nrandom.seed(42)\ntorch.cuda.synchronize()\nif os.path.exists('SavedOutputRun'):\n shutil.rmtree('SavedOutputRun')\ndef args_define():\n parser = argparse.ArgumentParser()\n parser.add_argument('--savepath', type=str, default=\"./lab_rs/\", help=\"Path for save Result\")\n parser.add_argument('--model_path', type=str, default=\"./\")\n parser.add_argument('--dataset', type=str, default='STSA', help=\"Dataset\")\n parser.add_argument('--datapath', type=str, default='./dataset/stsa.binary.train', help=\"Default data path\")\n parser.add_argument('--model', type=str, default='meta-llama/Llama-2-7b-chat-hf', help=\"Which LLM to use\")\n parser.add_argument('--cuda', type=int, default=0, help=\"Cuda ID\")\n parser.add_argument('--quant', type=int, default=32, help=\"Quantization\")\n parser.add_argument('--noise', type=str, default='non-noise', help=\"Whether to add noise\")\n parser.add_argument('--clf', type=str, default='LR', help=\"Classifier\")\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n return args\nargs = args_define()\nif args.quant != 32:\n if args.quant == 8:\n quantization_config1 = BitsAndBytesConfig(load_in_8bit=True)\n elif args.quant == 16:\n pass\n else:\n raise ValueError(\"We don't have this quantization bit! Please try 8, 16, 32.\")\ncache_dir = args.model_path\ntokenizer = AutoTokenizer.from_pretrained(args.model, cache_dir=cache_dir)\nif args.quant == 32:\n model = AutoModelForCausalLM.from_pretrained(args.model, cache_dir=cache_dir)\nelif args.quant == 8:\n model = AutoModelForCausalLM.from_pretrained(args.model, quantization_config=quantization_config1,\n cache_dir=cache_dir)\nelif args.quant == 16:\n model = AutoModelForCausalLM.from_pretrained(args.model, torch_dtype=torch.bfloat16, cache_dir=cache_dir)\nelse:\n raise ValueError(\"We don't have this quantization bit! Please try 8, 16, 32.\")\nfile_path = args.datapath\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score, roc_auc_score, f1_score\nfrom tqdm import tqdm\nmodel_2_layer = {\"google/gemma-7b\": 28, \"google/gemma-2b\": 18, \"meta-llama/Llama-2-7b-chat-hf\": 32,\n \"meta-llama/Llama-2-13b-chat-hf\": 40, \"meta-llama/Llama-2-70b-chat-hf\": 80,\n \"Qwen/Qwen1.5-0.5B\": 24, \"Qwen/Qwen1.5-1.8B\": 24, \"Qwen/Qwen1.5-4B\": 40,\n \"Qwen/Qwen1.5-7B\": 32, \"Qwen/Qwen1.5-14B\": 40, \"Qwen/Qwen1.5-72B\": 80}\ntot_layer = model_2_layer[args.model]\nDP = DataProcessing(data_path=args.datapath, data_name=args.dataset, noise=args.noise)\np_question, n_question, prompt, cot = DP.dispacher()\nModel = LLM(cuda_id=args.cuda, layer_num=tot_layer, quant=args.quant)\nif args.TestCode:\n p_question = p_question[:500]\n n_question = n_question[:500]\n\ndef analzing_method(Model, DP, tokenizer, p_question, n_question, tot_layer, cot, model, args):\n list_acc = []\n list_f1 = []\n list_auc = []\n rp_logs = [[] for _ in range(tot_layer)]\n rp_questions = [[] for _ in range(tot_layer)]\n rp_log_data_list = []\n rp_question_data_list = []\n for q in tqdm(p_question):\n input_text = DP.get_prompt(prompt, cot, q)\n with torch.no_grad():\n input_ids = tokenizer(input_text, return_tensors=\"pt\").input_ids\n hs = Model.get_hidden_states(model, tokenizer, input_text)\n for i in range(tot_layer):\n hs_i = hs[i, :, :]\n hs_i = hs_i[-1, :].cpu()\n try:\n hs_i = hs_i.numpy()\n except:\n hs_i = hs_i.float().numpy()\n rp_logs[i].append(hs_i)\n for q in tqdm(n_question):\n input_text = DP.get_prompt(prompt, cot, q)\n with torch.no_grad():\n input_ids = tokenizer(input_text, return_tensors=\"pt\").input_ids\n hs = Model.get_hidden_states(model, tokenizer, input_text)\n for i in range(tot_layer):\n hs_i = hs[i, :, :]\n hs_i = hs_i[-1, :].cpu()\n try:\n hs_i = hs_i.numpy()\n except:\n hs_i = hs_i.float().numpy()\n rp_questions[i].append(hs_i)\n for i in range(tot_layer):\n rp_log_data_list.append(np.array([tensor for tensor in rp_logs[i]]))\n rp_question_data_list.append(np.array([tensor for tensor in rp_questions[i]]))\n labels_log = np.zeros(len(rp_log_data_list[0]))\n labels_question = np.ones(len(rp_question_data_list[0]))\n for i in range(tot_layer):\n rp_log_data_i = rp_log_data_list[i]\n rp_question_data_i = rp_question_data_list[i]\n X = np.concatenate((rp_log_data_i, rp_question_data_i), axis=0)\n y = np.concatenate((labels_log, labels_question), axis=0)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=42)\n if args.clf == 'LR':\n classifier = LogisticRegression(penalty='l2')\n elif args.clf == 'RF':\n classifier = RandomForestClassifier(random_state=42)\n classifier.fit(X_train, y_train)\n y_pred = classifier.predict(X_test)\n accuracy = accuracy_score(y_test, y_pred)\n f1 = f1_score(y_test, y_pred, average='binary')\n y_prob = classifier.predict_proba(X_test)[:, 1]\n roc_auc = roc_auc_score(y_test, y_prob)\n list_acc.append(accuracy)\n list_f1.append(f1)\n list_auc.append(roc_auc)\n return list_acc, list_f1, list_auc\n\nlist_acc, list_f1, list_auc = analzing_method(Model, DP, tokenizer, p_question, n_question, tot_layer, cot, model, args)\ndict_res = {\"Acc\": list_acc, \"F1\": list_f1, \"AUC\": list_auc}\ndef LoadDataset(filename):\n with open(filename, 'r+') as f:\n read_dict = f.read()\n f.close()\n read_dict = json.loads(read_dict)\n return read_dict\ndef SaveDataset(filename, dataset):\n dict_json = json.dumps(dataset)\n with open(filename, 'w+') as f:\n f.write(dict_json)\n f.close()\nmodel_name_refresh = {\"google/gemma-7b\": \"gemma-7b\", \"google/gemma-2b\": \"gemma-2b\",\n \"meta-llama/Llama-2-7b-chat-hf\": \"Llama-7b\", \"meta-llama/Llama-2-13b-chat-hf\": \"Llama-13b\",\n \"meta-llama/Llama-2-70b-chat-hf\": \"Llama-70b\", \"Qwen/Qwen1.5-0.5B\": \"Qwen-0.5B\",\n \"Qwen/Qwen1.5-1.8B\": \"Qwen-1.8B\", \"Qwen/Qwen1.5-4B\": \"Qwen-4B\", \"Qwen/Qwen1.5-7B\": \"Qwen-7B\",\n \"Qwen/Qwen1.5-14B\": \"Qwen-14B\", \"Qwen/Qwen1.5-72B\": \"Qwen-72B\"}\nmodel_name = model_name_refresh[args.model]\nprint(list_acc)\nprint(list_f1)\nprint(list_auc)" } ] }, { "paper_id": 9, "paper_details": { "title": "TRANSMI: A Framework to Create Strong Baselines from Multilingual Pretrained Language Models for Transliterated Data", "url": "https://arxiv.org/abs/2405.09913" }, "enviorment_name": "TransMI", "repo_original_url": "https://github.com/cisnlp/transmi", "project_path": "Benchmark/9-TransMI/TransMI-main", "file_organization": "\nTransMI-main/\n evaluation/\n retrieval/\n bible_lang_list.txt\n evaluate_retrieval_all_tatoeba.py\n evaluate_retrieval_all_tatoeba.sh\n evaluate_retrieval_bible.py\n evaluate_retrieval_bible.sh\n tatoeba_lang_list.txt\n sib200/\n evaluate_sib_all.py\n evaluate_sib_all.sh\n sib200_lang_list.txt\n tagging/\n evaluate_all_ner.py\n evaluate_all_ner.sh\n evaluate_all_pos.py\n evaluate_all_pos.sh\n ner_lang_list.txt\n pos_lang_list.txt\n run_tag.py\n utils_tag.py\n taxi1500/\n evaluate_all.py\n evaluate_all.sh\n texi1500_lang_list.txt\n images/\n framework.pdf\n framework.png\n models/\n xlm-roberta-base-with-transliteration-max/\n config.json\n pytorch_model.bin\n sentencepiece.bpe.model\n special_tokens_map.json\n tokenizer_config.json\n tokenizer.json\n README.md\n sentencepiece_model_pb2.py\n temp/\n sentence_roman.txt\n sentence.txt\n transmi.py\n uroman1.py\n", "latex_code_path": "Benchmark/9-TransMI/arXiv-2405.09913v2", "task_details": [ { "task_id": 0, "indent": 1, "script": "\npython transmi.py\n", "latex_code": "\n\\subsection{Merge New Vocabulary}\nOnce we obtain $T$, we can modify the original vocabulary\n$V^{\\text{orig}}$ by adding the subword transliterations\n$v_i$. However, we need to consider the possible\ntransliteration ambiguity while merging. For subword\ntransliterations that already exist in $V^{\\text{orig}}$,\nnothing needs to be done\n-- this applies to all\nsubwords in Latin script without any\ndiacritics. For each subword transliteration $v'$ that has\na one-to-one relation to a $w'$, i.e.,\n$\\forall (v, w, s) \\in T: v=v'\\Rightarrow w=w'$,\nwe can simply add it with its\nassociated score to the vocabulary table.\n\n\nFor each of the remaining subwords $v'$,\nwe first define a new set of triplets\n$U(v') := \\{ (v,w,s) \\in T | v=v'\\}$.\nThen, to address the transliteration\nambiguity, we propose three different modes\nto merge\nthem into the vocabulary.\n\n\\paragraph{Min-Merge Mode} In this mode, we select\nthe triplet whose score $s'$ is the \\textbf{lowest} for the \ntransliteration $v'$:\n$$s'\\dnrm{min}(v') = \\min_{(v,w,s) \\in U(v')}s$$\nThis mode will be favorable to preserve the less frequent\nsubwords. Adding the subword transliteration\n$v'$ and its associated score $s'\\dnrm{min}(v')$ to the vocabulary\ntable is likely to alter the tokenizer's behavior negatively.\nAs a consequence, we\nexpect this mode will perform worst\namong all modes.\n\n\\paragraph{Max-Merge Mode}\nIn contrast to Min-Merge Mode,\nthis mode selects the triplet\n$(v', w', s') \\in T$ whose score is the \\textbf{highest}:\n$$s'\\dnrm{max}(v') = \\max_{(v,w,s) \\in U(v')}s$$\nFor high-frequency subwords,\nthis\nmode replicates the previous tokenization behavior\nfor the original script: after transliteration,\nwe are likely to obtain the same tokenization.\nTherefore, we expect this mode will achieve the\nbest performance.\n\n\\paragraph{Average-Merge Mode}\nThis mode \\textbf{averages} the scores of all triplets containing $v'$.\n$$ s'\\dnrm{avg}(v') = \\frac{\\sum_{(v,w,s) \\in U(v')}s}{|U(v')|}$$\nWe then add\nsubword $v'$ with score $ s'\\dnrm{avg}(v')$ to the vocabulary.\nAverage-Merge Mode brings amount a change in tokenizer behavior that lies between Min-Merge Mode and Max-Merge Mode.\\footnote{As is common in vocabulary extension and tokenizer merging\n\\citep{imanigooghari-etal-2023-glot500,lin2024mala}, we do\nnot renormalize the modified scores (to ensure the new\nunigram distribution is a proper probability distribution)\nbecause the tokenization behavior is only determined by the\norder of scores.}\n", "completion_path": "./transmi.py", "namespace": "transmi.get_new_vocab_score", "type": "function", "signature_position": [ 44, 44 ], "body_position": [ 45, 69 ], "ReferenceCode_With_Comments": "\nnew_vocab_score_dict = {} # Container for updated vocabulary scores.\nvocab_score_dict = dict(vocab_score_list)\n\nfor i in range(len(vocab_score_list)):\n transli = origin_to_trans[vocab_score_list[i][0]] # Get transliterated subword.\n\n # -----------------------------------------------------------------------\n # Snippet 1: Here, we check if v' is found in the trans_to_origin mapping.\n # If it is, we look at whether there is a one-to-one or a one-to-many\n # relation. The LaTeX states that if |U(v')| = 1, we directly use the\n # original score. Otherwise, we apply the specified merge mode to\n # compute s'(v') via min, max, or average of the original scores.\n # -----------------------------------------------------------------------\n # [Begin Snippet 1]\n if transli in trans_to_origin:\n \n # One-to-one transliteration mapping\n if len(trans_to_origin[transli]) == 1:\n score = vocab_score_list[i][1]\n\n # Multiple mappings (transliteration ambiguity)\n else:\n score_list = []\n for source in trans_to_origin[transli]:\n score_list.append(vocab_score_dict[source])\n\n if merge_mode == 'max':\n score = max(score_list)\n elif merge_mode == 'min':\n score = min(score_list)\n elif merge_mode == \"average\":\n score = sum(score_list) / len(score_list)\n else:\n raise NotImplementedError\n else:\n continue\n # [End Snippet 1]\n\n new_vocab_score_dict[transli] = score\n\n# ---------------------------------------------------------------------------\n# Snippet 2: After assigning s'(v') to all new subwords, we convert the\n# dictionary into a list and sort it in descending order. This final step\n# aligns with the LaTeX concept of adding subword transliterations to the\n# vocabulary according to their assigned scores, ensuring that subwords with\n# higher scores appear first.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nnew_vocab_score_list = [[x1, x2] for x1, x2 in new_vocab_score_dict.items()] # Convert dict to list.\nnew_vocab_score_list = sorted(new_vocab_score_list, key=lambda item: item[1], reverse=True) # Sort by score.\n\nreturn new_vocab_score_list\n# [End Snippet 2]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX description lacks explicit instructions for handling transliterated subwords that do not directly originate from the original vocabulary (identity mappings). The reference Python code explicitly ignores such cases by iterating only through transliterations explicitly obtained from original subwords via the 'origin_to_trans' mapping.\n - The LaTeX description does not explicitly mention how to handle transliterated tokens whose original subwords are absent from the provided vocabulary (i.e., tokens without scores). The reference Python implementation explicitly skips such cases.\n - The LaTeX does not explicitly clarify the behavior when exactly one transliterated token maps to exactly one original token. Although implied, the LaTeX lacks clarity in explicitly stating that such transliterations should directly inherit the original token's score without applying merge operations. The Python reference code explicitly implements this logic.\n - The LaTeX description suggests that ambiguity resolution should be done by forming the set U(v') for each transliterated subword v'. However, it does not specify clearly that ambiguity resolution should be limited strictly to subwords present in the original vocabulary (as done in the reference Python code).\n - the code includes an explicit sorting operation to arrange the final vocabulary in descending order of scores.\n\n Mismatched Details:\n - LaTeX states that existing transliterated subwords \"need nothing to be done,\" but the reference code recomputes their scores even when they exist in the original vocabulary if they have transliteration ambiguity.\n", "Missing_details": [ "\n- The LaTeX description lacks explicit instructions for handling transliterated subwords that do not directly originate from the original vocabulary (identity mappings). The reference Python code explicitly ignores such cases by iterating only through transliterations explicitly obtained from original subwords via the 'origin_to_trans' mapping.", "\n- The LaTeX description does not explicitly mention how to handle transliterated tokens whose original subwords are absent from the provided vocabulary (i.e., tokens without scores). The reference Python implementation explicitly skips such cases.", "\n- The LaTeX does not explicitly clarify the behavior when exactly one transliterated token maps to exactly one original token. Although implied, the LaTeX lacks clarity in explicitly stating that such transliterations should directly inherit the original token's score without applying merge operations. The Python reference code explicitly implements this logic.", "\n- The LaTeX description suggests that ambiguity resolution should be done by forming the set U(v') for each transliterated subword v'. However, it does not specify clearly that ambiguity resolution should be limited strictly to subwords present in the original vocabulary (as done in the reference Python code).", "\n- the code includes an explicit sorting operation to arrange the final vocabulary in descending order of scores." ], "Mismatched_details": [ "\n- LaTeX states that existing transliterated subwords \"need nothing to be done,\" but the reference code recomputes their scores even when they exist in the original vocabulary if they have transliteration ambiguity." ] }, "Arguments": { "string": "\nInput Variables:\n - vocab_score_list (list[list]) : each list within vocab_score_list contains the original subword and their respective score, i.e. [[subword: str, score: float], ...].\n - origin_to_trans (dict): A mapping from original subwords (str) to their transliterated forms (str).\n - trans_to_origin (dict): A mapping from transliterated subwords (str) to a list of original subwords (list of str).\n - merge_mode (str): The merge strategy ('max', 'min', 'average') to handle transliteration ambiguity.\n", "Arguments_list": [ { "name": "vocab_score_dict", "string": "- vocab_score_list (list[list]) : each list within vocab_score_list contains the original subword and their respective score, i.e. [[subword: str, score: float], ...].", "dependency": null }, { "name": "origin_to_trans", "string": "- origin_to_trans (dict): A mapping from original subwords (str) to their transliterated forms (str).", "dependency": null }, { "name": "trans_to_origin", "string": "- trans_to_origin (dict): A mapping from transliterated subwords (str) to a list of original subwords (list of str).", "dependency": null }, { "name": "merge_mode", "string": "- merge_mode (str): The merge strategy ('max', 'min', 'average') to handle transliteration ambiguity.", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File Dependency: \n - None\n\n Cross-File Dependency: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs: \n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - new_vocab_score_list (list): A sorted list of subwords and their updated scores, in descending order of scores.\n Format: [[subword: str, score: float], ...].\n", "Return_list": [ { "name": "new_vocab_score_list", "string": "\n- new_vocab_score_list (list): A sorted list of subwords and their updated scores, in descending order of scores.\n Format: [[subword: str, score: float], ...].\n" } ] }, "ori_python_file": "import argparse\nimport os\nfrom uroman1 import UromanWrapper\nfrom transformers import AutoModelForMaskedLM, AutoTokenizer\nfrom transformers import XLMRobertaTokenizer, AutoModelForMaskedLM\nimport sentencepiece_model_pb2 as sp_model\nimport glob\nimport numpy as np\nimport json\nimport torch\ndef initialize_subword_embeddings(\n model,\n token_to_id_dict_old,\n id_to_token_dict_old,\n token_to_id_dict_new,\n trans_to_origin,\n new_vocab_score_list,\n merge_mode\n):\n embeddings = model.get_input_embeddings().weight.detach().numpy()\n new_embeddings = np.zeros((len(token_to_id_dict_new), embeddings.shape[1]), dtype=embeddings.dtype)\n for i in range(len(token_to_id_dict_old)):\n idx = token_to_id_dict_new[id_to_token_dict_old[i]]\n new_embeddings[idx] = embeddings[i]\n for i, (token, score) in enumerate(new_vocab_score_list):\n if i % 1000 == 0:\n print(f\"{i}, {token}...\")\n idx = token_to_id_dict_new[token]\n source_tokens = trans_to_origin[token]\n if len(source_tokens) == 1:\n new_embeddings[idx] = embeddings[token_to_id_dict_old[source_tokens[0]]]\n else:\n if merge_mode == 'max':\n new_embeddings[idx] = embeddings[token_to_id_dict_old[source_tokens[0]]]\n elif merge_mode == 'min':\n new_embeddings[idx] = embeddings[token_to_id_dict_old[source_tokens[-1]]]\n elif merge_mode == 'average':\n emb = np.zeros(embeddings.shape[1])\n for old_index in [token_to_id_dict_old[source] for source in source_tokens]:\n emb += embeddings[old_index]\n new_embeddings[idx] = emb / len(source_tokens)\n return new_embeddings\n\ndef get_new_vocab_score(vocab_score_list, origin_to_trans, trans_to_origin, merge_mode):\n new_vocab_score_dict = {}\n vocab_score_dict = dict(vocab_score_list)\n for i in range(len(vocab_score_list)):\n transli = origin_to_trans[vocab_score_list[i][0]]\n if transli in trans_to_origin:\n if len(trans_to_origin[transli]) == 1:\n score = vocab_score_list[i][1]\n else:\n score_list = []\n for source in trans_to_origin[transli]:\n score_list.append(vocab_score_dict[source])\n if merge_mode == 'max':\n score = max(score_list)\n elif merge_mode == 'min':\n score = min(score_list)\n elif merge_mode == \"average\":\n score = sum(score_list) / len(score_list)\n else:\n raise NotImplementedError\n else:\n continue\n new_vocab_score_dict[transli] = score\n new_vocab_score_list = [[x1, x2] for x1, x2 in new_vocab_score_dict.items()]\n new_vocab_score_list = sorted(new_vocab_score_list, key=lambda item: item[1], reverse=True)\n return new_vocab_score_list\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--model_name', default='xlm-roberta-base')\n parser.add_argument('--merge_mode', default='max')\n parser.add_argument('--save_path', default='./models')\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n target_path = args.save_path + f\"/{args.model_name.split('/')[-1]}-with-transliteration-{args.merge_mode}\"\n if os.path.exists(target_path):\n pass\n else:\n os.makedirs(target_path)\n tokenizer = AutoTokenizer.from_pretrained(args.model_name)\n model = AutoModelForMaskedLM.from_pretrained(args.model_name)\n tokenizer.save_pretrained(target_path)\n model.save_pretrained(target_path)\n original_m = sp_model.ModelProto()\n original_m.ParseFromString(open(f\"{target_path}/sentencepiece.bpe.model\", 'rb').read())\n vocab = sorted(tokenizer.get_vocab().items(), key=lambda x: x[1], reverse=False)\n vocab_list = [x[0] for x in vocab]\n if args.TestCode:\n vocab_list = vocab_list[:1000]\n roman = UromanWrapper()\n transliterated_vocab = roman.romanize(vocab_list)\n origin_to_trans = dict(zip(vocab_list, transliterated_vocab))\n new_tokens = set(transliterated_vocab).difference(set(vocab_list))\n new_tokens = new_tokens - set([''])\n print(\"Number of newly added tokens: \", len(new_tokens))\n new_tokens = list(new_tokens)\n print(\"Building transliteration dictionary ...\")\n trans_to_origin = {}\n for index, token in enumerate(new_tokens):\n source = []\n for i in range(len(transliterated_vocab)):\n if token == transliterated_vocab[i]:\n source.append(vocab_list[i])\n trans_to_origin[token] = source\n with open(f\"{target_path}/tokenizer.json\", 'r') as file:\n tokenizer_data = json.load(file)\n if args.TestCode:\n vocab_tokenizer_data = tokenizer_data['model']['vocab']\n vocab_tokenizer_data_new = list()\n for i in range(len(vocab_tokenizer_data)):\n if vocab_tokenizer_data[i][0] in vocab_list:\n vocab_tokenizer_data_new.append(vocab_tokenizer_data[i])\n tokenizer_data['model']['vocab'] = vocab_tokenizer_data_new\n vocab_score_dict = tokenizer_data['model']['vocab']\n new_vocab_score_list = get_new_vocab_score(vocab_score_dict, origin_to_trans, trans_to_origin, args.merge_mode)\n add_cnt = 0\n piece_d = {piece.piece: 0 for piece in original_m.pieces}\n for (piece, score) in new_vocab_score_list:\n if piece not in piece_d:\n piece_to_add = sp_model.ModelProto().SentencePiece()\n piece_to_add.piece = piece\n piece_to_add.score = score\n original_m.pieces.append(piece_to_add)\n add_cnt += 1\n if not args.TestCode:\n file_paths = glob.glob(os.path.join(target_path, '*'))\n for file_path in file_paths:\n if os.path.isfile(file_path):\n os.remove(file_path)\n new_spm_save_dir = f\"{target_path}/sentencepiece.bpe.model\"\n with open(new_spm_save_dir, 'wb') as f:\n f.write(original_m.SerializeToString())\n tokenizer = XLMRobertaTokenizer.from_pretrained(args.model_name)\n tokenizer.vocab_file = new_spm_save_dir\n tokenizer.sp_model.load(tokenizer.vocab_file)\n if not args.TestCode:\n tokenizer.save_pretrained(target_path)\n tokenizer_old = XLMRobertaTokenizer.from_pretrained(args.model_name)\n tokenizer_new = XLMRobertaTokenizer.from_pretrained(target_path)\n token_to_id_dict_old = dict(sorted(tokenizer_old.get_vocab().items(), key=lambda item: item[1]))\n id_to_token_dict_old = {idx: token for token, idx in token_to_id_dict_old.items()}\n token_to_id_dict_new = dict(sorted(tokenizer_new.get_vocab().items(), key=lambda item: item[1]))\n id_to_token_dict_new = {idx: token for token, idx in token_to_id_dict_new.items()}\n new_vocab_score_list_1 = list()\n for i in range(len(new_vocab_score_list)):\n if new_vocab_score_list[i][0] in token_to_id_dict_new:\n new_vocab_score_list_1.append(new_vocab_score_list[i])\n new_vocab_score_list = new_vocab_score_list_1\n new_embeddings = initialize_subword_embeddings(\n model,\n token_to_id_dict_old,\n id_to_token_dict_old,\n token_to_id_dict_new,\n trans_to_origin,\n new_vocab_score_list,\n args.merge_mode\n )" }, { "task_id": 1, "indent": 1, "script": "\npython transmi.py\n", "latex_code": "\n\\subsection{Subword Embedding Initialization}\nThe last stage deals with embedding initialization for the\nnewly introduced subwords, which are transliterations of the subwords in the original vocabulary. \nTherefore, we aim to make full use of the\nknowledge encoded in the original subword embedding matrix\n$\\boldsymbol{E}^{\\text{orig}}$ to avoid any sort of\ntraining. To achieve this, we create an additional embedding\nmatrix $\\boldsymbol{E}^{\\text{add}}$ for the new subwords\nand initialize the embedding for each subword based on the\n\\textbf{correspondence} we obtain in the previous vocabulary merge\nstage. Specifically, we directly copy the original embedding\nfor those new subwords that have a one-to-one\ntransliteration relation. \nFor the rest of the subwords, we\ninitialize their embeddings according to which mode is used\nin the last stage; this makes the resulting embeddings\nconsistent with\nthe updated tokenizer behavior.\n\n\\paragraph{Min-Merge Mode}\nIn Min-Merge Mode, we selected\nthe triple $(v',s'\\dnrm{min}(v'),w')$.\nCorrespondingly, \nwe initialize the embedding of $v'$ as\n$w'$: $\\boldsymbol{E}^{\\text{add}}_{v'}\n= \\boldsymbol{E}^{\\text{orig}}_{w'}$.\n\n\\paragraph{Max-Merge Mode}\nIn Max-Merge Mode, we selected\nthe triple $(v',s'\\dnrm{max}(v'),w')$.\nCorrespondingly, \nwe initialize the embedding of $v'$ as\n$w'$: $\\boldsymbol{E}^{\\text{add}}_{v'}\n= \\boldsymbol{E}^{\\text{orig}}_{w'}$.\n\n\\paragraph{Average-Merge Mode}\nIn Average-Merge Mode, we\naveraged the scores of all $w'$ that are mapped to $v'$,\ni.e., we averaged the scores in $U(v')$.\nCorrespondingly, \nwe initialize the embedding of $v'$ as\nthe average of the $w'$:\n$$\\boldsymbol{E}^{\\text{add}}_{v'}= \\frac{\\sum_{(v,w,s) \\in U(v')}\\boldsymbol{E}^{\\text{orig}}_{w}}{|U(v')|}$$.\n\nBy choosing any mode, each embedding in\n$\\boldsymbol{E}^{\\text{add}}$ is carefully initialized, and\nin the same representation space as\n$\\boldsymbol{E}^{\\text{orig}}$. \n", "completion_path": "./transmi.py", "namespace": "transmi.initialize_subword_embeddings", "type": "function", "signature_position": [ 11, 19 ], "body_position": [ 20, 42 ], "ReferenceCode_With_Comments": "\n\nembeddings = model.get_input_embeddings().weight.detach().numpy()\nnew_embeddings = np.zeros((len(token_to_id_dict_new), embeddings.shape[1]), dtype=embeddings.dtype)\n\nfor i in range(len(token_to_id_dict_old)):\n idx = token_to_id_dict_new[id_to_token_dict_old[i]]\n new_embeddings[idx] = embeddings[i]\n\n# -----------------------------------------------------------------------------\n# Snippet 1: For new transliterated subwords, we look up their original counterparts\n# in trans_to_origin. If there is only one counterpart, the embedding is copied from\n# the single source subword. This matches the LaTeX reference to one-to-one\n# transliteration where E^{add}_{v'} = E^{orig}_{w'}.\n# -----------------------------------------------------------------------------\n# [Begin Snippet 1]\nfor i, (token, score) in enumerate(new_vocab_score_list):\n if i % 1000 == 0:\n print(f\"{i}, {token}...\")\n\n idx = token_to_id_dict_new[token]\n source_tokens = trans_to_origin[token]\n\n if len(source_tokens) == 1: # One-to-one case\n new_embeddings[idx] = embeddings[token_to_id_dict_old[source_tokens[0]]]\n # [End Snippet 1]\n\n # -----------------------------------------------------------------------------\n # Snippet 2: If multiple original subwords map to the same transliteration,\n # we apply Min-, Max-, or Average-Merge Mode. The LaTeX states that the embedding\n # for v' must be set to E^{orig}_{w'} corresponding to the chosen triple or the\n # average of all w' if 'average' mode is used.\n # -----------------------------------------------------------------------------\n # [Begin Snippet 2]\n else: # Multiple original correspondences\n if merge_mode == 'max':\n new_embeddings[idx] = embeddings[token_to_id_dict_old[source_tokens[0]]]\n elif merge_mode == 'min':\n new_embeddings[idx] = embeddings[token_to_id_dict_old[source_tokens[-1]]]\n elif merge_mode == 'average':\n emb = np.zeros(embeddings.shape[1])\n for old_index in [token_to_id_dict_old[source] for source in source_tokens]:\n emb += embeddings[old_index]\n new_embeddings[idx] = emb / len(source_tokens)\n# [End Snippet 2]\n\n# -----------------------------------------------------------------------------\n# Snippet 3: The function returns the matrix E^{add}, which completes the embedding\n# initialization phase for newly added subwords (v') described in the LaTeX.\n# -----------------------------------------------------------------------------\n# [Begin Snippet 3]\nreturn new_embeddings\n# [End Snippet 3]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX description does not specify how to handle embeddings for subwords that already exist in both the original and new vocabularies (i.e., subwords unchanged by transliteration). The reference Python code explicitly copies these unchanged embeddings directly from the original embedding matrix (E^{orig}) to the new embedding matrix (E^{add}).\n - The LaTeX description omits the explicit use and importance of `new_vocab_score_list`, which contains the ordering of tokens and their corresponding scores. In the reference Python code, the ordering provided by `trans_to_origin` is determined by scores, essential for correctly selecting embeddings in 'max' and 'min' merge modes.\n - The LaTeX does not specify how the original vocabulary indices are mapped to new vocabulary indices. The reference code explicitly uses 'id_to_token_dict_old' and 'token_to_id_dict_new' to align embeddings for original tokens.\n \n Mismatched Details:\n - The LaTeX code ambiguously mentions selecting embeddings for 'max' and 'min' merge modes based on triples involving scores (e.g., $(v', s'_{min}(v'), w')$). However, it does not clarify explicitly that the candidate original tokens (`w'`) are sorted or ordered based on these scores before embedding selection. In contrast, the reference Python code explicitly assumes the order of tokens provided by `trans_to_origin` reflects descending scores, ensuring correct selection of embeddings for 'max' (highest score) and 'min' (lowest score) merge modes.\n", "Missing_details": [ "\n- The LaTeX description does not specify how to handle embeddings for subwords that already exist in both the original and new vocabularies (i.e., subwords unchanged by transliteration). The reference Python code explicitly copies these unchanged embeddings directly from the original embedding matrix (E^{orig}) to the new embedding matrix (E^{add}).", "\n- The LaTeX description omits the explicit use and importance of `new_vocab_score_list`, which contains the ordering of tokens and their corresponding scores. In the reference Python code, the ordering provided by `trans_to_origin` is determined by scores, essential for correctly selecting embeddings in 'max' and 'min' merge modes.", " \n- The LaTeX does not specify how the original vocabulary indices are mapped to new vocabulary indices. The reference code explicitly uses 'id_to_token_dict_old' and 'token_to_id_dict_new' to align embeddings for original tokens." ], "Mismatched_details": [ "\n- The LaTeX code ambiguously mentions selecting embeddings for 'max' and 'min' merge modes based on triples involving scores (e.g., $(v', s'_{min}(v'), w')$). However, it does not clarify explicitly that the candidate original tokens (`w'`) are sorted or ordered based on these scores before embedding selection. In contrast, the reference Python code explicitly assumes the order of tokens provided by `trans_to_origin` reflects descending scores, ensuring correct selection of embeddings for 'max' (highest score) and 'min' (lowest score) merge modes." ] }, "Arguments": { "string": "\nInput Variables:\n - model (an object of XLMRobertaForMaskedLM): A model object containing an embedding layer. Used to extract the original subword embeddings.\n - token_to_id_dict_old (dict): A dictionary mapping original vocabulary tokens to their respective indices.\n - id_to_token_dict_old (dict): A dictionary mapping original indices to their respective tokens. Reverse of token_to_id_dict_old.\n - token_to_id_dict_new (dict): A dictionary mapping new vocabulary tokens to their respective indices.\n - trans_to_origin (dict): A mapping from new subwords to their corresponding original subwords (one-to-one or one-to-many relations).\n - new_vocab_score_list (List[List]): A list of [token, score] pairs for the new vocabulary, where:\n - `token` is the new subword.\n - `score` indicates its importance or relevance (used for monitoring progress during initialization).\n - merge_mode (str): Specifies how to handle new subwords with multiple original correspondences. Options are:\n - 'max': Use the embedding of the most probable original subword.\n - 'min': Use the embedding of the least probable original subword.\n - 'average': Average the embeddings of all mapped original subwords.\n", "Arguments_list": [ { "name": "model", "string": "- model (an object of XLMRobertaForMaskedLM): A model object containing an embedding layer. Used to extract the original subword embeddings.", "dependency": null }, { "name": "token_to_id_dict_old", "string": "- token_to_id_dict_old (dict): A dictionary mapping original vocabulary tokens to their respective indices.", "dependency": null }, { "name": "id_to_token_dict_old", "string": "- id_to_token_dict_old (dict): A dictionary mapping original indices to their respective tokens. Reverse of token_to_id_dict_old.", "dependency": null }, { "name": "token_to_id_dict_new", "string": "- token_to_id_dict_new (dict): A dictionary mapping new vocabulary tokens to their respective indices.", "dependency": null }, { "name": "trans_to_origin", "string": "- trans_to_origin (dict): A mapping from new subwords to their corresponding original subwords (one-to-one or one-to-many relations).", "dependency": null }, { "name": "new_vocab_score_list", "string": "- new_vocab_score_list (List[List]): A list of [token, score] pairs for the new vocabulary, where:\n - `token` is the new subword.\n - `score` indicates its importance or relevance (used for monitoring progress during initialization).", "dependency": null }, { "name": "merge_mode", "string": "- merge_mode (str): Specifies how to handle new subwords with multiple original correspondences. Options are:\n - 'max': Use the embedding of the most probable original subword.\n - 'min': Use the embedding of the least probable original subword.\n - 'average': Average the embeddings of all mapped original subwords.", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File Dependency: \n - None\n\n Cross-File Dependency: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - numpy.zeros\n", "list": [ "numpy.zeros" ] }, "Return": { "Return_String": "\nOutput Variables:\n - new_embeddings (numpy.ndarray, shape: [num of words, dimension]): A 2D array where each row corresponds to the embedding of a subword in the new vocabulary.\n", "Return_list": [ { "name": "new_embeddings", "string": "\n- new_embeddings (numpy.ndarray, shape: [num of words, dimension]): A 2D array where each row corresponds to the embedding of a subword in the new vocabulary.\n" } ] }, "ori_python_file": "import argparse\nimport os\nfrom uroman1 import UromanWrapper\nfrom transformers import AutoModelForMaskedLM, AutoTokenizer\nfrom transformers import XLMRobertaTokenizer, AutoModelForMaskedLM\nimport sentencepiece_model_pb2 as sp_model\nimport glob\nimport numpy as np\nimport json\nimport torch\ndef initialize_subword_embeddings(\n model,\n token_to_id_dict_old,\n id_to_token_dict_old,\n token_to_id_dict_new,\n trans_to_origin,\n new_vocab_score_list,\n merge_mode\n):\n embeddings = model.get_input_embeddings().weight.detach().numpy()\n new_embeddings = np.zeros((len(token_to_id_dict_new), embeddings.shape[1]), dtype=embeddings.dtype)\n for i in range(len(token_to_id_dict_old)):\n idx = token_to_id_dict_new[id_to_token_dict_old[i]]\n new_embeddings[idx] = embeddings[i]\n for i, (token, score) in enumerate(new_vocab_score_list):\n if i % 1000 == 0:\n print(f\"{i}, {token}...\")\n idx = token_to_id_dict_new[token]\n source_tokens = trans_to_origin[token]\n if len(source_tokens) == 1:\n new_embeddings[idx] = embeddings[token_to_id_dict_old[source_tokens[0]]]\n else:\n if merge_mode == 'max':\n new_embeddings[idx] = embeddings[token_to_id_dict_old[source_tokens[0]]]\n elif merge_mode == 'min':\n new_embeddings[idx] = embeddings[token_to_id_dict_old[source_tokens[-1]]]\n elif merge_mode == 'average':\n emb = np.zeros(embeddings.shape[1])\n for old_index in [token_to_id_dict_old[source] for source in source_tokens]:\n emb += embeddings[old_index]\n new_embeddings[idx] = emb / len(source_tokens)\n return new_embeddings\n\ndef get_new_vocab_score(vocab_score_list, origin_to_trans, trans_to_origin, merge_mode):\n new_vocab_score_dict = {}\n vocab_score_dict = dict(vocab_score_list)\n for i in range(len(vocab_score_list)):\n transli = origin_to_trans[vocab_score_list[i][0]]\n if transli in trans_to_origin:\n if len(trans_to_origin[transli]) == 1:\n score = vocab_score_list[i][1]\n else:\n score_list = []\n for source in trans_to_origin[transli]:\n score_list.append(vocab_score_dict[source])\n if merge_mode == 'max':\n score = max(score_list)\n elif merge_mode == 'min':\n score = min(score_list)\n elif merge_mode == \"average\":\n score = sum(score_list) / len(score_list)\n else:\n raise NotImplementedError\n else:\n continue\n new_vocab_score_dict[transli] = score\n new_vocab_score_list = [[x1, x2] for x1, x2 in new_vocab_score_dict.items()]\n new_vocab_score_list = sorted(new_vocab_score_list, key=lambda item: item[1], reverse=True)\n return new_vocab_score_list\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--model_name', default='xlm-roberta-base')\n parser.add_argument('--merge_mode', default='max')\n parser.add_argument('--save_path', default='./models')\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n target_path = args.save_path + f\"/{args.model_name.split('/')[-1]}-with-transliteration-{args.merge_mode}\"\n if os.path.exists(target_path):\n pass\n else:\n os.makedirs(target_path)\n tokenizer = AutoTokenizer.from_pretrained(args.model_name)\n model = AutoModelForMaskedLM.from_pretrained(args.model_name)\n tokenizer.save_pretrained(target_path)\n model.save_pretrained(target_path)\n original_m = sp_model.ModelProto()\n original_m.ParseFromString(open(f\"{target_path}/sentencepiece.bpe.model\", 'rb').read())\n vocab = sorted(tokenizer.get_vocab().items(), key=lambda x: x[1], reverse=False)\n vocab_list = [x[0] for x in vocab]\n if args.TestCode:\n vocab_list = vocab_list[:1000]\n roman = UromanWrapper()\n transliterated_vocab = roman.romanize(vocab_list)\n origin_to_trans = dict(zip(vocab_list, transliterated_vocab))\n new_tokens = set(transliterated_vocab).difference(set(vocab_list))\n new_tokens = new_tokens - set([''])\n print(\"Number of newly added tokens: \", len(new_tokens))\n new_tokens = list(new_tokens)\n print(\"Building transliteration dictionary ...\")\n trans_to_origin = {}\n for index, token in enumerate(new_tokens):\n source = []\n for i in range(len(transliterated_vocab)):\n if token == transliterated_vocab[i]:\n source.append(vocab_list[i])\n trans_to_origin[token] = source\n with open(f\"{target_path}/tokenizer.json\", 'r') as file:\n tokenizer_data = json.load(file)\n if args.TestCode:\n vocab_tokenizer_data = tokenizer_data['model']['vocab']\n vocab_tokenizer_data_new = list()\n for i in range(len(vocab_tokenizer_data)):\n if vocab_tokenizer_data[i][0] in vocab_list:\n vocab_tokenizer_data_new.append(vocab_tokenizer_data[i])\n tokenizer_data['model']['vocab'] = vocab_tokenizer_data_new\n vocab_score_dict = tokenizer_data['model']['vocab']\n new_vocab_score_list = get_new_vocab_score(vocab_score_dict, origin_to_trans, trans_to_origin, args.merge_mode)\n add_cnt = 0\n piece_d = {piece.piece: 0 for piece in original_m.pieces}\n for (piece, score) in new_vocab_score_list:\n if piece not in piece_d:\n piece_to_add = sp_model.ModelProto().SentencePiece()\n piece_to_add.piece = piece\n piece_to_add.score = score\n original_m.pieces.append(piece_to_add)\n add_cnt += 1\n if not args.TestCode:\n file_paths = glob.glob(os.path.join(target_path, '*'))\n for file_path in file_paths:\n if os.path.isfile(file_path):\n os.remove(file_path)\n new_spm_save_dir = f\"{target_path}/sentencepiece.bpe.model\"\n with open(new_spm_save_dir, 'wb') as f:\n f.write(original_m.SerializeToString())\n tokenizer = XLMRobertaTokenizer.from_pretrained(args.model_name)\n tokenizer.vocab_file = new_spm_save_dir\n tokenizer.sp_model.load(tokenizer.vocab_file)\n if not args.TestCode:\n tokenizer.save_pretrained(target_path)\n tokenizer_old = XLMRobertaTokenizer.from_pretrained(args.model_name)\n tokenizer_new = XLMRobertaTokenizer.from_pretrained(target_path)\n token_to_id_dict_old = dict(sorted(tokenizer_old.get_vocab().items(), key=lambda item: item[1]))\n id_to_token_dict_old = {idx: token for token, idx in token_to_id_dict_old.items()}\n token_to_id_dict_new = dict(sorted(tokenizer_new.get_vocab().items(), key=lambda item: item[1]))\n id_to_token_dict_new = {idx: token for token, idx in token_to_id_dict_new.items()}\n new_vocab_score_list_1 = list()\n for i in range(len(new_vocab_score_list)):\n if new_vocab_score_list[i][0] in token_to_id_dict_new:\n new_vocab_score_list_1.append(new_vocab_score_list[i])\n new_vocab_score_list = new_vocab_score_list_1\n new_embeddings = initialize_subword_embeddings(\n model,\n token_to_id_dict_old,\n id_to_token_dict_old,\n token_to_id_dict_new,\n trans_to_origin,\n new_vocab_score_list,\n args.merge_mode\n )" } ] }, { "paper_id": 10, "paper_details": { "title": "Enhancing Knowledge Distillation of Large Language Models through Efficient Multi-Modal Distribution Alignment", "url": "https://arxiv.org/abs/2409.12545" }, "enviorment_name": "rlkd", "repo_original_url": "https://github.com/pty72/rlkd", "project_path": "Benchmark/10-RLKD-main/RLKD-main", "file_organization": "\nRLKD-main/\n env.sh\n LICENSE\n pretrain/\n data/\n demo.jsonl\n kd_pretrain.py\n README.md\n requirements.txt\n run_pretrain.sh\n run_sft.sh\n sft/\n data/\n dolly/\n dolly_test.jsonl\n dolly_train.jsonl\n gsm8k/\n test_use.jsonl\n train_use.jsonl\n kd_sft.py\n sft_dataset.py\n", "latex_code_path": "Benchmark/10-RLKD-main/arXiv-2409.12545v2", "task_details": [ { "task_id": 0, "indent": 1, "script": "\npython ./sft/kd_sft.py\n", "latex_code": "\n\\section{Method}\n\\label{sec4}\n\nExisting distillation objectives bring the two distributions closer by minimizing the distance between the teacher's and the student's predicted distributions. Although these distillation objectives can align the student's predicted distribution with the teacher's after a sufficient number of steps in theory, their efficiency in learning multi-modal distributions in practical scenarios still needs further improvement. Consequently, we aim to introduce additional optimization objectives to enhance the learning of peak predictions.\n\nThe direct optimization objective of the existing distillation objectives is the distance between two distributions. The methods for calculating the distance of these distillation objectives differ, but they compute the same objects, as $\\mathcal{L}_{\\text{logits}}=\\sum_i distance(P(i),Q(i))$. Therefore, existing distillation objectives only calculate the distance between each individual category, without utilizing the relationship among categories, as the black lines shown in Figure \\hyperref[Fig4]{4}.\n\n\\begin{figure}[h] \n\\centering \n\n\n\\includegraphics[width=0.45\\textwidth]{4.pdf} \n\\vspace{-0.1cm}\n\\caption{Comparison of computational objects on peak predictions. The black lines represent existing distillation objectives and the red lines represent our method.} \n\\label{Fig4}\n\\vspace{-0.2cm}\n\\end{figure}\n\nIn this work, we enhance the learning of peak predictions in KD of LLMs by introducing a new optimization objective of \\textit{word-level ranking loss}. The new optimization objective focuses on the prediction order of high probabilities between student and teacher models, enabling the student model to match the teacher model on critical predicted categories.\n\nOur specific approach focuses on the top-$k$ predicted tokens from both the teacher and student models. We calculate the consistency by comparing the probability order of these tokens in the teacher model with the probability order in the student model. This method straightforwardly enhances the consistency of top-$k$ predictions between two multi-modal distributions, thereby strengthening the alignment of peak predictions between the student and teacher models. Importantly, the computational objects of our ranking loss are the probability values in the prediction sequences of the union of the teacher's and student's top-k predictions, not just the teacher's top-k predictions. This ensures that the excessively high predictive probability in the student model are also reasonably optimized.\n\nOur approach allows that during the optimization process, the calculation of peak predictions is not limited to comparisons within a single category. As the red lines shown in Figure \\hyperref[Fig4]{4}, $Q(i)$ needs to be compared with $Q(j)$ and $Q(k)$ based on the ranking position of $P(i)$ in the teacher's predictions to minimize the ranking loss.\n\nWe consider Spearman's rank correlation coefficient (SRCC) as the target for the measurement of ranking consistency. Compared to the Pearson coefficient, which also measures order consistency, SRCC only considers the consistency in the order of two sets of arrangements, without taking into account the correlation of the actual element values. We prefer that the ranking loss focuses more on the consistency of the predicted categories and probability values are non-linear relationships, therefore we select SRCC as the optimization objective for ranking loss, as\n\\begin{equation}\n\\mathcal{L}_{\\text{Ranking}} = 1 - \\rho_{\\text{srcc}}(p, q) = 1 - \\frac{\\text{Cov}(R_p, R_q)}{\\sigma_{R_p} \\cdot \\sigma_{R_q}}\n\\end{equation}\nwhere $p$ and $q$ are subsets of distributions $P$ and $Q$, respectively, and each subset represents the probability values on the respective distributions for the union of top-$k$ predictions. $R_p$ denotes the rank index of $p$, $\\sigma_{R_p}$ is the standard deviation of $R_p$, and $\\text{Cov}(R_p, R_q)$ is the covariance of $R_p$ and $R_q$. \n\nAlthough sorting operations are theoretically non-differentiable, existing work \\cite{blondel2020fast, ramzi2023optimization} has implemented differentiable ranking operator suitable for stochastic gradient descent. Several studies \\cite{huang2022relational, rudd2022efficient, wang2023monoskd} have used SRCC as an optimization objective in other research areas based on such operators.\n\nOverall, our method fully utilizes the peak predictions information from both the teacher and student models. Compared to previous methods that calculate loss within a single category, our approach further optimizes using probability values between categories. As shown in Figure \\hyperref[Fig4]{4}, when combined with existing objectives, the fused objective allows the student model to more comprehensively learn the peak predictions of the teacher model from two different perspectives, showing excellent compatibility.\n", "completion_path": "./sft/kd_sft.py", "namespace": "sft.kd_sft.topk_spearman_loss", "type": "function", "signature_position": [ 97, 97 ], "body_position": [ 98, 113 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Select the top-k tokens from both teacher and student, aligning\n# with the LaTeX emphasis on focusing on \"peak predictions\" for the ranking\n# consistency measurement.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\n_, tea_topk_indices = torch.topk(teacher_logits, k, dim=-1)\n_, stu_topk_indices = torch.topk(student_logits, k, dim=-1)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Form the union of top-k indices from both distributions, ensuring\n# that all significant tokens from both models are considered, reflecting the\n# union operation mentioned in the LaTeX for comprehensive peak comparison.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nunion_indices = torch.unique(torch.cat((tea_topk_indices, stu_topk_indices), dim=-1), dim=-1)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Sort the unioned indices to establish a consistent order, then\n# record the count of these merged top tokens (the \"peak predictions\").\n# This aligns with the idea that each distribution\u2019s top predictions must be\n# compared in a shared index space.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\ntea_topk_indices, _ = torch.sort(union_indices, dim=-1)\nlength = tea_topk_indices.size()[-1]\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Gather the teacher and student logits at these unioned indices\n# and apply a differentiable ranking operation (soft_rank) to facilitate\n# gradient-based optimization, corresponding to the differentiable approach\n# used for Spearman\u2019s rank correlation coefficient in the LaTeX.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\ntea_topk_values = torch.gather(teacher_logits, -1, tea_topk_indices)\nstu_topk_values = torch.gather(student_logits, -1, tea_topk_indices)\n\nstu_topk_values = torchsort.soft_rank(stu_topk_values.view(-1, length))\ntea_topk_values = torchsort.soft_rank(tea_topk_values.view(-1, length))\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Normalize the ranked values by subtracting their mean and dividing\n# by their norm, focusing only on the directional consistency of the ranks\n# rather than the absolute magnitude. This aligns with the SRCC approach\n# mentioned in the LaTeX, which cares about order consistency.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nstu_topk_values = stu_topk_values - stu_topk_values.mean(dim=1, keepdim=True)\nstu_topk_values = stu_topk_values / stu_topk_values.norm(dim=1, keepdim=True)\ntea_topk_values = tea_topk_values - tea_topk_values.mean(dim=1, keepdim=True)\ntea_topk_values = tea_topk_values / tea_topk_values.norm(dim=1, keepdim=True)\n# [End Snippet 5]\n\n# ---------------------------------------------------------------------------\n# Snippet 6: Compute the dot product of the normalized rank vectors, then take\n# its mean to approximate the correlation between student and teacher \"peak\"\n# distributions. Then, return the positive correlation term.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 6]\ndot_product = (stu_topk_values * tea_topk_values).sum(dim=1)\noutput = torch.mean(dot_product)\nreturn output\n# [End Snippet 6]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX consistently refers to probabilities, but the code directly processes logits. This is acceptable in practice given that ranking operations on logits often mirror those on probabilities.\n - The LaTeX description does not specify sorting the union of top-k indices obtained from the teacher and student logits. However, the reference Python code explicitly sorts these indices after performing the union. The sorted indices ensure consistent ordering of logits.\n - The LaTeX description does not detail the normalization step clearly. In the reference Python code, normalization explicitly involves subtracting the mean and dividing by the L2 norm of the ranked vectors. \n - Differentiable ranking operator specification: While the LaTeX cites prior work for differentiable ranking, it does not describe the specific operator (e.g., `torchsort.soft_rank`). The reference code uses this operator to compute ranks over the full sequence length.\n \n Mismatched Details:\n - The LaTeX states that the ranking loss should be \"1 - SRCC\". The reference code, however, returns the mean dot product of normalized rank vectors directly.\n", "Missing_details": [ "\n- The LaTeX consistently refers to probabilities, but the code directly processes logits. This is acceptable in practice given that ranking operations on logits often mirror those on probabilities.\n", "\n- The LaTeX description does not specify sorting the union of top-k indices obtained from the teacher and student logits. However, the reference Python code explicitly sorts these indices after performing the union. The sorted indices ensure consistent ordering of logits.\n", "\n- The LaTeX description does not detail the normalization step clearly. In the reference Python code, normalization explicitly involves subtracting the mean and dividing by the L2 norm of the ranked vectors.\n", "\n- Differentiable ranking operator specification: While the LaTeX cites prior work for differentiable ranking, it does not describe the specific operator (e.g., `torchsort.soft_rank`). The reference code uses this operator to compute ranks over the full sequence length.\n" ], "Mismatched_details": [ "\n- The LaTeX states that the ranking loss should be \"1 - SRCC\". The reference code, however, returns the mean dot product of normalized rank vectors directly.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - student_logits (torch.Tensor, shape=[batch_size, vocab_size]): The raw output logits from the student model.\n - teacher_logits (torch.Tensor, shape=[batch_size, vocab_size]): The raw output logits from the teacher model.\n - k (int, default is 15.): The number of top tokens to be considered for ranking.\n", "Arguments_list": [ { "name": "student_logits", "string": "- student_logits (torch.Tensor, shape=[batch_size, vocab_size]): The raw output logits from the student model.", "dependency": null }, { "name": "teacher_logits", "string": "- teacher_logits (torch.Tensor, shape=[batch_size, vocab_size]): The raw output logits from the teacher model.", "dependency": null }, { "name": "k", "string": "- k (int, default is 15.): The number of top tokens to be considered for ranking.", "dependency": null } ] }, "dependency": { "string": "\nRepository Dependencies:\n Intra-File Dependencies: \n - None\n \n Cross-File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torchsort.soft_rank\n - torch.mean\n - torch.sort\n - torch.unique\n - torch.topk\n - torch.gather\n - torch.cat\n", "list": [ "torchsort.soft_rank", "torch.mean", "torch.sort", "torch.unique", "torch.topk", "torch.gather", "torch.cat" ] }, "Return": { "Return_String": "\nOutput Variable:\n - output (torch.Tensor): \n Returns a scalar tensor (torch.Tensor) representing the mean of the dot products between normalized rank vectors of student and teacher for each element in the batch. Higher values indicate stronger alignment.\n", "Return_list": [ { "name": "output", "string": "\n- output (torch.Tensor): \n Returns a scalar tensor (torch.Tensor) representing the mean of the dot products between normalized rank vectors of student and teacher for each element in the batch. Higher values indicate stronger alignment.\n" } ] }, "ori_python_file": "import torch\nfrom transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, get_scheduler\nimport random\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport sentencepiece as spm\nimport torchsort\nfrom tqdm import tqdm\nimport os\nimport numpy as np\nfrom datasets import load_dataset\nfrom torch.nn import CrossEntropyLoss\nimport transformers\nfrom typing import Optional, Dict, Sequence\nfrom sft_dataset import DataCollatorForSupervisedDataset, SupervisedDataset, DollyDataset\nimport argparse\nIGNORE_INDEX = -100\nDEFAULT_PAD_TOKEN = \"[PAD]\"\nDEFAULT_EOS_TOKEN = \"\"\nDEFAULT_BOS_TOKEN = \"\"\nDEFAULT_UNK_TOKEN = \"\"\n\ndef seed_it(seed):\n random.seed(seed)\n os.environ[\"PYTHONSEED\"] = str(seed)\n np.random.seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = True\n torch.backends.cudnn.enabled = True\n torch.manual_seed(seed)\n os.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\n torch.cuda.synchronize()\n\ndef smart_tokenizer_and_embedding_resize(\n special_tokens_dict: Dict,\n tokenizer: transformers.PreTrainedTokenizer,\n model: transformers.PreTrainedModel,\n):\n num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)\n model.resize_token_embeddings(len(tokenizer))\n if num_new_tokens > 0:\n input_embeddings = model.get_input_embeddings().weight.data\n output_embeddings = model.get_output_embeddings().weight.data\n input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)\n output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)\n input_embeddings[-num_new_tokens:] = input_embeddings_avg\n output_embeddings[-num_new_tokens:] = output_embeddings_avg\n\ndef calculate_perplexity(logits, labels):\n ce_loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.view(-1), reduction='none')\n perplexity = torch.exp(torch.mean(ce_loss)).item()\n return perplexity\n\ndata_id = 0\n\ndef init_netinput(batch_size, dataset, tokenizer, max_length):\n global data_id\n batch = []\n for i in range(batch_size):\n input_ids = tokenizer.encode(dataset[data_id]['text'], truncation=True, max_length=max_length, add_special_tokens=True)\n data_id += 1\n input_ids.append(2)\n while len(input_ids) < max_length:\n input_ids.extend(tokenizer.encode(dataset[data_id]['text'], truncation=True, max_length=max_length, add_special_tokens=True))\n data_id += 1\n input_ids.append(2)\n input_ids = input_ids[:max_length]\n batch.append(input_ids)\n return torch.tensor(batch)\n\ndef kl_divergence(p, q):\n return torch.sum(p * (torch.log(p + 1e-10) - torch.log(q + 1e-10)), dim=-1)\n\ndef kl_loss(teacher_distribution, student_distribution):\n kd_loss = kl_divergence(teacher_distribution, student_distribution)\n kd_loss = torch.mean(kd_loss, dim=-1)\n kd_loss = torch.mean(kd_loss, dim=-1)\n return kd_loss\n\ndef rkl_loss(teacher_distribution, student_distribution):\n return kl_loss(student_distribution, teacher_distribution)\n\ndef spearman_loss(pred, target, **kw):\n pred = torchsort.soft_rank(pred, **kw)\n target = torchsort.soft_rank(target, **kw)\n pred = pred - pred.mean()\n pred = pred / pred.norm()\n target = target - target.mean()\n target = target / target.norm()\n return (pred * target).sum()\n\nimport torch\nimport torchsort\n\ndef topk_spearman_loss(student_logits, teacher_logits, k=15):\n _, tea_topk_indices = torch.topk(teacher_logits, k, dim=-1)\n _, stu_topk_indices = torch.topk(student_logits, k, dim=-1)\n union_indices = torch.unique(torch.cat((tea_topk_indices, stu_topk_indices), dim=-1), dim=-1)\n tea_topk_indices, _ = torch.sort(union_indices, dim=-1)\n length = tea_topk_indices.size()[-1]\n tea_topk_values = torch.gather(teacher_logits, -1, tea_topk_indices)\n stu_topk_values = torch.gather(student_logits, -1, tea_topk_indices)\n stu_topk_values = torchsort.soft_rank(stu_topk_values.view(-1, length))\n tea_topk_values = torchsort.soft_rank(tea_topk_values.view(-1, length))\n stu_topk_values = stu_topk_values - stu_topk_values.mean(dim=1, keepdim=True)\n stu_topk_values = stu_topk_values / stu_topk_values.norm(dim=1, keepdim=True)\n tea_topk_values = tea_topk_values - tea_topk_values.mean(dim=1, keepdim=True)\n tea_topk_values = tea_topk_values / tea_topk_values.norm(dim=1, keepdim=True)\n dot_product = (stu_topk_values * tea_topk_values).sum(dim=1)\n output = torch.mean(dot_product)\n return output\n\ndef tvd_loss(teacher_logits, student_logits):\n absolute_differences = torch.sum(torch.abs(teacher_logits - student_logits), dim=-1)\n return 0.5 * absolute_differences\n\ndef CEloss(net_output, target):\n loss_fct = CrossEntropyLoss()\n a, b, vocab_size = net_output.size()\n loss = loss_fct(net_output.contiguous().view(-1, vocab_size), target.contiguous().view(-1))\n return loss\n\ndef topk_consistency(teacher_logits, student_logits, k):\n _, teacher_topk_idx = torch.topk(teacher_logits, k, dim=-1)\n _, student_topk_idx = torch.topk(student_logits, k, dim=-1)\n consistency = torch.zeros_like(teacher_topk_idx, dtype=torch.float)\n for i in range(k):\n consistency += (teacher_topk_idx == student_topk_idx[:, i].view(-1, 1)).float()\n accuracy = consistency.sum(dim=1) / k\n return accuracy\n\ndef js_divergence(p, q):\n m = 0.5 * (p + q)\n kl_p_m = kl_divergence(p, m)\n kl_q_m = kl_divergence(q, m)\n js_div = 0.5 * kl_p_m + 0.5 * kl_q_m\n return js_div\n\ndef js_loss(teacher_distribution, student_distribution):\n js = js_divergence(teacher_distribution, student_distribution)\n js = torch.mean(js, dim=-1)\n js = torch.mean(js, dim=-1)\n return js\n\ndef only_rank_loss(teacher_logits, student_logits, k=10):\n rank_loss_value = 1 - topk_spearman_loss(student_logits, teacher_logits, k)\n if torch.isnan(rank_loss_value):\n teacher_probs = F.softmax(teacher_logits, dim=-1)\n student_probs = F.softmax(student_logits, dim=-1)\n fallback_loss = kl_loss(teacher_probs, student_probs)\n return fallback_loss\n else:\n return rank_loss_value\n\ndef distill_loss(teacher_logits, student_logits, distill_obj, use_ranking_loss, ranking_range, ranking_loss_magnification):\n k = ranking_range\n if use_ranking_loss:\n rank_loss_value = 1 - topk_spearman_loss(student_logits, teacher_logits, k)\n teacher_probs = F.softmax(teacher_logits, dim=-1)\n student_probs = F.softmax(student_logits, dim=-1)\n if distill_obj == 'kl':\n v_loss = kl_loss(teacher_probs, student_probs)\n elif distill_obj == 'rkl':\n v_loss = rkl_loss(teacher_probs, student_probs)\n elif distill_obj == 'js':\n v_loss = js_loss(teacher_probs, student_probs)\n elif distill_obj == 'tvd':\n v_loss = tvd_loss(teacher_probs, student_probs)\n if use_ranking_loss:\n if torch.isnan(rank_loss_value):\n print('Error with ranking loss; fallback to distribution loss only.')\n final_loss = v_loss\n else:\n final_loss = rank_loss_value + v_loss / ranking_loss_magnification\n return final_loss\n else:\n return v_loss\n\ndef distill():\n parser = argparse.ArgumentParser(description=\"RLKD Demo\")\n parser.add_argument('--task', type=str, default='gsm8k', choices=['gsm8k', 'xsum', 'dolly'])\n parser.add_argument('--epoch', type=int, default=2)\n parser.add_argument('--gradient_acc', type=int, default=32)\n parser.add_argument('--seed', type=int, default=72)\n parser.add_argument('--batch_size', type=int, default=1)\n parser.add_argument('--seq_len', type=int, default=2048)\n parser.add_argument('--teacher_path', type=str, default=\"OFA-Sys/gsm8k-rft-llama7b2-u13b\")\n parser.add_argument('--student_path', type=str, default=\"TinyLlama/TinyLlama-1.1B-Chat-v1.0\")\n parser.add_argument('--tokenizer_path', type=str, default=\"OFA-Sys/gsm8k-rft-llama7b2-u13b\")\n parser.add_argument('--learning_rate', type=float, default=2e-5)\n parser.add_argument('--data_path', type=str, default='sft/data/gsm8k/train_use.jsonl')\n parser.add_argument('--distill_obj', type=str, default='kl', choices=['kl', 'rkl', 'js', 'tvd'])\n parser.add_argument('--use_ranking_loss', type=bool, default=True)\n parser.add_argument('--ranking_range', type=int, default=5)\n parser.add_argument('--ranking_loss_magnification', type=float, default=2.0)\n parser.add_argument('--save_path', type=str, default='checkpoints/rlkd/sft/test')\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n seed_it(args.seed)\n print('Seed:', args.seed)\n batch_size = args.batch_size\n max_length = args.seq_len\n num_epochs = args.epoch\n teacher_config = AutoConfig.from_pretrained(args.teacher_path)\n teacher_model = AutoModelForCausalLM.from_pretrained(\n args.teacher_path, config=teacher_config\n )\n teacher_model.to(device)\n teacher_model.eval()\n student_config = AutoConfig.from_pretrained(args.student_path)\n student_model = AutoModelForCausalLM.from_pretrained(\n args.student_path, config=student_config\n )\n student_model.to(device)\n student_model.train()\n tokenizer = AutoTokenizer.from_pretrained(\n args.tokenizer_path, padding_side=\"right\", use_fast=False, model_max_length=max_length\n )\n smart_tokenizer_and_embedding_resize(\n special_tokens_dict=dict(pad_token=DEFAULT_PAD_TOKEN),\n tokenizer=tokenizer,\n model=student_model,\n )\n tokenizer.add_special_tokens(\n {\n \"eos_token\": DEFAULT_EOS_TOKEN,\n \"bos_token\": DEFAULT_BOS_TOKEN,\n \"unk_token\": DEFAULT_UNK_TOKEN,\n }\n )\n optimizer = optim.AdamW(student_model.parameters(), lr=args.learning_rate)\n lr_scheduler = get_scheduler(\n name='cosine',\n optimizer=optimizer,\n num_warmup_steps=0,\n num_training_steps=100000,\n )\n if args.task == 'gsm8k':\n dataset = SupervisedDataset(args.data_path, tokenizer)\n else:\n dataset = DollyDataset(args.data_path, tokenizer)\n if args.TestCode:\n dataset.sources = dataset.sources[:20]\n dataset.targets = dataset.targets[:20]\n total_samples = len(dataset)\n num_step = total_samples // batch_size\n grad_accum_steps = args.gradient_acc\n global data_id\n data_id = 0\n total_step = 0\n for epoch in range(num_epochs):\n print(f\"Epoch {epoch+1}/{num_epochs}\")\n pbar = tqdm(range(num_step), desc=\"Training\", ncols=120)\n for step in pbar:\n len_querys = []\n len_inputs = []\n batch_inputs = []\n for i in range(batch_size):\n if data_id >= total_samples:\n data_id = 0\n data = dataset[data_id]\n data_id += 1\n query_ids = tokenizer(\n data[\"input_ids\"], return_tensors='pt', max_length=max_length, truncation=True\n )[\"input_ids\"]\n full_ids = tokenizer(\n data[\"input_ids\"] + data[\"labels\"], return_tensors='pt',\n max_length=max_length, truncation=True\n )[\"input_ids\"]\n batch_inputs.append(full_ids.squeeze())\n len_inputs.append(full_ids.size(-1))\n len_querys.append(query_ids.size(-1))\n input_ids = torch.nn.utils.rnn.pad_sequence(\n batch_inputs, batch_first=True, padding_value=tokenizer.pad_token_id\n ).to(device)\n attention_mask = input_ids.ne(tokenizer.pad_token_id).to(device)\n student_logits = student_model(input_ids, attention_mask=attention_mask).logits\n with torch.no_grad():\n teacher_logits = teacher_model(input_ids, attention_mask=attention_mask).logits\n batch_size_eff, seq_len, vocab_size = teacher_logits.size()\n mask = torch.zeros((batch_size_eff, seq_len), dtype=torch.bool, device=device)\n for bi in range(batch_size_eff):\n mask[bi, len_querys[bi] : len_inputs[bi]] = True\n teacher_logits_batch = teacher_logits[mask].view(-1, vocab_size)\n student_logits_batch = student_logits[mask].view(-1, vocab_size)\n loss = distill_loss(\n teacher_logits_batch,\n student_logits_batch,\n args.distill_obj,\n args.use_ranking_loss,\n args.ranking_range,\n args.ranking_loss_magnification,\n )\n loss = loss / grad_accum_steps\n loss.backward()\n if (step + 1) % grad_accum_steps == 0:\n torch.nn.utils.clip_grad_norm_(student_model.parameters(), 1.0)\n optimizer.step()\n lr_scheduler.step()\n optimizer.zero_grad()\n pbar.set_postfix({\"loss\": f\"{loss.item():.4f}\"})\n total_step += 1\nif __name__ == \"__main__\":\n distill()" } ] }, { "paper_id": 11, "paper_details": { "title": "Document-level Claim Extraction and Decontextualisation for Fact-Checking", "url": "https://arxiv.org/abs/2406.03239" }, "enviorment_name": "Averitec", "repo_original_url": "https://github.com/Tswings/AVeriTeC-DCE", "project_path": "Benchmark/11-AVeriTeC-DCE-main/AVeriTeC-DCE-main", "file_organization": "\nAVeriTeC-DCE-main/\n 1_data_extraction.py\n 2_context_generation.py\n 3_decontextualisation.py\n all_data/\n 1_all_available_url_fulltext.json\n 2_sent_ranked_by_bertsum.json\n 3_generated_candidates.jsonl\n 4_generated_questions.jsonl\n 5_generated_answers.jsonl\n 6_generated_context.jsonl\n 7_highquality_context.jsonl\n averitec_data/\n 1_avail_url_in_dev_with_fulltext.json\n 1_avail_url_in_test_with_fulltext.json\n 1_avail_url_in_train_with_fulltext.json\n dev.json\n test.json\n train.json\n AVeriTeC-main/\n data/\n dev.json\n filtered_parallel_src.json\n filtered_parallel_tgt.json\n misinfo_list.txt\n data_loaders/\n DualEncoderDataLoader.py\n JustificationProductionDataLoader.py\n NoEvidenceDataLoader.py\n SequenceClassificationDataLoader.py\n eval.py\n justification_production/\n trained_model_justification_generation.py\n models/\n DualEncoderModule.py\n JustificationGenerationModule.py\n NaiveSeqClassModule.py\n SequenceClassificationModule.py\n README.md\n requirements.txt\n retrieval_coarse/\n averitec_search.py\n combine_search_results.py\n html2lines.py\n prompt_question_generation.py\n prompt_question_generation_vicuna.py\n split_sentences_for_downloaded_pages.py\n retrieval_reranking/\n combine_decorated_files.py\n decorate_with_questions.py\n decorate_with_questions_vicuna.py\n no_reranker.py\n trained_model_reranker.py\n utils.py\n veracity_prediction/\n no_evidence.py\n veracity_prediction.py\n decontext/\n decontext_dataset/\n decontext_dev.jsonl\n t5_base/\n pretrained_models_base_checkpoint\n pretrained_models_base_model.ckpt-999900.data-00000-of-00016\n pretrained_models_base_model.ckpt-999900.data-00001-of-00016\n pretrained_models_base_model.ckpt-999900.data-00002-of-00016\n pretrained_models_base_model.ckpt-999900.data-00003-of-00016\n pretrained_models_base_model.ckpt-999900.data-00004-of-00016\n pretrained_models_base_model.ckpt-999900.data-00005-of-00016\n pretrained_models_base_model.ckpt-999900.data-00006-of-00016\n pretrained_models_base_model.ckpt-999900.data-00007-of-00016\n pretrained_models_base_model.ckpt-999900.data-00008-of-00016\n pretrained_models_base_model.ckpt-999900.data-00009-of-00016\n pretrained_models_base_model.ckpt-999900.data-00010-of-00016\n pretrained_models_base_model.ckpt-999900.data-00011-of-00016\n pretrained_models_base_model.ckpt-999900.data-00012-of-00016\n pretrained_models_base_model.ckpt-999900.data-00013-of-00016\n pretrained_models_base_model.ckpt-999900.data-00014-of-00016\n pretrained_models_base_model.ckpt-999900.data-00015-of-00016\n pretrained_models_base_model.ckpt-999900.index\n pretrained_models_base_model.ckpt-999900.meta\n pretrained_models_base_operative_config.gin\n docnli_model/\n DocNLI.pretrained.RoBERTA.model.pt\n en_core_web_lg-3.8.0-py3-none-any.whl\n env.sh\n presumm/\n cal_rouge.py\n distributed.py\n logs/\n test.log\n models/\n adam.py\n data_loader.py\n decoder.py\n encoder.py\n __init__.py\n loss.py\n model_builder.py\n neural.py\n optimizers.py\n predictor.py\n reporter_ext.py\n reporter.py\n trainer_ext.py\n trainer.py\n others/\n __init__.py\n logging.py\n pyrouge.py\n tokenization.py\n utils.py\n post_stats.py\n prepro/\n data_builder.py\n __init__.py\n smart_common_words.txt\n utils.py\n preprocess.py\n raw_data/\n temp_ext.raw_src\n train_abstractive.py\n train_extractive.py\n train_ori.py\n train.py\n translate/\n beam.py\n __init__.py\n penalties.py\n README.md\n requirements.txt\n", "latex_code_path": "Benchmark/11-AVeriTeC-DCE-main/arXiv-2406.03239v2", "task_details": [ { "task_id": 0, "indent": 1, "script": "\npython 2_context_generation.py\n", "latex_code": "\n\\subsection{Sentence Extraction} \\label{section_3_1}\nThe claims selected by human fact-checkers are typically related to the central idea of the document considered. Thus we propose to model sentence extraction as extractive summarization. For this purpose, we concatenate all the sentences in the document into an input sequence, \nwhich is then fed to BertSum~\\cite{liu2019text}, a document-level extractive summarization method trained on the CNN/DailyMail dataset. \nSpecifically, given a document consisting of $n$ sentences $\\mathcal{D}=\\{{s}_1, {s}_2, ..., {s}_n\\}$, we first formulate the input sequence $C$ as ``${\\rm [CLS]}\\ {s}_1\\ {\\rm [SEP]} \\ {\\rm [CLS]}\\ {s}_2$ ${\\rm [SEP]}\\ ...\\ {\\rm [CLS]} \\ {s}_n {\\rm [SEP]}$'', where $\\rm [CLS]$ and $\\rm [SEP]$ denote the start and end token for each sentence, respectively, and then feed them into a pre-trained encoder BERT to obtain the sentence representation $\\mathbf s$. Finally, a linear layer on sentence representations $\\mathbf{S} = \\{\\mathbf{s}_1, ..., \\mathbf{s}_i, ..., \\mathbf{s}_n\\}$ is used to score sentences.\n\\begin{eqnarray}\n\\begin{array}{l}\n\\begin{aligned}\n\\mathbf{S} & = {\\rm BERT}(C) \\\\\nscore_i & = \\sigma(W\\mathbf{s}_i+b_0)\n\\end{aligned}\n\\end{array}\n\\label{eq3_1_1}\n\\end{eqnarray}\nwhere $\\sigma$ is a sigmoid function, $\\mathbf{s}_i$ denotes the representation of the $i$-th $\\rm [CLS]$ token, \\ie the representation of the $i$-th sentence, and $score_i$ denotes the score of the $i$-th sentence. All sentences are constructed into an ordered set $S = \\{s'_1, ..., s'_i, ..., s'_n\\}$ according to their scores. Since all sentences are ranked by sentence-level scoring, some top-scoring sentences may have the same or similar meaning. To avoid redundancy, we add an entailment model DocNLI~\\cite{yin2021docnli}, a more generalizable model trained on five datasets from different benchmarks, on top of the output of BertSum to remove redundant sentences by calculating the entailment scores between sentences, \\eg we first remove the sentences that have an entailment relationship with the top-1 sentence in $S$, and then repeat this process for the remaining top-2/3/... sentence until we extract $k$ central sentences. Following previous work~\\cite{liu2019text}, we only select the top-$k$ sentences with the highest scores in Equation~\\ref{eq3_1_1} as candidate central sentences.\n\\begin{eqnarray}\n\\begin{array}{l}\n\\begin{aligned}\nS' & = {\\rm DocNLI}(S)\n\\end{aligned}\n\\end{array}\n\\label{eq3_1_2}\n\\end{eqnarray}\nwhere $S'=\\{s'_1, s'_2, ..., s'_k\\}$ is a set of central sentences that do not contain the same meaning.\n", "completion_path": "./2_context_generation.py", "namespace": "2_context_generation.sentence_ranking_by_BertSum", "type": "function", "signature_position": [ 20, 20 ], "body_position": [ 21, 33 ], "ReferenceCode_With_Comments": "\n# -----------------------------------------------------------------------\n# Snippet 1: Here, we invoke the BertSum model to performs sentence-level scoring in alignment.\n# -----------------------------------------------------------------------\n# [Begin Snippet 1]\nsent_with_score = train.main(configs)\n# [End Snippet 1]\n\n# -----------------------------------------------------------------------\n# Snippet 2: We iterate through each document, remove potential leading or\n# trailing quotes to facilitate sentence tokenization, then store the\n# scores, indices, and ordered lists of sentences. This parallels the\n# LaTeX description where sentences are re-ranked and associated with\n# \\(\\text{score}_i\\). \n# -----------------------------------------------------------------------\n# [Begin Snippet 2]\nfor idx, sample in enumerate(samples):\n fulltext = sample['fulltext']\n\n if fulltext[0] in [\"\u201c\", \"'\", \"\u201d\"] and fulltext[-1] in [\"\u201c\", \"'\", \"\u201d\"]:\n fulltext = fulltext[1:-1]\n\n sentences = sent_tokenize(fulltext)\n\n sample['sents_id_selected_by_bertsum'] = sent_with_score[idx][2]\n sample['sents_selected_by_bertsum'] = sent_with_score[idx][0]\n sample['sents_with_scores_by_bertsum'] = sent_with_score[idx][1].tolist()\n sample['sents_order_by_bertsum'] = sent_with_score[idx][4]\n sample['sent_texts_order_by_bertsum'] = sent_with_score[idx][5]\n\n sample['sentences'] = sentences\n# [End Snippet 2]\n\n# -----------------------------------------------------------------------\n# Snippet 3: Finally, we return the updated samples, which completes the\n# process of ranking sentences by BertSum.\n# -----------------------------------------------------------------------\n# [Begin Snippet 3]\nreturn samples\n# [End Snippet 3]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - Sentence Tokenization Method: The LaTeX description does not specify how sentences should be tokenized. However, the reference Python code explicitly uses NLTK's `sent_tokenize` to ensure accurate sentence boundaries.\n \n Mismatched Details:\n - The code does not include the DocNLI-based redundancy removal step.\n - The code does not explicitly limit the number of top-k sentences, whereas the LaTeX description suggests selecting only top-k.\n - Embedding and Scoring Procedure: The LaTeX description suggests sentence embeddings are derived directly from the BERT `[CLS]` token and scored using a linear layer followed by a sigmoid function. However, the reference Python code implicitly leverages BertSum's internal pipeline (`presumm.train`) to handle embedding extraction, scoring, and ranking as an integrated step.\n", "Missing_details": [ "\n- Sentence Tokenization Method: The LaTeX description does not specify how sentences should be tokenized. However, the reference Python code explicitly uses NLTK's `sent_tokenize` to ensure accurate sentence boundaries.\n" ], "Mismatched_details": [ "\n- The code does not include the DocNLI-based redundancy removal step.\n", "\n- The code does not explicitly limit the number of top-k sentences, whereas the LaTeX description suggests selecting only top-k.\n", "\n- Embedding and Scoring Procedure: The LaTeX description suggests sentence embeddings are derived directly from the BERT `[CLS]` token and scored using a linear layer followed by a sigmoid function. However, the reference Python code implicitly leverages BertSum's internal pipeline (`presumm.train`) to handle embedding extraction, scoring, and ranking as an integrated step.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - samples (list[dict]): Contains the data from which we want to extract sentences. A list where each element is a dictionary representing a document. The keys in the dictionary include:\n - 'claim' (String): The statement under investigation (e.g., that Kamala Harris called young voters \"stupid\").\n - 'label' (String): The verification outcome assigned to the claim, here labeled as \"Supported.\"\n - 'questions' (List[Dict]): Holds question-and-answer pairs or additional metadata relevant to the fact-check process.\n - 'fulltext' (String): The complete text of the article or document to be summarized.\n - configs (dict): Holds configuration parameters for BertSum, including model settings, file paths, and other inference-related attributes.\n - 'task' (String): Specifies the type of summarization task; 'ext' indicates extractive summarization.\n - 'mode' (String): The mode of operation, e.g. 'test_text' means we are testing on input text.\n - test_from (String): The path to the pre-trained BertSum model checkpoint (e.g., 'presumm/save_model/bertext_cnndm_transformer.pt').\n - 'ext_src' (String): The source file containing the text data for summarization or scoring (e.g., 'all_data/1_all_available_url_fulltext.json').\n - 'result_path' (String): The path where the model's output or generated summaries are saved.\n - 'alpha' (Float): A parameter controlling aspects of summary length or coverage (depending on the implementation in BertSum).\n - 'log_file' (String): The file where the model logs (e.g., status, warnings, errors) are written.\n - 'visible_gpus' (String): Identifies which GPU(s) to use. '0' means using the GPU device with index 0, or may indicate CPU-only if no GPU is available.\n", "Arguments_list": [ { "name": "samples", "string": "\n- samples (list[dict]): Contains the data from which we want to extract sentences. A list where each element is a dictionary representing a document. The keys in the dictionary include:\n - 'claim' (String): The statement under investigation (e.g., that Kamala Harris called young voters \"stupid\").\n - 'label' (String): The verification outcome assigned to the claim, here labeled as \"Supported.\"\n - 'questions' (List[Dict]): Holds question-and-answer pairs or additional metadata relevant to the fact-check process.\n - 'fulltext' (String): The complete text of the article or document to be summarized.\n", "dependency": null }, { "name": "configs", "string": "\n- configs (dict): Holds configuration parameters for BertSum, including model settings, file paths, and other inference-related attributes.\n - 'task' (String): Specifies the type of summarization task; 'ext' indicates extractive summarization.\n - 'mode' (String): The mode of operation, e.g. 'test_text' means we are testing on input text.\n - test_from (String): The path to the pre-trained BertSum model checkpoint (e.g., 'presumm/save_model/bertext_cnndm_transformer.pt').\n - 'ext_src' (String): The source file containing the text data for summarization or scoring (e.g., 'all_data/1_all_available_url_fulltext.json').\n - 'result_path' (String): The path where the model's output or generated summaries are saved.\n - 'alpha' (Float): A parameter controlling aspects of summary length or coverage (depending on the implementation in BertSum).\n - 'log_file' (String): The file where the model logs (e.g., status, warnings, errors) are written.\n - 'visible_gpus' (String): Identifies which GPU(s) to use. '0' means using the GPU device with index 0, or may indicate CPU-only if no GPU is available.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File Dependency: \n - None\n\n Cross-File Dependency:\n - presumm.train.main\n", "intra_file": [], "cross_file": [ "presumm.train.main" ] }, "external_APIs": { "string": "\nExternal APIs: \n - nltk.tokenize.sent_tokenize\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - samples (list of dict): Returns the original list of dictionaries with additional keys containing the sentence-ranking results from BertSum, including:\n - 'sents_id_selected_by_bertsum' (List[Int]): Indices of the sentences selected by BertSum based on their scores.\n - 'sents_selected_by_bertsum' (List[String]): The actual text of the sentences chosen by BertSum.\n - 'sents_with_scores_by_bertsum' (List[Float]): Confidence scores assigned by BertSum to the selected sentences.\n - 'sents_order_by_bertsum' (List[Int]): The ranking order of the selected sentences by score.\n - 'sent_texts_order_by_bertsum' (List[String]): The sentences re-ordered according to their rank.\n - 'sentences' (List[String]): The full text split into tokenized sentences.\n", "Return_list": [ { "name": "samples", "string": "\n- samples (list of dict): Returns the original list of dictionaries with additional keys containing the sentence-ranking results from BertSum, including:\n - 'sents_id_selected_by_bertsum' (List[Int]): Indices of the sentences selected by BertSum based on their scores.\n - 'sents_selected_by_bertsum' (List[String]): The actual text of the sentences chosen by BertSum.\n - 'sents_with_scores_by_bertsum' (List[Float]): Confidence scores assigned by BertSum to the selected sentences.\n - 'sents_order_by_bertsum' (List[Int]): The ranking order of the selected sentences by score.\n - 'sent_texts_order_by_bertsum' (List[String]): The sentences re-ordered according to their rank.\n - 'sentences' (List[String]): The full text split into tokenized sentences.\n" } ] }, "ori_python_file": "import os\nimport json\nimport spacy\nimport stanza, argparse\nimport numpy as np\nfrom tqdm import tqdm\nfrom nltk.translate.chrf_score import sentence_chrf\nimport sys\nsys.path.append('presumm')\nfrom presumm import train\nfrom nltk.tokenize import sent_tokenize\nimport torch\nimport torch.nn as nn\nfrom simcse import SimCSE\nfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLM, T5ForConditionalGeneration\nfrom transformers import AutoModelForSequenceClassification\nfrom transformers.models.roberta.modeling_roberta import RobertaModel\nimport pickle\n\ndef sentence_ranking_by_BertSum(samples, configs):\n sent_with_score = train.main(configs)\n for idx, sample in enumerate(samples):\n fulltext = sample['fulltext']\n if fulltext[0] in [\"\u201c\", \"'\", \"\u201d\"] and fulltext[-1] in [\"\u201c\", \"'\", \"\u201d\"]:\n fulltext = fulltext[1:-1]\n sentences = sent_tokenize(fulltext)\n sample['sents_id_selected_by_bertsum'] = sent_with_score[idx][2]\n sample['sents_selected_by_bertsum'] = sent_with_score[idx][0]\n sample['sents_with_scores_by_bertsum'] = sent_with_score[idx][1].tolist()\n sample['sents_order_by_bertsum'] = sent_with_score[idx][4]\n sample['sent_texts_order_by_bertsum'] = sent_with_score[idx][5]\n sample['sentences'] = sentences\n return samples\n\ndef get_phrases(tree, label):\n if tree.is_leaf():\n return []\n results = []\n for child in tree.children:\n results += get_phrases(child, label)\n if tree.label == label:\n return [' '.join(tree.leaf_labels())] + results\n else:\n return results\n\ndef candidate_answer_extraction(samples):\n nlp = spacy.load('en_core_web_lg')\n stanza_nlp = stanza.Pipeline(lang='en', processors='tokenize,pos,constituency')\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Candidate Generation\"):\n fulltext = sample['fulltext']\n chrf_all_sents = [sentence_chrf(sample['claim'].split(), sent.split()) for sent in sample['sentences']]\n top3_sent_id_in_all_sents = np.argsort(-np.array(chrf_all_sents)).tolist()[:3]\n top3_chrf_in_all_sents = [chrf_all_sents[i] for i in top3_sent_id_in_all_sents]\n sample['top3_sent_in_all_sents'] = [top3_sent_id_in_all_sents, top3_chrf_in_all_sents]\n chrf_ext_sents = [sentence_chrf(sample['claim'].split(), sample['sentences'][_id].split()) for _id in\n sample['sents_order_by_bertsum']]\n order_top3_sent_id_in_ext_sents = np.argsort(-np.array(chrf_ext_sents)).tolist()[:3]\n top3_sent_id_in_ext_sents = [sample['sents_order_by_bertsum'][j] for j in order_top3_sent_id_in_ext_sents]\n top3_chrf_in_ext_sents = [chrf_ext_sents[i] for i in order_top3_sent_id_in_ext_sents]\n sample['top3_sent_in_ext_sents'] = [top3_sent_id_in_ext_sents, top3_chrf_in_ext_sents]\n if fulltext not in fulltext_processed.keys():\n sample['candidate_answers'] = []\n central_sents_sel_by_bertsum = [i for i in sample['sents_order_by_bertsum']]\n candidate_central_sentences = [sample['sentences'][i] for i in central_sents_sel_by_bertsum]\n candidate_answers = []\n for sent in candidate_central_sentences:\n if sent:\n candidate_answers_list = []\n doc = nlp(sent)\n stanza_doc = stanza_nlp(sent)\n ents = [ent.text for sent in doc.sents for ent in sent.noun_chunks]\n ents += [ent.text for sent in doc.sents for ent in sent.ents]\n ents += [phrase for sent in stanza_doc.sentences for phrase in get_phrases(sent.constituency, 'NP')]\n ents += [phrase for sent in stanza_doc.sentences for phrase in get_phrases(sent.constituency, 'VP')]\n ents += [word.text for sent in stanza_doc.sentences for word in sent.words if\n word.upos in ['VERB', 'ADV', 'ADJ', 'NOUN']]\n negations = [word for word in ['not', 'never'] if word in sample['fulltext']]\n candidate_answers_list.extend(sorted(set(ents + negations)))\n candidate_answers.append(candidate_answers_list)\n sample['candidate_answers'].extend(candidate_answers)\n fulltext_processed[fulltext] = sample['candidate_answers']\n else:\n print(\"Load the processed fulltext\")\n sample['candidate_answers'] = fulltext_processed[fulltext]\n return samples\n\ndef question_generation(samples, tokenizer, model, batch_size, max_length_gen=32, max_length_tokenizer=1024):\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Generating Questions\"):\n fulltext = sample['fulltext']\n if fulltext not in fulltext_processed.keys():\n sample['generated_question'] = []\n cand_sents = [i for i in sample['sents_order_by_bertsum']]\n assert len(cand_sents) == len(sample['candidate_answers'])\n for idx in range(len(sample['candidate_answers'])):\n texts = []\n _sentence = sample['sentences'][cand_sents[idx]]\n _candidate_ansewrs = sample['candidate_answers'][idx]\n for cand_ans in _candidate_ansewrs:\n texts.append(f\"{_sentence} \\\\n {cand_ans}\")\n gen_question = []\n if texts:\n for idy in range(0, len(texts), batch_size):\n input_ids = tokenizer(\n texts[idy:idy + batch_size],\n return_tensors=\"pt\",\n padding='longest',\n truncation=True,\n max_length=max_length_tokenizer\n ).input_ids.to(model.device)\n generated_ids = model.generate(input_ids, max_length=max_length_gen, do_sample=False)\n output = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)\n gen_question.extend(output)\n sample['generated_question'].append(gen_question)\n else:\n sample['generated_question'].append(gen_question)\n fulltext_processed[fulltext] = sample['generated_question']\n else:\n sample['generated_question'] = fulltext_processed[fulltext]\n return samples\n\ndef qa_generation(samples, model, tokenizer):\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Generating Answers\"):\n fulltext = sample['fulltext']\n cand_sents = [i for i in sample['sents_order_by_bertsum']]\n if fulltext not in fulltext_processed.keys():\n sample['answer'] = []\n for idx, questions in enumerate(sample['generated_question']):\n print(\"id={}/{}\".format(idx, len(sample['generated_question'])))\n if len(fulltext) <= 400:\n context = fulltext\n else:\n if cand_sents[idx] >= 10:\n context = sample['sentences'][\n (cand_sents[idx] - 10):(cand_sents[idx] + 10)\n ]\n else:\n context = sample['sentences'][0:(cand_sents[idx] + 10)]\n current_answers = []\n question_processed = dict()\n for idy, question in enumerate(questions):\n if question not in question_processed.keys():\n input_ids = tokenizer.encode(\n f\"{question} \\n {context}\",\n return_tensors='pt'\n ).to(model.device)\n with torch.no_grad():\n outputs = model.generate(\n input_ids,\n num_beams=4,\n do_sample=False\n )\n predict_answer_tokens_string = tokenizer.batch_decode(\n outputs,\n skip_special_tokens=True\n )[0]\n current_answers.append(predict_answer_tokens_string.strip())\n question_processed[question] = predict_answer_tokens_string.strip()\n else:\n print(\"Load the processed question\")\n current_answers.append(question_processed[question])\n sample['answer'].append(current_answers)\n fulltext_processed[fulltext] = sample['answer']\n else:\n print(\"Load the processed fulltext\")\n sample['answer'] = fulltext_processed[fulltext]\n return samples\n\ndef qa_to_context(samples, model, tokenizer, max_length_tokenizer=512, max_length_gen=64):\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Converting QA to statements\"):\n fulltext = sample['fulltext']\n if fulltext not in fulltext_processed.keys():\n generated_questions = sample['generated_question']\n generated_answers = sample['answer']\n sample['candidate_claims'] = []\n for questions, answers in zip(generated_questions, generated_answers):\n candidate_corrections_list = []\n qa_pair_processed = dict()\n for idx, answer in enumerate(answers):\n input_text = f\"{answer} \\\\n {questions[idx]}\"\n if input_text not in qa_pair_processed.keys():\n input_ids = tokenizer(\n input_text,\n return_tensors=\"pt\",\n padding='longest',\n truncation=True,\n max_length=max_length_tokenizer\n ).input_ids.to(model.device)\n generated_ids = model.generate(\n input_ids,\n max_length=max_length_gen,\n do_sample=False,\n early_stopping=True\n )\n candidate_corrections = tokenizer.batch_decode(\n generated_ids,\n skip_special_tokens=True\n )\n candidate_corrections_list.append(candidate_corrections)\n qa_pair_processed[input_text] = candidate_corrections\n else:\n print(\"Load the processed qa pair\")\n candidate_corrections_list.append(qa_pair_processed[input_text])\n sample['candidate_claims'].append(candidate_corrections_list)\n fulltext_processed[fulltext] = sample['candidate_claims']\n else:\n print(\"Load the processed fulltext\")\n sample['candidate_claims'] = fulltext_processed[fulltext]\n return samples\n\ndef gen_highquality_context(samples):\n simcse_model = SimCSE(\"princeton-nlp/sup-simcse-roberta-large\")\n cw_labels = ['Non-Factual Statement(NFS)', 'Unimportant Factual Statement(UFS)', 'Check-worthy Factual Statement(CFS)']\n cw_tokenizer = AutoTokenizer.from_pretrained(\"whispAI/ClaimBuster-DeBERTaV2\", use_auth_token=True)\n cw_model = AutoModelForSequenceClassification.from_pretrained(\"whispAI/ClaimBuster-DeBERTaV2\", use_auth_token=True)\n class RobertaForSequenceClassification(nn.Module):\n def __init__(self, tagset_size):\n super(RobertaForSequenceClassification, self).__init__()\n self.tagset_size = tagset_size\n self.roberta_single = RobertaModel.from_pretrained(pretrain_model_dir)\n self.single_hidden2tag = RobertaClassificationHead(bert_hidden_dim, tagset_size)\n def forward(self, input_ids, input_mask):\n outputs_single = self.roberta_single(input_ids, input_mask, None)\n hidden_states_single = outputs_single[1]\n score_single = self.single_hidden2tag(hidden_states_single)\n return score_single\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n bert_hidden_dim = 1024\n pretrain_model_dir = 'roberta-large'\n label_list = [\"entailment\", \"not_entailment\"]\n num_labels = len(label_list)\n class RobertaClassificationHead(nn.Module):\n def __init__(self, bert_hidden_dim, num_labels):\n super(RobertaClassificationHead, self).__init__()\n self.dense = nn.Linear(bert_hidden_dim, bert_hidden_dim)\n self.dropout = nn.Dropout(0.1)\n self.out_proj = nn.Linear(bert_hidden_dim, num_labels)\n def forward(self, features):\n x = features\n x = self.dropout(x)\n x = self.dense(x)\n x = torch.tanh(x)\n x = self.dropout(x)\n x = self.out_proj(x)\n return x\n model = RobertaForSequenceClassification(num_labels).to(device)\n tokenizer = AutoTokenizer.from_pretrained(pretrain_model_dir)\n checkpoint = torch.load('docnli_model/DocNLI.pretrained.RoBERTA.model.pt')\n model.load_state_dict(checkpoint, strict=False)\n def entailment_score(text1, text2):\n encoded_ctx = tokenizer.encode(text1)[:-1]\n encoded_correction = tokenizer.encode(text2)[1:]\n encoded_ctx_truncated = encoded_ctx[:512 - 1 - len(encoded_correction)]\n input_ids = torch.LongTensor(encoded_ctx_truncated + [tokenizer.sep_token_id] + encoded_correction).unsqueeze(\n 0).to(device)\n attention_mask = torch.LongTensor([1] * len(input_ids)).unsqueeze(0).to(device)\n inputs = {'input_ids': input_ids, 'input_mask': attention_mask}\n with torch.no_grad():\n model.eval()\n logits = model(**inputs)\n probs = torch.nn.Softmax(dim=1)(logits)\n correct_prob = probs[0][0].item()\n return correct_prob\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Running DocNLI\"):\n fulltext = sample['fulltext']\n cand_sents = [i for i in sample['sents_order_by_bertsum']]\n if fulltext not in fulltext_processed.keys():\n sample['claim_rank_by_entail_score'] = []\n sample['claim_rank_by_simcse_score'] = []\n sample['final_claims_cw'] = []\n sample['final_claims'] = []\n for idx, gen_claim in enumerate(sample['candidate_claims']):\n cand_claim_by_entail = []\n cand_claim_by_simcse = []\n cand_claim_rmv_dup = []\n if gen_claim:\n gen_claim_entail_scores = []\n gen_claim_simcse_scores = []\n claim_processed = dict()\n for idy, _claim in enumerate(gen_claim):\n if _claim[0] not in claim_processed.keys():\n correct_prob = entailment_score(sample['sentences'][cand_sents[idx]], _claim[0])\n gen_claim_entail_scores.append(correct_prob)\n claim_processed[_claim[0]] = correct_prob\n else:\n print(\"load the processed claim\")\n gen_claim_entail_scores.append(claim_processed[_claim[0]])\n topk_claims_id = range(len(gen_claim_entail_scores))\n if not topk_claims_id:\n topk_claims_id = np.argsort(-np.array(gen_claim_entail_scores)).tolist()[:5]\n for idz, _claim in enumerate(gen_claim):\n if idz in topk_claims_id:\n if [_claim[0], gen_claim_entail_scores[idz]] not in cand_claim_by_entail:\n cand_claim_by_entail.append([_claim[0], gen_claim_entail_scores[idz]])\n cand_claim_by_entail = sorted(cand_claim_by_entail, key=lambda x: x[1], reverse=True)\n if cand_claim_by_entail:\n cand_claim_by_entail_list = [c for c, s in cand_claim_by_entail]\n simcse_score = (simcse_model.similarity(sample['sentences'][cand_sents[idx]],\n cand_claim_by_entail_list)).ravel().tolist()\n gen_claim_simcse_scores.extend(simcse_score)\n cand_claim_by_simcse_id = np.argsort(-np.array(gen_claim_simcse_scores)).tolist()\n cand_claim_by_simcse.extend(\n [cand_claim_by_entail_list[i], gen_claim_simcse_scores[i]] for i in cand_claim_by_simcse_id)\n sample['claim_rank_by_entail_score'].append(cand_claim_by_entail)\n sample['claim_rank_by_simcse_score'].append(cand_claim_by_simcse)\n cand_claim_rmv_dup.extend([c for c, s in cand_claim_by_simcse])\n filter_by_entail_ids = []\n for i in reversed(range(len(cand_claim_rmv_dup))):\n for j in reversed(range(i)):\n if i not in filter_by_entail_ids:\n entail_prob = entailment_score(cand_claim_rmv_dup[j], cand_claim_rmv_dup[i])\n if entail_prob > 0.9:\n filter_by_entail_ids.append(i)\n for i in filter_by_entail_ids:\n del cand_claim_rmv_dup[i]\n simcse_sents = simcse_model.similarity(cand_claim_rmv_dup, cand_claim_rmv_dup)\n filter_by_simcse_ids = []\n for i in reversed(range(len(cand_claim_rmv_dup))):\n for j in reversed(range(i)):\n if i not in filter_by_simcse_ids:\n if simcse_sents[i][j] > 0.85:\n filter_by_simcse_ids.append(i)\n for i in filter_by_simcse_ids:\n del cand_claim_rmv_dup[i]\n cand_claim_with_check_worthy = []\n cand_claim_final = []\n for claim_text in cand_claim_rmv_dup:\n cw_sent_inputs = cw_tokenizer(claim_text, return_tensors=\"pt\")\n cw_sent_outputs = cw_model(**cw_sent_inputs)\n sent_logits = cw_sent_outputs.logits.tolist()[0]\n cw_sent_class = np.argmax(sent_logits)\n sent_label = cw_labels[int(cw_sent_class)]\n cand_claim_with_check_worthy.append([claim_text, sent_label, sent_logits])\n if sent_label in ['Unimportant Factual Statement(UFS)', 'Check-worthy Factual Statement(CFS)']:\n cand_claim_final.append([claim_text])\n sample['final_claims_cw'].append(cand_claim_with_check_worthy)\n sample['final_claims'].append(cand_claim_final)\n else:\n sample['claim_rank_by_entail_score'].append(cand_claim_by_entail)\n sample['claim_rank_by_simcse_score'].append(cand_claim_by_simcse)\n sample['final_claims_cw'].append([])\n sample['final_claims'].append([])\n fulltext_processed[fulltext] = [sample['claim_rank_by_entail_score'],\n sample['claim_rank_by_simcse_score'], sample['final_claims_cw'],\n sample['final_claims']]\n else:\n print(\"Load the processed fulltext\")\n sample['claim_rank_by_entail_score'], sample['claim_rank_by_simcse_score'], sample['final_claims_cw'], sample['final_claims'] = fulltext_processed[fulltext]\n return samples\n\ndef main(args):\n import os, random\n os.environ['PYTHONHASHSEED'] = str(42)\n os.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\n np.random.seed(42)\n if torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\n torch.use_deterministic_algorithms(True)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n random.seed(42)\n torch.cuda.synchronize()\n data_path = \"all_data\"\n all_avail_url_files = \"{}/1_all_available_url_fulltext.json\".format(data_path)\n if not os.path.exists(all_avail_url_files):\n print(\"***** run python 1_extract_texts_from_url.py *****\")\n ranked_sentence_file = \"{}/2_sent_ranked_by_bertsum.json\".format(data_path)\n samples = json.load(open(all_avail_url_files, 'r'))\n if args.TestCode:\n samples = samples[:10]\n configs = dict()\n configs['task'] = 'ext'\n configs['mode'] = 'test_text'\n configs['test_from'] = 'presumm/save_model/bertext_cnndm_transformer.pt'\n configs['text_src'] = 'all_data/1_all_available_url_fulltext.json'\n configs['result_path'] = 'presumm/results/ootb_output'\n configs['alpha'] = 0.95\n configs['log_file'] = 'presumm/logs/test.log'\n configs['visible_gpus'] = '0'\n ranked_samples = sentence_ranking_by_BertSum(samples, configs)\n cand_ans_extraction_file = \"{}/3_generated_candidates.jsonl\".format(data_path)\n cand_ans_samples = candidate_answer_extraction(ranked_samples)\n gen_question_file = \"{}/4_generated_questions.jsonl\".format(data_path)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n tokenizer = AutoTokenizer.from_pretrained('t5-base')\n model = AutoModelForSeq2SeqLM.from_pretrained('Salesforce/mixqg-base').to(device)\n model.eval()\n batch_size = 10\n gen_que_samples = question_generation(cand_ans_samples, tokenizer, model, batch_size)\n gen_answer_file = \"{}/5_generated_answers.jsonl\".format(data_path)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model_name = 'allenai/unifiedqa-v2-t5-base-1251000'\n tokenizer = AutoTokenizer.from_pretrained('t5-base')\n model = T5ForConditionalGeneration.from_pretrained(model_name).to(device)\n model.eval()\n gen_answer_samples = qa_generation(gen_que_samples, model, tokenizer)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n pretrain_model_path = \"khhuang/zerofec-qa2claim-t5-base\"\n tokenizer = AutoTokenizer.from_pretrained('t5-base')\n model = AutoModelForSeq2SeqLM.from_pretrained(pretrain_model_path).to(device)\n model.eval()\n gen_context_file = \"{}/6_generated_context.jsonl\".format(data_path)\n gen_context_samples = qa_to_context(gen_answer_samples, model, tokenizer)\n gen_context_file = \"{}/7_highquality_context.jsonl\".format(data_path)\n gen_highcontext_samples = gen_highquality_context(gen_context_samples)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n main(args)" }, { "task_id": 1, "indent": 1, "script": "\npython 2_context_generation.py\n", "latex_code": "\n\\paragraph{Question Generation.} To identify ambiguous information units in candidate central sentences, we first use Spacy\\protect\\footnotemark[4] to extract named entities, pronouns, nouns, noun phrases, verbs and verb phrases in the sentence $i$ as the potentially ambiguous information units ${U}_i=$ $\\{u^1_i, u^2_i, ..., u^j_i, ..., u^m_i\\}, i \\in [1,2,...,k]$, where $u^j_i$ denotes the $j$-th information unit of the $i$-th candidate sentence $s'_i$. \n\n\\footnotetext[4]{\\url{https://spacy.io}}\n\nOnce the set of information units for a sentence ${U}_i$ is identified, we then generate a question for each of them. Specifically, we concatenate $u^j_i$ and $s'_i$ in which $u^j_i$ is located as the input sequence and feed it into $\\rm QG$~\\cite{murakhovs2021mixqg}, a question generator model trained on nine question generation datasets with different types of answers, to produce the question $q^j_i$ with $u^j_i$ as the answer. \n\\begin{eqnarray}\n\\begin{array}{l}\n{Q}_i = \\{q^j_i\\}^{m}_{j=1} = \\{{\\rm QG}(s'_i, u^j_i)\\}^{m}_{j=1}\n\\end{array}\n\\label{eq3_2_1}\n\\end{eqnarray}\nwhere ${Q}_i$ denotes the set of questions corresponding to $U_i$ in the sentence $s'_i$.\n", "completion_path": "./2_context_generation.py", "namespace": "2_context_generation.question_generation", "type": "function", "signature_position": [ 88, 88 ], "body_position": [ 89, 121 ], "ReferenceCode_With_Comments": " \nfulltext_processed = dict()\n\nfor sample in tqdm(samples, desc=\"Generating Questions\"):\n fulltext = sample['fulltext']\n\n\n # -----------------------------------------------------------------------\n # Snippet 1: Here, we initialize structures in the sample to hold the new\n # questions if the current 'fulltext' has not been processed. We also\n # verify the number of candidate sentences matches the number\n # of ambiguous units , which the LaTeX describes as \n # U\u1d62 = {u\u1d62\u00b9, u\u1d62\u00b2, ...}. This check ensures each extracted unit aligns\n # with the target sentence s\u1d62\u2032 before question generation.\n # -----------------------------------------------------------------------\n # [Begin Snippet 1]\n if fulltext not in fulltext_processed.keys():\n sample['generated_question'] = []\n\n cand_sents = [i for i in sample['sents_order_by_bertsum']]\n assert len(cand_sents) == len(sample['candidate_answers'])\n # [End Snippet 1]\n\n # -------------------------------------------------------------------\n # Snippet 2: For each candidate sentence, we build the input sequence\n # for the question generator by joining the sentence s\u1d62\u2032 with each\n # ambiguous unit u\u1d62\u02b2. This step fulfills\n # the LaTeX description of feeding s\u1d62\u2032 and u\u1d62\u02b2 into QG(s\u1d62\u2032, u\u1d62\u02b2).\n # -------------------------------------------------------------------\n # [Begin Snippet 2]\n for idx in range(len(sample['candidate_answers'])):\n texts = []\n _sentence = sample['sentences'][cand_sents[idx]]\n _candidate_ansewrs = sample['candidate_answers'][idx]\n\n for cand_ans in _candidate_ansewrs:\n texts.append(f\"{_sentence} \\\\n {cand_ans}\")\n\n gen_question = []\n # [End Snippet 2]\n\n # -----------------------------------------------------------------\n # Snippet 3: We perform batch processing of these joined inputs\n # through the question generation model. The resulting questions\n # correspond to q\u1d62\u02b2 in the LaTeX, capturing the ambiguous unit as\n # an answer. The loop then appends these generated questions to the\n # sample dictionary for future stages.\n # -----------------------------------------------------------------\n # [Begin Snippet 3]\n if texts:\n for idy in range(0, len(texts), batch_size):\n input_ids = tokenizer(\n texts[idy:idy + batch_size],\n return_tensors=\"pt\",\n padding='longest',\n truncation=True,\n max_length=max_length_tokenizer\n ).input_ids.to(model.device)\n\n generated_ids = model.generate(input_ids, max_length=max_length_gen, do_sample=False)\n\n output = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)\n gen_question.extend(output)\n\n sample['generated_question'].append(gen_question)\n else:\n sample['generated_question'].append(gen_question)\n # [End Snippet 3]\n\n fulltext_processed[fulltext] = sample['generated_question']\n else:\n sample['generated_question'] = fulltext_processed[fulltext]\n\n# -----------------------------------------------------------------\n# Snippet 4: Return the samples\n# -----------------------------------------------------------------\n# [Begin Snippet 4]\nreturn samples\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - Spacy-based information unit extraction is handled in a previous step (candidate_answer_extraction)\n - The generation adopts the greedy decoding strategy.\n - The LaTeX description omits the caching mechanism present in the reference Python code. In the reference implementation, a dictionary is used to store generated questions keyed by the `fulltext` of each sample. The workflow involves checking if the `fulltext` of a sample has already been processed; if so, it retrieves the cached questions without re-running the question generation model. If not, it generates questions, stores them in the cache, and updates the sample.\n - The LaTeX does not specify the formatting of the input sequence for the QG model. In the reference code, the workflow constructs each input by concatenating the sentence (`_sentence`) and candidate answer (`cand_ans`) with a newline separator (`\"{_sentence} \\\\n {cand_ans}\"`). This specific formatting is fed into the tokenizer and model, potentially influencing how the QG model interprets the context and generates questions.\n - The LaTeX omits the deterministic behavior specification for the QG model. In the reference code, the workflow explicitly sets `do_sample=False` in the `model.generate()` call, ensuring that question generation is deterministic and reproducible across runs.\n\n Mismatched Details:\n - None\n", "Missing_details": [ "\n- Spacy-based information unit extraction is handled in a previous step (candidate_answer_extraction)\n", "\n- The generation adopts the greedy decoding strategy.\n", "\n- The LaTeX description omits the caching mechanism present in the reference Python code. In the reference implementation, a dictionary is used to store generated questions keyed by the `fulltext` of each sample. The workflow involves checking if the `fulltext` of a sample has already been processed; if so, it retrieves the cached questions without re-running the question generation model. If not, it generates questions, stores them in the cache, and updates the sample.\n", "\n- The LaTeX does not specify the formatting of the input sequence for the QG model. In the reference code, the workflow constructs each input by concatenating the sentence (`_sentence`) and candidate answer (`cand_ans`) with a newline separator (`\"{_sentence} \\\\n {cand_ans}\"`). This specific formatting is fed into the tokenizer and model, potentially influencing how the QG model interprets the context and generates questions.\n", "\n- The LaTeX omits the deterministic behavior specification for the QG model. In the reference code, the workflow explicitly sets `do_sample=False` in the `model.generate()` call, ensuring that question generation is deterministic and reproducible across runs.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - samples (list[dict]): Contains the data from which we want to extract sentences. A list where each element is a dictionary representing a document. The keys in the dictionary include:\n - 'claim' (String): The statement under investigation (e.g., that Kamala Harris called young voters \"stupid\").\n - 'label' (String): The verification outcome assigned to the claim, here labeled as \"Supported.\"\n - 'questions' (List[Dict]): Holds question-and-answer pairs or additional metadata relevant to the fact-check process.\n - 'fulltext' (String): The complete text of the article or document to be summarized.\n - 'sents_id_selected_by_bertsum' (List[Int]): Indices of the sentences selected by BertSum based on their scores.\n - 'sents_selected_by_bertsum' (List[String]): The actual text of the sentences chosen by BertSum.\n - 'sents_with_scores_by_bertsum' (List[Float]): Confidence scores assigned by BertSum to the selected sentences.\n - 'sents_order_by_bertsum' (List[Int]): The ranking order of the selected sentences by score.\n - 'sent_texts_order_by_bertsum' (List[String]): The sentences re-ordered according to their rank.\n - 'sentences' (List[String]): The full text split into tokenized sentences.\n - 'candidate_answers' (List[List[String]]): Candidate answers extracted from the selected sentences.\n - tokenizer (transformers.PreTrainedTokenizer):\n A tokenizer from Hugging Face Transformers configured for the question generation model.\n - model (transformers.PreTrainedModel):\n A pre-trained seq2seq model used for question generation.\n - batch_size (int):\n Controls how many examples are processed at once when sending data to the question generation model.\n - max_length_gen (int):\n The maximum generate length for the model.\n - max_length_tokenizer (int):\n The maximum length for tokenizer.\n", "Arguments_list": [ { "name": "samples", "string": "\n- samples (list[dict]): Contains the data from which we want to extract sentences. A list where each element is a dictionary representing a document. The keys in the dictionary include:\n - 'claim' (String): The statement under investigation (e.g., that Kamala Harris called young voters \"stupid\").\n - 'label' (String): The verification outcome assigned to the claim, here labeled as \"Supported.\"\n - 'questions' (List[Dict]): Holds question-and-answer pairs or additional metadata relevant to the fact-check process.\n - 'fulltext' (String): The complete text of the article or document to be summarized.\n - 'sents_id_selected_by_bertsum' (List[Int]): Indices of the sentences selected by BertSum based on their scores.\n - 'sents_selected_by_bertsum' (List[String]): The actual text of the sentences chosen by BertSum.\n - 'sents_with_scores_by_bertsum' (List[Float]): Confidence scores assigned by BertSum to the selected sentences.\n - 'sents_order_by_bertsum' (List[Int]): The ranking order of the selected sentences by score.\n - 'sent_texts_order_by_bertsum' (List[String]): The sentences re-ordered according to their rank.\n - 'sentences' (List[String]): The full text split into tokenized sentences.\n - 'candidate_answers' (List[List[String]]): Candidate answers extracted from the selected sentences.\n", "dependency": null }, { "name": "tokenizer", "string": "\n- tokenizer (transformers.PreTrainedTokenizer):\n A tokenizer from Hugging Face Transformers configured for the question generation model.\n", "dependency": null }, { "name": "model", "string": "\n- model (transformers.PreTrainedModel):\n A pre-trained seq2seq model used for question generation.\n", "dependency": null }, { "name": "batch_size", "string": "\n- batch_size (int):\n Controls how many examples are processed at once when sending data to the question generation model.\n", "dependency": null }, { "name": "max_length_gen", "string": "\n- max_length_gen (int):\n The maximum generate length for the model.\n", "dependency": null }, { "name": "max_length_tokenizer", "string": "\n- max_length_tokenizer (int):\n The maximum length for tokenizer.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File Dependency: \n - None\n\n Cross-File Dependency:\n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIS:\n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - samples (list of dict): Returns the original list of dictionaries with additional keys containing the generated questions for each candidate answer. The updated key is:\n - 'generated_question' (List[List[String]]): corresponding to the list of questions generated by the QG model for each candidate answer in 'candidate_answers'.\n", "Return_list": [ { "name": "samples", "string": "\n- samples (list of dict): Returns the original list of dictionaries with additional keys containing the generated questions for each candidate answer. The updated key is:\n - 'generated_question' (List[List[String]]): corresponding to the list of questions generated by the QG model for each candidate answer in 'candidate_answers'.\n" } ] }, "ori_python_file": "import os\nimport json\nimport spacy\nimport stanza, argparse\nimport numpy as np\nfrom tqdm import tqdm\nfrom nltk.translate.chrf_score import sentence_chrf\nimport sys\nsys.path.append('presumm')\nfrom presumm import train\nfrom nltk.tokenize import sent_tokenize\nimport torch\nimport torch.nn as nn\nfrom simcse import SimCSE\nfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLM, T5ForConditionalGeneration\nfrom transformers import AutoModelForSequenceClassification\nfrom transformers.models.roberta.modeling_roberta import RobertaModel\nimport pickle\n\ndef sentence_ranking_by_BertSum(samples, configs):\n sent_with_score = train.main(configs)\n for idx, sample in enumerate(samples):\n fulltext = sample['fulltext']\n if fulltext[0] in [\"\u201c\", \"'\", \"\u201d\"] and fulltext[-1] in [\"\u201c\", \"'\", \"\u201d\"]:\n fulltext = fulltext[1:-1]\n sentences = sent_tokenize(fulltext)\n sample['sents_id_selected_by_bertsum'] = sent_with_score[idx][2]\n sample['sents_selected_by_bertsum'] = sent_with_score[idx][0]\n sample['sents_with_scores_by_bertsum'] = sent_with_score[idx][1].tolist()\n sample['sents_order_by_bertsum'] = sent_with_score[idx][4]\n sample['sent_texts_order_by_bertsum'] = sent_with_score[idx][5]\n sample['sentences'] = sentences\n return samples\n\ndef get_phrases(tree, label):\n if tree.is_leaf():\n return []\n results = []\n for child in tree.children:\n results += get_phrases(child, label)\n if tree.label == label:\n return [' '.join(tree.leaf_labels())] + results\n else:\n return results\n\ndef candidate_answer_extraction(samples):\n nlp = spacy.load('en_core_web_lg')\n stanza_nlp = stanza.Pipeline(lang='en', processors='tokenize,pos,constituency')\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Candidate Generation\"):\n fulltext = sample['fulltext']\n chrf_all_sents = [sentence_chrf(sample['claim'].split(), sent.split()) for sent in sample['sentences']]\n top3_sent_id_in_all_sents = np.argsort(-np.array(chrf_all_sents)).tolist()[:3]\n top3_chrf_in_all_sents = [chrf_all_sents[i] for i in top3_sent_id_in_all_sents]\n sample['top3_sent_in_all_sents'] = [top3_sent_id_in_all_sents, top3_chrf_in_all_sents]\n chrf_ext_sents = [sentence_chrf(sample['claim'].split(), sample['sentences'][_id].split()) for _id in\n sample['sents_order_by_bertsum']]\n order_top3_sent_id_in_ext_sents = np.argsort(-np.array(chrf_ext_sents)).tolist()[:3]\n top3_sent_id_in_ext_sents = [sample['sents_order_by_bertsum'][j] for j in order_top3_sent_id_in_ext_sents]\n top3_chrf_in_ext_sents = [chrf_ext_sents[i] for i in order_top3_sent_id_in_ext_sents]\n sample['top3_sent_in_ext_sents'] = [top3_sent_id_in_ext_sents, top3_chrf_in_ext_sents]\n if fulltext not in fulltext_processed.keys():\n sample['candidate_answers'] = []\n central_sents_sel_by_bertsum = [i for i in sample['sents_order_by_bertsum']]\n candidate_central_sentences = [sample['sentences'][i] for i in central_sents_sel_by_bertsum]\n candidate_answers = []\n for sent in candidate_central_sentences:\n if sent:\n candidate_answers_list = []\n doc = nlp(sent)\n stanza_doc = stanza_nlp(sent)\n ents = [ent.text for sent in doc.sents for ent in sent.noun_chunks]\n ents += [ent.text for sent in doc.sents for ent in sent.ents]\n ents += [phrase for sent in stanza_doc.sentences for phrase in get_phrases(sent.constituency, 'NP')]\n ents += [phrase for sent in stanza_doc.sentences for phrase in get_phrases(sent.constituency, 'VP')]\n ents += [word.text for sent in stanza_doc.sentences for word in sent.words if\n word.upos in ['VERB', 'ADV', 'ADJ', 'NOUN']]\n negations = [word for word in ['not', 'never'] if word in sample['fulltext']]\n candidate_answers_list.extend(sorted(set(ents + negations)))\n candidate_answers.append(candidate_answers_list)\n sample['candidate_answers'].extend(candidate_answers)\n fulltext_processed[fulltext] = sample['candidate_answers']\n else:\n print(\"Load the processed fulltext\")\n sample['candidate_answers'] = fulltext_processed[fulltext]\n return samples\n\ndef question_generation(samples, tokenizer, model, batch_size, max_length_gen=32, max_length_tokenizer=1024):\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Generating Questions\"):\n fulltext = sample['fulltext']\n if fulltext not in fulltext_processed.keys():\n sample['generated_question'] = []\n cand_sents = [i for i in sample['sents_order_by_bertsum']]\n assert len(cand_sents) == len(sample['candidate_answers'])\n for idx in range(len(sample['candidate_answers'])):\n texts = []\n _sentence = sample['sentences'][cand_sents[idx]]\n _candidate_ansewrs = sample['candidate_answers'][idx]\n for cand_ans in _candidate_ansewrs:\n texts.append(f\"{_sentence} \\\\n {cand_ans}\")\n gen_question = []\n if texts:\n for idy in range(0, len(texts), batch_size):\n input_ids = tokenizer(\n texts[idy:idy + batch_size],\n return_tensors=\"pt\",\n padding='longest',\n truncation=True,\n max_length=max_length_tokenizer\n ).input_ids.to(model.device)\n generated_ids = model.generate(input_ids, max_length=max_length_gen, do_sample=False)\n output = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)\n gen_question.extend(output)\n sample['generated_question'].append(gen_question)\n else:\n sample['generated_question'].append(gen_question)\n fulltext_processed[fulltext] = sample['generated_question']\n else:\n sample['generated_question'] = fulltext_processed[fulltext]\n return samples\n\ndef qa_generation(samples, model, tokenizer):\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Generating Answers\"):\n fulltext = sample['fulltext']\n cand_sents = [i for i in sample['sents_order_by_bertsum']]\n if fulltext not in fulltext_processed.keys():\n sample['answer'] = []\n for idx, questions in enumerate(sample['generated_question']):\n print(\"id={}/{}\".format(idx, len(sample['generated_question'])))\n if len(fulltext) <= 400:\n context = fulltext\n else:\n if cand_sents[idx] >= 10:\n context = sample['sentences'][\n (cand_sents[idx] - 10):(cand_sents[idx] + 10)\n ]\n else:\n context = sample['sentences'][0:(cand_sents[idx] + 10)]\n current_answers = []\n question_processed = dict()\n for idy, question in enumerate(questions):\n if question not in question_processed.keys():\n input_ids = tokenizer.encode(\n f\"{question} \\n {context}\",\n return_tensors='pt'\n ).to(model.device)\n with torch.no_grad():\n outputs = model.generate(\n input_ids,\n num_beams=4,\n do_sample=False\n )\n predict_answer_tokens_string = tokenizer.batch_decode(\n outputs,\n skip_special_tokens=True\n )[0]\n current_answers.append(predict_answer_tokens_string.strip())\n question_processed[question] = predict_answer_tokens_string.strip()\n else:\n print(\"Load the processed question\")\n current_answers.append(question_processed[question])\n sample['answer'].append(current_answers)\n fulltext_processed[fulltext] = sample['answer']\n else:\n print(\"Load the processed fulltext\")\n sample['answer'] = fulltext_processed[fulltext]\n return samples\n\ndef qa_to_context(samples, model, tokenizer, max_length_tokenizer=512, max_length_gen=64):\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Converting QA to statements\"):\n fulltext = sample['fulltext']\n if fulltext not in fulltext_processed.keys():\n generated_questions = sample['generated_question']\n generated_answers = sample['answer']\n sample['candidate_claims'] = []\n for questions, answers in zip(generated_questions, generated_answers):\n candidate_corrections_list = []\n qa_pair_processed = dict()\n for idx, answer in enumerate(answers):\n input_text = f\"{answer} \\\\n {questions[idx]}\"\n if input_text not in qa_pair_processed.keys():\n input_ids = tokenizer(\n input_text,\n return_tensors=\"pt\",\n padding='longest',\n truncation=True,\n max_length=max_length_tokenizer\n ).input_ids.to(model.device)\n generated_ids = model.generate(\n input_ids,\n max_length=max_length_gen,\n do_sample=False,\n early_stopping=True\n )\n candidate_corrections = tokenizer.batch_decode(\n generated_ids,\n skip_special_tokens=True\n )\n candidate_corrections_list.append(candidate_corrections)\n qa_pair_processed[input_text] = candidate_corrections\n else:\n print(\"Load the processed qa pair\")\n candidate_corrections_list.append(qa_pair_processed[input_text])\n sample['candidate_claims'].append(candidate_corrections_list)\n fulltext_processed[fulltext] = sample['candidate_claims']\n else:\n print(\"Load the processed fulltext\")\n sample['candidate_claims'] = fulltext_processed[fulltext]\n return samples\n\ndef gen_highquality_context(samples):\n simcse_model = SimCSE(\"princeton-nlp/sup-simcse-roberta-large\")\n cw_labels = ['Non-Factual Statement(NFS)', 'Unimportant Factual Statement(UFS)', 'Check-worthy Factual Statement(CFS)']\n cw_tokenizer = AutoTokenizer.from_pretrained(\"whispAI/ClaimBuster-DeBERTaV2\", use_auth_token=True)\n cw_model = AutoModelForSequenceClassification.from_pretrained(\"whispAI/ClaimBuster-DeBERTaV2\", use_auth_token=True)\n class RobertaForSequenceClassification(nn.Module):\n def __init__(self, tagset_size):\n super(RobertaForSequenceClassification, self).__init__()\n self.tagset_size = tagset_size\n self.roberta_single = RobertaModel.from_pretrained(pretrain_model_dir)\n self.single_hidden2tag = RobertaClassificationHead(bert_hidden_dim, tagset_size)\n def forward(self, input_ids, input_mask):\n outputs_single = self.roberta_single(input_ids, input_mask, None)\n hidden_states_single = outputs_single[1]\n score_single = self.single_hidden2tag(hidden_states_single)\n return score_single\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n bert_hidden_dim = 1024\n pretrain_model_dir = 'roberta-large'\n label_list = [\"entailment\", \"not_entailment\"]\n num_labels = len(label_list)\n class RobertaClassificationHead(nn.Module):\n def __init__(self, bert_hidden_dim, num_labels):\n super(RobertaClassificationHead, self).__init__()\n self.dense = nn.Linear(bert_hidden_dim, bert_hidden_dim)\n self.dropout = nn.Dropout(0.1)\n self.out_proj = nn.Linear(bert_hidden_dim, num_labels)\n def forward(self, features):\n x = features\n x = self.dropout(x)\n x = self.dense(x)\n x = torch.tanh(x)\n x = self.dropout(x)\n x = self.out_proj(x)\n return x\n model = RobertaForSequenceClassification(num_labels).to(device)\n tokenizer = AutoTokenizer.from_pretrained(pretrain_model_dir)\n checkpoint = torch.load('docnli_model/DocNLI.pretrained.RoBERTA.model.pt')\n model.load_state_dict(checkpoint, strict=False)\n def entailment_score(text1, text2):\n encoded_ctx = tokenizer.encode(text1)[:-1]\n encoded_correction = tokenizer.encode(text2)[1:]\n encoded_ctx_truncated = encoded_ctx[:512 - 1 - len(encoded_correction)]\n input_ids = torch.LongTensor(encoded_ctx_truncated + [tokenizer.sep_token_id] + encoded_correction).unsqueeze(\n 0).to(device)\n attention_mask = torch.LongTensor([1] * len(input_ids)).unsqueeze(0).to(device)\n inputs = {'input_ids': input_ids, 'input_mask': attention_mask}\n with torch.no_grad():\n model.eval()\n logits = model(**inputs)\n probs = torch.nn.Softmax(dim=1)(logits)\n correct_prob = probs[0][0].item()\n return correct_prob\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Running DocNLI\"):\n fulltext = sample['fulltext']\n cand_sents = [i for i in sample['sents_order_by_bertsum']]\n if fulltext not in fulltext_processed.keys():\n sample['claim_rank_by_entail_score'] = []\n sample['claim_rank_by_simcse_score'] = []\n sample['final_claims_cw'] = []\n sample['final_claims'] = []\n for idx, gen_claim in enumerate(sample['candidate_claims']):\n cand_claim_by_entail = []\n cand_claim_by_simcse = []\n cand_claim_rmv_dup = []\n if gen_claim:\n gen_claim_entail_scores = []\n gen_claim_simcse_scores = []\n claim_processed = dict()\n for idy, _claim in enumerate(gen_claim):\n if _claim[0] not in claim_processed.keys():\n correct_prob = entailment_score(sample['sentences'][cand_sents[idx]], _claim[0])\n gen_claim_entail_scores.append(correct_prob)\n claim_processed[_claim[0]] = correct_prob\n else:\n print(\"load the processed claim\")\n gen_claim_entail_scores.append(claim_processed[_claim[0]])\n topk_claims_id = range(len(gen_claim_entail_scores))\n if not topk_claims_id:\n topk_claims_id = np.argsort(-np.array(gen_claim_entail_scores)).tolist()[:5]\n for idz, _claim in enumerate(gen_claim):\n if idz in topk_claims_id:\n if [_claim[0], gen_claim_entail_scores[idz]] not in cand_claim_by_entail:\n cand_claim_by_entail.append([_claim[0], gen_claim_entail_scores[idz]])\n cand_claim_by_entail = sorted(cand_claim_by_entail, key=lambda x: x[1], reverse=True)\n if cand_claim_by_entail:\n cand_claim_by_entail_list = [c for c, s in cand_claim_by_entail]\n simcse_score = (simcse_model.similarity(sample['sentences'][cand_sents[idx]],\n cand_claim_by_entail_list)).ravel().tolist()\n gen_claim_simcse_scores.extend(simcse_score)\n cand_claim_by_simcse_id = np.argsort(-np.array(gen_claim_simcse_scores)).tolist()\n cand_claim_by_simcse.extend(\n [cand_claim_by_entail_list[i], gen_claim_simcse_scores[i]] for i in cand_claim_by_simcse_id)\n sample['claim_rank_by_entail_score'].append(cand_claim_by_entail)\n sample['claim_rank_by_simcse_score'].append(cand_claim_by_simcse)\n cand_claim_rmv_dup.extend([c for c, s in cand_claim_by_simcse])\n filter_by_entail_ids = []\n for i in reversed(range(len(cand_claim_rmv_dup))):\n for j in reversed(range(i)):\n if i not in filter_by_entail_ids:\n entail_prob = entailment_score(cand_claim_rmv_dup[j], cand_claim_rmv_dup[i])\n if entail_prob > 0.9:\n filter_by_entail_ids.append(i)\n for i in filter_by_entail_ids:\n del cand_claim_rmv_dup[i]\n simcse_sents = simcse_model.similarity(cand_claim_rmv_dup, cand_claim_rmv_dup)\n filter_by_simcse_ids = []\n for i in reversed(range(len(cand_claim_rmv_dup))):\n for j in reversed(range(i)):\n if i not in filter_by_simcse_ids:\n if simcse_sents[i][j] > 0.85:\n filter_by_simcse_ids.append(i)\n for i in filter_by_simcse_ids:\n del cand_claim_rmv_dup[i]\n cand_claim_with_check_worthy = []\n cand_claim_final = []\n for claim_text in cand_claim_rmv_dup:\n cw_sent_inputs = cw_tokenizer(claim_text, return_tensors=\"pt\")\n cw_sent_outputs = cw_model(**cw_sent_inputs)\n sent_logits = cw_sent_outputs.logits.tolist()[0]\n cw_sent_class = np.argmax(sent_logits)\n sent_label = cw_labels[int(cw_sent_class)]\n cand_claim_with_check_worthy.append([claim_text, sent_label, sent_logits])\n if sent_label in ['Unimportant Factual Statement(UFS)', 'Check-worthy Factual Statement(CFS)']:\n cand_claim_final.append([claim_text])\n sample['final_claims_cw'].append(cand_claim_with_check_worthy)\n sample['final_claims'].append(cand_claim_final)\n else:\n sample['claim_rank_by_entail_score'].append(cand_claim_by_entail)\n sample['claim_rank_by_simcse_score'].append(cand_claim_by_simcse)\n sample['final_claims_cw'].append([])\n sample['final_claims'].append([])\n fulltext_processed[fulltext] = [sample['claim_rank_by_entail_score'],\n sample['claim_rank_by_simcse_score'], sample['final_claims_cw'],\n sample['final_claims']]\n else:\n print(\"Load the processed fulltext\")\n sample['claim_rank_by_entail_score'], sample['claim_rank_by_simcse_score'], sample['final_claims_cw'], sample['final_claims'] = fulltext_processed[fulltext]\n return samples\n\ndef main(args):\n import os, random\n os.environ['PYTHONHASHSEED'] = str(42)\n os.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\n np.random.seed(42)\n if torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\n torch.use_deterministic_algorithms(True)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n random.seed(42)\n torch.cuda.synchronize()\n data_path = \"all_data\"\n all_avail_url_files = \"{}/1_all_available_url_fulltext.json\".format(data_path)\n if not os.path.exists(all_avail_url_files):\n print(\"***** run python 1_extract_texts_from_url.py *****\")\n ranked_sentence_file = \"{}/2_sent_ranked_by_bertsum.json\".format(data_path)\n samples = json.load(open(all_avail_url_files, 'r'))\n if args.TestCode:\n samples = samples[:10]\n configs = dict()\n configs['task'] = 'ext'\n configs['mode'] = 'test_text'\n configs['test_from'] = 'presumm/save_model/bertext_cnndm_transformer.pt'\n configs['text_src'] = 'all_data/1_all_available_url_fulltext.json'\n configs['result_path'] = 'presumm/results/ootb_output'\n configs['alpha'] = 0.95\n configs['log_file'] = 'presumm/logs/test.log'\n configs['visible_gpus'] = '0'\n ranked_samples = sentence_ranking_by_BertSum(samples, configs)\n cand_ans_extraction_file = \"{}/3_generated_candidates.jsonl\".format(data_path)\n cand_ans_samples = candidate_answer_extraction(ranked_samples)\n gen_question_file = \"{}/4_generated_questions.jsonl\".format(data_path)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n tokenizer = AutoTokenizer.from_pretrained('t5-base')\n model = AutoModelForSeq2SeqLM.from_pretrained('Salesforce/mixqg-base').to(device)\n model.eval()\n batch_size = 10\n gen_que_samples = question_generation(cand_ans_samples, tokenizer, model, batch_size)\n gen_answer_file = \"{}/5_generated_answers.jsonl\".format(data_path)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model_name = 'allenai/unifiedqa-v2-t5-base-1251000'\n tokenizer = AutoTokenizer.from_pretrained('t5-base')\n model = T5ForConditionalGeneration.from_pretrained(model_name).to(device)\n model.eval()\n gen_answer_samples = qa_generation(gen_que_samples, model, tokenizer)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n pretrain_model_path = \"khhuang/zerofec-qa2claim-t5-base\"\n tokenizer = AutoTokenizer.from_pretrained('t5-base')\n model = AutoModelForSeq2SeqLM.from_pretrained(pretrain_model_path).to(device)\n model.eval()\n gen_context_file = \"{}/6_generated_context.jsonl\".format(data_path)\n gen_context_samples = qa_to_context(gen_answer_samples, model, tokenizer)\n gen_context_file = \"{}/7_highquality_context.jsonl\".format(data_path)\n gen_highcontext_samples = gen_highquality_context(gen_context_samples)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n main(args)" }, { "task_id": 2, "indent": 1, "script": "\npython 2_context_generation.py\n", "latex_code": "\n\\paragraph{Question Answering.} After question generation, our next step is to clarify ambiguous information units by answering corresponding questions with the document $\\mathcal{D}$. Specifically, following \\citet{schlichtkrull2023averitec}, %to maintain consistency with AVeriTeC,\nwe first use BM25~\\cite{robertson2009probabilistic} to retrieve evidence $E$ related to the question $q^j_i$ from $\\mathcal{D}$, and then answer $q^j_i$ with $E$ using an existing QA model~\\cite{khashabi2022unifiedqa} trained on twenty datasets that can answer different types of questions.\n% using an existing QA model~\\cite{khashabi2022unifiedqa}:\n\\begin{eqnarray}\n\\begin{array}{c}\n\\begin{aligned}\nE &= {\\rm BM25}(\\mathcal{D},q^j_i) \\\\\na^j_i & = {\\rm QA}(E,q^j_i)\n\\end{aligned}\n\\end{array}\n\\label{eq3_2_2}\n\\end{eqnarray}\nwhere $a^j_i$ denotes a more complete information unit corresponding to ${u}^i_j$, \\eg a complete coreference. We denote all question-answer pairs of the $i$-th sentence as $P_i=\\{(q^1_i, a^1_i), (q^2_i, a^2_i), ..., (q^m_i, a^m_i)\\}$.\n", "completion_path": "./2_context_generation.py", "namespace": "2_context_generation.qa_generation", "type": "function", "signature_position": [ 123, 123 ], "body_position": [ 124, 169 ], "ReferenceCode_With_Comments": "\nfulltext_processed = dict()\nfor sample in tqdm(samples, desc=\"Generating Answers\"):\n\n fulltext = sample['fulltext']\n cand_sents = [i for i in sample['sents_order_by_bertsum']]\n\n # -----------------------------------------------------------------------\n # Snippet 1: We check if the current 'fulltext' has been processed before. \n # If not, we create a new list 'answer' to store answers for each question. \n # This aligns with the LaTeX approach of generating a\u1d62\u2c7c from each question q\u1d62\u2c7c.\n # -----------------------------------------------------------------------\n # [Begin Snippet 1]\n if fulltext not in fulltext_processed.keys():\n sample['answer'] = []\n\n for idx, questions in enumerate(sample['generated_question']):\n print(\"id={}/{}\".format(idx, len(sample['generated_question'])))\n\n if len(fulltext) <= 400:\n context = fulltext\n else:\n if cand_sents[idx] >= 10:\n context = sample['sentences'][\n (cand_sents[idx] - 10):(cand_sents[idx] + 10)\n ]\n else:\n context = sample['sentences'][0:(cand_sents[idx] + 10)]\n # [End Snippet 1]\n\n # -------------------------------------------------------------------\n # Snippet 2: For each question q\u1d62\u2c7c, we pass (q\u1d62\u2c7c + context) to the \n # QA model, which approximates the step a\u1d62\u2c7c = QA(E, q\u1d62\u2c7c). \n # We store answers in current_answers, caching repeated questions locally.\n # -------------------------------------------------------------------\n # [Begin Snippet 2]\n current_answers = []\n question_processed = dict() \n for idy, question in enumerate(questions):\n if question not in question_processed.keys():\n input_ids = tokenizer.encode(\n f\"{question} \\n {context}\",\n return_tensors='pt'\n ).to(model.device)\n\n with torch.no_grad():\n outputs = model.generate(\n input_ids,\n num_beams=4,\n do_sample=False\n )\n predict_answer_tokens_string = tokenizer.batch_decode(\n outputs,\n skip_special_tokens=True\n )[0]\n\n current_answers.append(predict_answer_tokens_string.strip())\n question_processed[question] = predict_answer_tokens_string.strip()\n else:\n print(\"Load the processed question\")\n current_answers.append(question_processed[question])\n\n sample['answer'].append(current_answers)\n # [End Snippet 2]\n\n fulltext_processed[fulltext] = sample['answer']\n\n else:\n print(\"Load the processed fulltext\")\n sample['answer'] = fulltext_processed[fulltext]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Returns the updated list of samples, each containing a new key 'answer'.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nreturn samples\n# [End Snippet 3]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The generation adopts the greedy decoding strategy.\n - The LaTeX description does not specify how the document \\(\\mathcal{D}\\) is segmented or preprocessed before applying BM25 retrieval. In the reference Python code (Snippet 2), the workflow involves checking the length of the `fulltext` (\u2264 400 characters) to decide whether to use it directly as the context or to extract a window of sentences around a candidate sentence indexed by `cand_sents` (e.g., `sample['sentences'][(cand_sents[idx] - 10):(cand_sents[idx] + 10)]`). This preprocessing step determines the evidence \\(E\\) by dynamically selecting a relevant subset of the document based on sentence indices pre-selected by BertSum, ensuring the QA model receives a focused yet sufficiently broad context.\n - The LaTeX omits any mention of caching mechanisms for efficiency and consistency. In the reference code (Snippets 3 and 4), the workflow includes two caching strategies: (1) a local dictionary (`question_processed`) stores answers for repeated questions within the same sample, avoiding redundant model inference, and (2) a global dictionary (`fulltext_processed`) caches answers for identical `fulltext` inputs across samples, reusing results instead of recomputing them.\n - The LaTeX description indicates answering a question using a QA model without specifying the exact prompt format. In practice, the reference Python code concatenates questions and contexts with a newline (`{question} \\n {context}`)\n \n Mismatched Details:\n - None\n\n\n", "Missing_details": [ "\n- The generation adopts the greedy decoding strategy.\n", "\n- The LaTeX description does not specify how the document \\(\\mathcal{D}\\) is segmented or preprocessed before applying BM25 retrieval. In the reference Python code (Snippet 2), the workflow involves checking the length of the `fulltext` (\u2264 400 characters) to decide whether to use it directly as the context or to extract a window of sentences around a candidate sentence indexed by `cand_sents` (e.g., `sample['sentences'][(cand_sents[idx] - 10):(cand_sents[idx] + 10)]`). This preprocessing step determines the evidence \\(E\\) by dynamically selecting a relevant subset of the document based on sentence indices pre-selected by BertSum, ensuring the QA model receives a focused yet sufficiently broad context.\n", " \n- The LaTeX omits any mention of caching mechanisms for efficiency and consistency. In the reference code (Snippets 3 and 4), the workflow includes two caching strategies: (1) a local dictionary (`question_processed`) stores answers for repeated questions within the same sample, avoiding redundant model inference, and (2) a global dictionary (`fulltext_processed`) caches answers for identical `fulltext` inputs across samples, reusing results instead of recomputing them.\n", " \n- The LaTeX description indicates answering a question using a QA model without specifying the exact prompt format. In practice, the reference Python code concatenates questions and contexts with a newline (`{question} \\n {context}`)\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - samples (list[dict]): Contains the data from which we want to extract sentences. A list where each element is a dictionary representing a document. The keys in the dictionary include:\n - 'claim' (String): The statement under investigation (e.g., that Kamala Harris called young voters \"stupid\").\n - 'label' (String): The verification outcome assigned to the claim, here labeled as \"Supported.\"\n - 'questions' (List[Dict]): Holds question-and-answer pairs or additional metadata relevant to the fact-check process.\n - 'fulltext' (String): The complete text of the article or document to be summarized.\n - 'sents_id_selected_by_bertsum' (List[Int]): Indices of the sentences selected by BertSum based on their scores.\n - 'sents_selected_by_bertsum' (List[String]): The actual text of the sentences chosen by BertSum.\n - 'sents_with_scores_by_bertsum' (List[Float]): Confidence scores assigned by BertSum to the selected sentences.\n - 'sents_order_by_bertsum' (List[Int]): The ranking order of the selected sentences by score.\n - 'sent_texts_order_by_bertsum' (List[String]): The sentences re-ordered according to their rank.\n - 'sentences' (List[String]): The full text split into tokenized sentences.\n - 'candidate_answers' (List[List[String]]): Candidate answers extracted from the selected sentences.\n - 'generated_question' (List[List[String]]): corresponding to the list of questions generated by the QG model for each candidate answer in 'candidate_answers'.\n - model (transformers.T5ForConditionalGeneration):\n A pre-trained seq2seq model used for question generation.\n - tokenizer (transformers.PreTrainedTokenizer):\n A tokenizer from Hugging Face Transformers configured for the question generation model.\n", "Arguments_list": [ { "name": "samples", "string": "\n- samples (list[dict]): Contains the data from which we want to extract sentences. A list where each element is a dictionary representing a document. The keys in the dictionary include:\n - 'claim' (String): The statement under investigation (e.g., that Kamala Harris called young voters \"stupid\").\n - 'label' (String): The verification outcome assigned to the claim, here labeled as \"Supported.\"\n - 'questions' (List[Dict]): Holds question-and-answer pairs or additional metadata relevant to the fact-check process.\n - 'fulltext' (String): The complete text of the article or document to be summarized.\n - 'sents_id_selected_by_bertsum' (List[Int]): Indices of the sentences selected by BertSum based on their scores.\n - 'sents_selected_by_bertsum' (List[String]): The actual text of the sentences chosen by BertSum.\n - 'sents_with_scores_by_bertsum' (List[Float]): Confidence scores assigned by BertSum to the selected sentences.\n - 'sents_order_by_bertsum' (List[Int]): The ranking order of the selected sentences by score.\n - 'sent_texts_order_by_bertsum' (List[String]): The sentences re-ordered according to their rank.\n - 'sentences' (List[String]): The full text split into tokenized sentences.\n - 'candidate_answers' (List[List[String]]): Candidate answers extracted from the selected sentences.\n - 'generated_question' (List[List[String]]): corresponding to the list of questions generated by the QG model for each candidate answer in 'candidate_answers'.\n", "dependency": null }, { "name": "model", "string": "\n- model (transformers.T5ForConditionalGeneration):\n A pre-trained seq2seq model used for question generation.\n", "dependency": "transformers.T5ForConditionalGeneration" }, { "name": "tokenizer", "string": "\n- tokenizer (transformers.PreTrainedTokenizer):\n A tokenizer from Hugging Face Transformers configured for the question generation model.\n", "dependency": "transformers.PreTrainedTokenizer" } ] }, "dependency": { "string": "\nDependencies:\n Intra-File Dependencies: \n - None\n\n Cross-File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.no_grad\n", "list": [ "torch.no_grad" ] }, "Return": { "Return_String": "\nOutput Variables:\n - samples (list of dict): Returns the original list of dictionaries with additional keys containing the generated answers for each question. The updated key is:\n - 'answer' (List[List[String]]): Nested list of answers corresponding to the generated questions ('generated_question' in each sample within samples).\n", "Return_list": [ { "name": "samples", "string": "\n- samples (list of dict): Returns the original list of dictionaries with additional keys containing the generated answers for each question. The updated key is:\n - 'answer' (List[List[String]]): Nested list of answers corresponding to the generated questions ('generated_question' in each sample within samples).\n" } ] }, "ori_python_file": "import os\nimport json\nimport spacy\nimport stanza, argparse\nimport numpy as np\nfrom tqdm import tqdm\nfrom nltk.translate.chrf_score import sentence_chrf\nimport sys\nsys.path.append('presumm')\nfrom presumm import train\nfrom nltk.tokenize import sent_tokenize\nimport torch\nimport torch.nn as nn\nfrom simcse import SimCSE\nfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLM, T5ForConditionalGeneration\nfrom transformers import AutoModelForSequenceClassification\nfrom transformers.models.roberta.modeling_roberta import RobertaModel\nimport pickle\n\ndef sentence_ranking_by_BertSum(samples, configs):\n sent_with_score = train.main(configs)\n for idx, sample in enumerate(samples):\n fulltext = sample['fulltext']\n if fulltext[0] in [\"\u201c\", \"'\", \"\u201d\"] and fulltext[-1] in [\"\u201c\", \"'\", \"\u201d\"]:\n fulltext = fulltext[1:-1]\n sentences = sent_tokenize(fulltext)\n sample['sents_id_selected_by_bertsum'] = sent_with_score[idx][2]\n sample['sents_selected_by_bertsum'] = sent_with_score[idx][0]\n sample['sents_with_scores_by_bertsum'] = sent_with_score[idx][1].tolist()\n sample['sents_order_by_bertsum'] = sent_with_score[idx][4]\n sample['sent_texts_order_by_bertsum'] = sent_with_score[idx][5]\n sample['sentences'] = sentences\n return samples\n\ndef get_phrases(tree, label):\n if tree.is_leaf():\n return []\n results = []\n for child in tree.children:\n results += get_phrases(child, label)\n if tree.label == label:\n return [' '.join(tree.leaf_labels())] + results\n else:\n return results\n\ndef candidate_answer_extraction(samples):\n nlp = spacy.load('en_core_web_lg')\n stanza_nlp = stanza.Pipeline(lang='en', processors='tokenize,pos,constituency')\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Candidate Generation\"):\n fulltext = sample['fulltext']\n chrf_all_sents = [sentence_chrf(sample['claim'].split(), sent.split()) for sent in sample['sentences']]\n top3_sent_id_in_all_sents = np.argsort(-np.array(chrf_all_sents)).tolist()[:3]\n top3_chrf_in_all_sents = [chrf_all_sents[i] for i in top3_sent_id_in_all_sents]\n sample['top3_sent_in_all_sents'] = [top3_sent_id_in_all_sents, top3_chrf_in_all_sents]\n chrf_ext_sents = [sentence_chrf(sample['claim'].split(), sample['sentences'][_id].split()) for _id in\n sample['sents_order_by_bertsum']]\n order_top3_sent_id_in_ext_sents = np.argsort(-np.array(chrf_ext_sents)).tolist()[:3]\n top3_sent_id_in_ext_sents = [sample['sents_order_by_bertsum'][j] for j in order_top3_sent_id_in_ext_sents]\n top3_chrf_in_ext_sents = [chrf_ext_sents[i] for i in order_top3_sent_id_in_ext_sents]\n sample['top3_sent_in_ext_sents'] = [top3_sent_id_in_ext_sents, top3_chrf_in_ext_sents]\n if fulltext not in fulltext_processed.keys():\n sample['candidate_answers'] = []\n central_sents_sel_by_bertsum = [i for i in sample['sents_order_by_bertsum']]\n candidate_central_sentences = [sample['sentences'][i] for i in central_sents_sel_by_bertsum]\n candidate_answers = []\n for sent in candidate_central_sentences:\n if sent:\n candidate_answers_list = []\n doc = nlp(sent)\n stanza_doc = stanza_nlp(sent)\n ents = [ent.text for sent in doc.sents for ent in sent.noun_chunks]\n ents += [ent.text for sent in doc.sents for ent in sent.ents]\n ents += [phrase for sent in stanza_doc.sentences for phrase in get_phrases(sent.constituency, 'NP')]\n ents += [phrase for sent in stanza_doc.sentences for phrase in get_phrases(sent.constituency, 'VP')]\n ents += [word.text for sent in stanza_doc.sentences for word in sent.words if\n word.upos in ['VERB', 'ADV', 'ADJ', 'NOUN']]\n negations = [word for word in ['not', 'never'] if word in sample['fulltext']]\n candidate_answers_list.extend(sorted(set(ents + negations)))\n candidate_answers.append(candidate_answers_list)\n sample['candidate_answers'].extend(candidate_answers)\n fulltext_processed[fulltext] = sample['candidate_answers']\n else:\n print(\"Load the processed fulltext\")\n sample['candidate_answers'] = fulltext_processed[fulltext]\n return samples\n\ndef question_generation(samples, tokenizer, model, batch_size, max_length_gen=32, max_length_tokenizer=1024):\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Generating Questions\"):\n fulltext = sample['fulltext']\n if fulltext not in fulltext_processed.keys():\n sample['generated_question'] = []\n cand_sents = [i for i in sample['sents_order_by_bertsum']]\n assert len(cand_sents) == len(sample['candidate_answers'])\n for idx in range(len(sample['candidate_answers'])):\n texts = []\n _sentence = sample['sentences'][cand_sents[idx]]\n _candidate_ansewrs = sample['candidate_answers'][idx]\n for cand_ans in _candidate_ansewrs:\n texts.append(f\"{_sentence} \\\\n {cand_ans}\")\n gen_question = []\n if texts:\n for idy in range(0, len(texts), batch_size):\n input_ids = tokenizer(\n texts[idy:idy + batch_size],\n return_tensors=\"pt\",\n padding='longest',\n truncation=True,\n max_length=max_length_tokenizer\n ).input_ids.to(model.device)\n generated_ids = model.generate(input_ids, max_length=max_length_gen, do_sample=False)\n output = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)\n gen_question.extend(output)\n sample['generated_question'].append(gen_question)\n else:\n sample['generated_question'].append(gen_question)\n fulltext_processed[fulltext] = sample['generated_question']\n else:\n sample['generated_question'] = fulltext_processed[fulltext]\n return samples\n\ndef qa_generation(samples, model, tokenizer):\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Generating Answers\"):\n fulltext = sample['fulltext']\n cand_sents = [i for i in sample['sents_order_by_bertsum']]\n if fulltext not in fulltext_processed.keys():\n sample['answer'] = []\n for idx, questions in enumerate(sample['generated_question']):\n print(\"id={}/{}\".format(idx, len(sample['generated_question'])))\n if len(fulltext) <= 400:\n context = fulltext\n else:\n if cand_sents[idx] >= 10:\n context = sample['sentences'][\n (cand_sents[idx] - 10):(cand_sents[idx] + 10)\n ]\n else:\n context = sample['sentences'][0:(cand_sents[idx] + 10)]\n current_answers = []\n question_processed = dict()\n for idy, question in enumerate(questions):\n if question not in question_processed.keys():\n input_ids = tokenizer.encode(\n f\"{question} \\n {context}\",\n return_tensors='pt'\n ).to(model.device)\n with torch.no_grad():\n outputs = model.generate(\n input_ids,\n num_beams=4,\n do_sample=False\n )\n predict_answer_tokens_string = tokenizer.batch_decode(\n outputs,\n skip_special_tokens=True\n )[0]\n current_answers.append(predict_answer_tokens_string.strip())\n question_processed[question] = predict_answer_tokens_string.strip()\n else:\n print(\"Load the processed question\")\n current_answers.append(question_processed[question])\n sample['answer'].append(current_answers)\n fulltext_processed[fulltext] = sample['answer']\n else:\n print(\"Load the processed fulltext\")\n sample['answer'] = fulltext_processed[fulltext]\n return samples\n\ndef qa_to_context(samples, model, tokenizer, max_length_tokenizer=512, max_length_gen=64):\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Converting QA to statements\"):\n fulltext = sample['fulltext']\n if fulltext not in fulltext_processed.keys():\n generated_questions = sample['generated_question']\n generated_answers = sample['answer']\n sample['candidate_claims'] = []\n for questions, answers in zip(generated_questions, generated_answers):\n candidate_corrections_list = []\n qa_pair_processed = dict()\n for idx, answer in enumerate(answers):\n input_text = f\"{answer} \\\\n {questions[idx]}\"\n if input_text not in qa_pair_processed.keys():\n input_ids = tokenizer(\n input_text,\n return_tensors=\"pt\",\n padding='longest',\n truncation=True,\n max_length=max_length_tokenizer\n ).input_ids.to(model.device)\n generated_ids = model.generate(\n input_ids,\n max_length=max_length_gen,\n do_sample=False,\n early_stopping=True\n )\n candidate_corrections = tokenizer.batch_decode(\n generated_ids,\n skip_special_tokens=True\n )\n candidate_corrections_list.append(candidate_corrections)\n qa_pair_processed[input_text] = candidate_corrections\n else:\n print(\"Load the processed qa pair\")\n candidate_corrections_list.append(qa_pair_processed[input_text])\n sample['candidate_claims'].append(candidate_corrections_list)\n fulltext_processed[fulltext] = sample['candidate_claims']\n else:\n print(\"Load the processed fulltext\")\n sample['candidate_claims'] = fulltext_processed[fulltext]\n return samples\n\ndef gen_highquality_context(samples):\n simcse_model = SimCSE(\"princeton-nlp/sup-simcse-roberta-large\")\n cw_labels = ['Non-Factual Statement(NFS)', 'Unimportant Factual Statement(UFS)', 'Check-worthy Factual Statement(CFS)']\n cw_tokenizer = AutoTokenizer.from_pretrained(\"whispAI/ClaimBuster-DeBERTaV2\", use_auth_token=True)\n cw_model = AutoModelForSequenceClassification.from_pretrained(\"whispAI/ClaimBuster-DeBERTaV2\", use_auth_token=True)\n class RobertaForSequenceClassification(nn.Module):\n def __init__(self, tagset_size):\n super(RobertaForSequenceClassification, self).__init__()\n self.tagset_size = tagset_size\n self.roberta_single = RobertaModel.from_pretrained(pretrain_model_dir)\n self.single_hidden2tag = RobertaClassificationHead(bert_hidden_dim, tagset_size)\n def forward(self, input_ids, input_mask):\n outputs_single = self.roberta_single(input_ids, input_mask, None)\n hidden_states_single = outputs_single[1]\n score_single = self.single_hidden2tag(hidden_states_single)\n return score_single\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n bert_hidden_dim = 1024\n pretrain_model_dir = 'roberta-large'\n label_list = [\"entailment\", \"not_entailment\"]\n num_labels = len(label_list)\n class RobertaClassificationHead(nn.Module):\n def __init__(self, bert_hidden_dim, num_labels):\n super(RobertaClassificationHead, self).__init__()\n self.dense = nn.Linear(bert_hidden_dim, bert_hidden_dim)\n self.dropout = nn.Dropout(0.1)\n self.out_proj = nn.Linear(bert_hidden_dim, num_labels)\n def forward(self, features):\n x = features\n x = self.dropout(x)\n x = self.dense(x)\n x = torch.tanh(x)\n x = self.dropout(x)\n x = self.out_proj(x)\n return x\n model = RobertaForSequenceClassification(num_labels).to(device)\n tokenizer = AutoTokenizer.from_pretrained(pretrain_model_dir)\n checkpoint = torch.load('docnli_model/DocNLI.pretrained.RoBERTA.model.pt')\n model.load_state_dict(checkpoint, strict=False)\n def entailment_score(text1, text2):\n encoded_ctx = tokenizer.encode(text1)[:-1]\n encoded_correction = tokenizer.encode(text2)[1:]\n encoded_ctx_truncated = encoded_ctx[:512 - 1 - len(encoded_correction)]\n input_ids = torch.LongTensor(encoded_ctx_truncated + [tokenizer.sep_token_id] + encoded_correction).unsqueeze(\n 0).to(device)\n attention_mask = torch.LongTensor([1] * len(input_ids)).unsqueeze(0).to(device)\n inputs = {'input_ids': input_ids, 'input_mask': attention_mask}\n with torch.no_grad():\n model.eval()\n logits = model(**inputs)\n probs = torch.nn.Softmax(dim=1)(logits)\n correct_prob = probs[0][0].item()\n return correct_prob\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Running DocNLI\"):\n fulltext = sample['fulltext']\n cand_sents = [i for i in sample['sents_order_by_bertsum']]\n if fulltext not in fulltext_processed.keys():\n sample['claim_rank_by_entail_score'] = []\n sample['claim_rank_by_simcse_score'] = []\n sample['final_claims_cw'] = []\n sample['final_claims'] = []\n for idx, gen_claim in enumerate(sample['candidate_claims']):\n cand_claim_by_entail = []\n cand_claim_by_simcse = []\n cand_claim_rmv_dup = []\n if gen_claim:\n gen_claim_entail_scores = []\n gen_claim_simcse_scores = []\n claim_processed = dict()\n for idy, _claim in enumerate(gen_claim):\n if _claim[0] not in claim_processed.keys():\n correct_prob = entailment_score(sample['sentences'][cand_sents[idx]], _claim[0])\n gen_claim_entail_scores.append(correct_prob)\n claim_processed[_claim[0]] = correct_prob\n else:\n print(\"load the processed claim\")\n gen_claim_entail_scores.append(claim_processed[_claim[0]])\n topk_claims_id = range(len(gen_claim_entail_scores))\n if not topk_claims_id:\n topk_claims_id = np.argsort(-np.array(gen_claim_entail_scores)).tolist()[:5]\n for idz, _claim in enumerate(gen_claim):\n if idz in topk_claims_id:\n if [_claim[0], gen_claim_entail_scores[idz]] not in cand_claim_by_entail:\n cand_claim_by_entail.append([_claim[0], gen_claim_entail_scores[idz]])\n cand_claim_by_entail = sorted(cand_claim_by_entail, key=lambda x: x[1], reverse=True)\n if cand_claim_by_entail:\n cand_claim_by_entail_list = [c for c, s in cand_claim_by_entail]\n simcse_score = (simcse_model.similarity(sample['sentences'][cand_sents[idx]],\n cand_claim_by_entail_list)).ravel().tolist()\n gen_claim_simcse_scores.extend(simcse_score)\n cand_claim_by_simcse_id = np.argsort(-np.array(gen_claim_simcse_scores)).tolist()\n cand_claim_by_simcse.extend(\n [cand_claim_by_entail_list[i], gen_claim_simcse_scores[i]] for i in cand_claim_by_simcse_id)\n sample['claim_rank_by_entail_score'].append(cand_claim_by_entail)\n sample['claim_rank_by_simcse_score'].append(cand_claim_by_simcse)\n cand_claim_rmv_dup.extend([c for c, s in cand_claim_by_simcse])\n filter_by_entail_ids = []\n for i in reversed(range(len(cand_claim_rmv_dup))):\n for j in reversed(range(i)):\n if i not in filter_by_entail_ids:\n entail_prob = entailment_score(cand_claim_rmv_dup[j], cand_claim_rmv_dup[i])\n if entail_prob > 0.9:\n filter_by_entail_ids.append(i)\n for i in filter_by_entail_ids:\n del cand_claim_rmv_dup[i]\n simcse_sents = simcse_model.similarity(cand_claim_rmv_dup, cand_claim_rmv_dup)\n filter_by_simcse_ids = []\n for i in reversed(range(len(cand_claim_rmv_dup))):\n for j in reversed(range(i)):\n if i not in filter_by_simcse_ids:\n if simcse_sents[i][j] > 0.85:\n filter_by_simcse_ids.append(i)\n for i in filter_by_simcse_ids:\n del cand_claim_rmv_dup[i]\n cand_claim_with_check_worthy = []\n cand_claim_final = []\n for claim_text in cand_claim_rmv_dup:\n cw_sent_inputs = cw_tokenizer(claim_text, return_tensors=\"pt\")\n cw_sent_outputs = cw_model(**cw_sent_inputs)\n sent_logits = cw_sent_outputs.logits.tolist()[0]\n cw_sent_class = np.argmax(sent_logits)\n sent_label = cw_labels[int(cw_sent_class)]\n cand_claim_with_check_worthy.append([claim_text, sent_label, sent_logits])\n if sent_label in ['Unimportant Factual Statement(UFS)', 'Check-worthy Factual Statement(CFS)']:\n cand_claim_final.append([claim_text])\n sample['final_claims_cw'].append(cand_claim_with_check_worthy)\n sample['final_claims'].append(cand_claim_final)\n else:\n sample['claim_rank_by_entail_score'].append(cand_claim_by_entail)\n sample['claim_rank_by_simcse_score'].append(cand_claim_by_simcse)\n sample['final_claims_cw'].append([])\n sample['final_claims'].append([])\n fulltext_processed[fulltext] = [sample['claim_rank_by_entail_score'],\n sample['claim_rank_by_simcse_score'], sample['final_claims_cw'],\n sample['final_claims']]\n else:\n print(\"Load the processed fulltext\")\n sample['claim_rank_by_entail_score'], sample['claim_rank_by_simcse_score'], sample['final_claims_cw'], sample['final_claims'] = fulltext_processed[fulltext]\n return samples\n\ndef main(args):\n import os, random\n os.environ['PYTHONHASHSEED'] = str(42)\n os.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\n np.random.seed(42)\n if torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\n torch.use_deterministic_algorithms(True)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n random.seed(42)\n torch.cuda.synchronize()\n data_path = \"all_data\"\n all_avail_url_files = \"{}/1_all_available_url_fulltext.json\".format(data_path)\n if not os.path.exists(all_avail_url_files):\n print(\"***** run python 1_extract_texts_from_url.py *****\")\n ranked_sentence_file = \"{}/2_sent_ranked_by_bertsum.json\".format(data_path)\n samples = json.load(open(all_avail_url_files, 'r'))\n if args.TestCode:\n samples = samples[:10]\n configs = dict()\n configs['task'] = 'ext'\n configs['mode'] = 'test_text'\n configs['test_from'] = 'presumm/save_model/bertext_cnndm_transformer.pt'\n configs['text_src'] = 'all_data/1_all_available_url_fulltext.json'\n configs['result_path'] = 'presumm/results/ootb_output'\n configs['alpha'] = 0.95\n configs['log_file'] = 'presumm/logs/test.log'\n configs['visible_gpus'] = '0'\n ranked_samples = sentence_ranking_by_BertSum(samples, configs)\n cand_ans_extraction_file = \"{}/3_generated_candidates.jsonl\".format(data_path)\n cand_ans_samples = candidate_answer_extraction(ranked_samples)\n gen_question_file = \"{}/4_generated_questions.jsonl\".format(data_path)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n tokenizer = AutoTokenizer.from_pretrained('t5-base')\n model = AutoModelForSeq2SeqLM.from_pretrained('Salesforce/mixqg-base').to(device)\n model.eval()\n batch_size = 10\n gen_que_samples = question_generation(cand_ans_samples, tokenizer, model, batch_size)\n gen_answer_file = \"{}/5_generated_answers.jsonl\".format(data_path)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model_name = 'allenai/unifiedqa-v2-t5-base-1251000'\n tokenizer = AutoTokenizer.from_pretrained('t5-base')\n model = T5ForConditionalGeneration.from_pretrained(model_name).to(device)\n model.eval()\n gen_answer_samples = qa_generation(gen_que_samples, model, tokenizer)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n pretrain_model_path = \"khhuang/zerofec-qa2claim-t5-base\"\n tokenizer = AutoTokenizer.from_pretrained('t5-base')\n model = AutoModelForSeq2SeqLM.from_pretrained(pretrain_model_path).to(device)\n model.eval()\n gen_context_file = \"{}/6_generated_context.jsonl\".format(data_path)\n gen_context_samples = qa_to_context(gen_answer_samples, model, tokenizer)\n gen_context_file = \"{}/7_highquality_context.jsonl\".format(data_path)\n gen_highcontext_samples = gen_highquality_context(gen_context_samples)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n main(args)" }, { "task_id": 3, "indent": 1, "script": "\npython 2_context_generation.py\n", "latex_code": "\n\\paragraph{QA-to-Context Generation.} After question answering, we utilize a seq2seq generation model to convert QA pairs $P_i$ into the corresponding context $C'_i$. Specifically, we first concatenate the question $q^j_i$ and the answer $a^j_i$ as the input sequence, and then output a sentence using the BART model \\cite{lewis2019bart} finetuned on QA2D \\cite{demszky2018transforming}. QA2D is a dataset with over 500k NLI examples that contains various inference phenomena rarely seen in previous NLI datasets. More formally,\n\\begin{eqnarray}\n\\begin{array}{l}\n\\tilde{s}^j_i = {\\rm BART}(q^j_i, a^j_i)\n\\end{array}\n\\label{eq3_2_3}\n\\end{eqnarray}\nwhere $\\tilde{s}^j_i$ is a declarative sentence corresponding to the information unit ${u}^j_i$. Finally, all generated sentences are combined into high-quality context $C'_i=\\{\\tilde{s}^1_i, \\tilde{s}^2_i, ..., \\tilde{s}^m_i\\}$ corresponding to the information units ${U}_i$ in sentence $s'_i$, which is then used in the next decontextualisation step to enrich the ambiguous sentences.\n", "completion_path": "./2_context_generation.py", "namespace": "2_context_generation.qa_to_context", "type": "function", "signature_position": [ 171, 171 ], "body_position": [ 172, 212 ], "ReferenceCode_With_Comments": "\n\nfulltext_processed = dict()\n\nfor sample in tqdm(samples, desc=\"Converting QA to statements\"):\n fulltext = sample['fulltext']\n\n if fulltext not in fulltext_processed.keys():\n generated_questions = sample['generated_question']\n generated_answers = sample['answer']\n\n sample['candidate_claims'] = []\n\n for questions, answers in zip(generated_questions, generated_answers):\n candidate_corrections_list = []\n qa_pair_processed = dict()\n\n # ---------------------------------------------------------------------------\n # Snippet 1: For each QA pair, construct the input text by concatenating the answer and the corresponding question.\n # Note: The order here is \"answer \\n question\", which is a slight deviation from the LaTeX description.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 1]\n for idx, answer in enumerate(answers):\n input_text = f\"{answer} \\\\n {questions[idx]}\"\n if input_text not in qa_pair_processed.keys():\n input_ids = tokenizer(\n input_text,\n return_tensors=\"pt\",\n padding='longest',\n truncation=True,\n max_length=max_length_tokenizer\n ).input_ids.to(model.device)\n # [End Snippet 1]\n\n # ---------------------------------------------------------------------------\n # Snippet 2: Generate the output sequence (a declarative sentence) using the seq2seq model.\n # Then, decode the generated token IDs into a text string. This corresponds to the LaTeX process of\n # converting QA pairs into declarative sentences using BART(QA, q\u1d62\u02b2, a\u1d62\u02b2).\n # ---------------------------------------------------------------------------\n # [Begin Snippet 2]\n generated_ids = model.generate(\n input_ids,\n max_length=max_length_gen,\n do_sample=False,\n early_stopping=True\n )\n candidate_corrections = tokenizer.batch_decode(\n generated_ids, \n skip_special_tokens=True\n )\n # [End Snippet 2]\n\n candidate_corrections_list.append(candidate_corrections)\n qa_pair_processed[input_text] = candidate_corrections\n else:\n print(\"Load the processed qa pair\")\n candidate_corrections_list.append(qa_pair_processed[input_text])\n \n\n sample['candidate_claims'].append(candidate_corrections_list)\n\n fulltext_processed[fulltext] = sample['candidate_claims']\n else:\n print(\"Load the processed fulltext\")\n sample['candidate_claims'] = fulltext_processed[fulltext]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Return the updated list of samples, now containing the generated declarative sentences\n# (candidate_claims) for each QA pair.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nreturn samples\n# [End Snippet 3]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX description does not mention the caching mechanism for identical documents implemented in the reference Python code. In the reference code, a dictionary `fulltext_processed` is used to store the generated `candidate_claims` for each unique `fulltext`. The workflow begins by checking if the current sample\u2019s `fulltext` exists in `fulltext_processed`. If it does not, the code processes the QA pairs to generate declarative sentences and caches the result under `fulltext`. If it does, the cached `candidate_claims` are directly assigned to the sample.\n - The LaTeX description lacks any reference to caching QA pairs within a sample, as implemented in the reference code via the `qa_pair_processed` dictionary. In the reference workflow, for each set of QA pairs within a sample, the code constructs an `input_text` from the answer and question, then checks if this `input_text` has been processed before. If not, it tokenizes the input, generates a declarative sentence using the model, decodes it, and caches the result in `qa_pair_processed`. If the `input_text` is already cached, the cached output is reused.\n - The LaTeX description does not specify the generation hyperparameters used in the reference code\u2019s `model.generate` call, such as `do_sample=False` and `early_stopping=True`.\n - The LaTeX description does not specify tokenization details like the padding strategy used. However, the Python implementation explicitly sets `padding='longest'` during tokenization, ensuring uniform sequence lengths within batches.\n\n Mismatched Details:\n - The LaTeX description states that the input sequence to the BART model is formed by concatenating the question \\( q^j_i \\) and answer \\( a^j_i \\), but it does not specify the order or separator. The reference Python code constructs this input as `f\"{answer} \\n {questions[idx]}\"`, placing the answer first, followed by a newline (`\\n`), and then the question. This workflow involves concatenating the answer and question in this specific order, tokenizing the result, and feeding it to the model.\n", "Missing_details": [ "\n- The LaTeX description does not mention the caching mechanism for identical documents implemented in the reference Python code. In the reference code, a dictionary `fulltext_processed` is used to store the generated `candidate_claims` for each unique `fulltext`. The workflow begins by checking if the current sample\u2019s `fulltext` exists in `fulltext_processed`. If it does not, the code processes the QA pairs to generate declarative sentences and caches the result under `fulltext`. If it does, the cached `candidate_claims` are directly assigned to the sample.\n", "\n- The LaTeX description lacks any reference to caching QA pairs within a sample, as implemented in the reference code via the `qa_pair_processed` dictionary. In the reference workflow, for each set of QA pairs within a sample, the code constructs an `input_text` from the answer and question, then checks if this `input_text` has been processed before. If not, it tokenizes the input, generates a declarative sentence using the model, decodes it, and caches the result in `qa_pair_processed`. If the `input_text` is already cached, the cached output is reused.\n", "\n- The LaTeX description does not specify the generation hyperparameters used in the reference code\u2019s `model.generate` call, such as `do_sample=False` and `early_stopping=True`.\n", "\n- The LaTeX description does not specify tokenization details like the padding strategy used. However, the Python implementation explicitly sets `padding='longest'` during tokenization, ensuring uniform sequence lengths within batches.\n" ], "Mismatched_details": [ "\n- The LaTeX description states that the input sequence to the BART model is formed by concatenating the question \\( q^j_i \\) and answer \\( a^j_i \\), but it does not specify the order or separator. The reference Python code constructs this input as `f\"{answer} \\n {questions[idx]}\"`, placing the answer first, followed by a newline (`\\n`), and then the question. This workflow involves concatenating the answer and question in this specific order, tokenizing the result, and feeding it to the model.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - samples (list[dict]): Contains the data from which we want to extract sentences. A list where each element is a dictionary representing a document. The keys in the dictionary include:\n - 'claim' (String): The statement under investigation (e.g., that Kamala Harris called young voters \"stupid\").\n - 'label' (String): The verification outcome assigned to the claim, here labeled as \"Supported.\"\n - 'questions' (List[Dict]): Holds question-and-answer pairs or additional metadata relevant to the fact-check process.\n - 'fulltext' (String): The complete text of the article or document to be summarized.\n - 'sents_id_selected_by_bertsum' (List[Int]): Indices of the sentences selected by BertSum based on their scores.\n - 'sents_selected_by_bertsum' (List[String]): The actual text of the sentences chosen by BertSum.\n - 'sents_with_scores_by_bertsum' (List[Float]): Confidence scores assigned by BertSum to the selected sentences.\n - 'sents_order_by_bertsum' (List[Int]): The ranking order of the selected sentences by score.\n - 'sent_texts_order_by_bertsum' (List[String]): The sentences re-ordered according to their rank.\n - 'sentences' (List[String]): The full text split into tokenized sentences.\n - 'candidate_answers' (List[List[String]]): Candidate answers extracted from the selected sentences.\n - 'generated_question' (List[List[String]]): corresponding to the list of questions generated by the QG model for each candidate answer in 'candidate_answers'.\n - 'answer' (List[List[String]]): Nested list of answers corresponding to the generated questions ('generated_question' in each sample within samples).\n - model (transformers.PreTrainedModel):\n A pre-trained seq2seq model used for question generation.\n - tokenizer (transformers.PreTrainedTokenizer):\n A tokenizer from Hugging Face Transformers configured for the question generation model.\n - batch_size (int):\n Controls how many examples are processed at once when sending data to the question generation model.\n - max_length_gen (int):\n The maximum generate length for the model.\n - max_length_tokenizer (int):\n The maximum length for tokenizer.\n", "Arguments_list": [ { "name": "samples", "string": "\n- samples (list[dict]): Contains the data from which we want to extract sentences. A list where each element is a dictionary representing a document. The keys in the dictionary include:\n - 'claim' (String): The statement under investigation (e.g., that Kamala Harris called young voters \"stupid\").\n - 'label' (String): The verification outcome assigned to the claim, here labeled as \"Supported.\"\n - 'questions' (List[Dict]): Holds question-and-answer pairs or additional metadata relevant to the fact-check process.\n - 'fulltext' (String): The complete text of the article or document to be summarized.\n - 'sents_id_selected_by_bertsum' (List[Int]): Indices of the sentences selected by BertSum based on their scores.\n - 'sents_selected_by_bertsum' (List[String]): The actual text of the sentences chosen by BertSum.\n - 'sents_with_scores_by_bertsum' (List[Float]): Confidence scores assigned by BertSum to the selected sentences.\n - 'sents_order_by_bertsum' (List[Int]): The ranking order of the selected sentences by score.\n - 'sent_texts_order_by_bertsum' (List[String]): The sentences re-ordered according to their rank.\n - 'sentences' (List[String]): The full text split into tokenized sentences.\n - 'candidate_answers' (List[List[String]]): Candidate answers extracted from the selected sentences.\n - 'generated_question' (List[List[String]]): corresponding to the list of questions generated by the QG model for each candidate answer in 'candidate_answers'.\n - 'answer' (List[List[String]]): Nested list of answers corresponding to the generated questions ('generated_question' in each sample within samples).\n", "dependency": null }, { "name": "model", "string": "\n- model (transformers.PreTrainedModel):\n A pre-trained seq2seq model used for question generation.\n", "dependency": "transformers.PreTrainedModel" }, { "name": "tokenizer", "string": "\n- tokenizer (transformers.PreTrainedTokenizer):\n A tokenizer from Hugging Face Transformers configured for the question generation model.\n", "dependency": "transformers.PreTrainedTokenizer" }, { "name": "batch_size", "string": "\n- batch_size (int):\n Controls how many examples are processed at once when sending data to the question generation model.\n", "dependency": null }, { "name": "max_length_gen", "string": "\n- max_length_gen (int):\n The maximum generate length for the model.\n", "dependency": null }, { "name": "max_length_tokenizer", "string": "\n- max_length_tokenizer (int):\n The maximum length for tokenizer.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File Dependency: \n - None\n\n Cross-File Dependency: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - samples (list of dict): Returns the original list of dictionaries with additional keys containing the generated declarative statements for each question-answer pair. The updated key is:\n - 'candidate_claims' (List[List[List[String]]]): Nested list of generated declarative statements for each answer in the 'answer' list.\n [\n [\n [ \"Generated sentence 1\" ], # For answer 1 of question set 1\n [ \"Generated sentence 2\" ], # For answer 2 of question set 1\n ...\n ],\n [\n [ \"Generated sentence 1\" ], # For answer 1 of question set 2\n [ \"Generated sentence 2\" ], # For answer 2 of question set 2\n ...\n ],\n ...\n ]\n", "Return_list": [ { "name": "samples", "string": "\n- samples (list of dict): Returns the original list of dictionaries with additional keys containing the generated declarative statements for each question-answer pair. The updated key is:\n - 'candidate_claims' (List[List[List[String]]]): Nested list of generated declarative statements for each answer in the 'answer' list.\n [\n [\n [ \"Generated sentence 1\" ], # For answer 1 of question set 1\n [ \"Generated sentence 2\" ], # For answer 2 of question set 1\n ...\n ],\n [\n [ \"Generated sentence 1\" ], # For answer 1 of question set 2\n [ \"Generated sentence 2\" ], # For answer 2 of question set 2\n ...\n ],\n ...\n ]\n" } ] }, "ori_python_file": "import os\nimport json\nimport spacy\nimport stanza, argparse\nimport numpy as np\nfrom tqdm import tqdm\nfrom nltk.translate.chrf_score import sentence_chrf\nimport sys\nsys.path.append('presumm')\nfrom presumm import train\nfrom nltk.tokenize import sent_tokenize\nimport torch\nimport torch.nn as nn\nfrom simcse import SimCSE\nfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLM, T5ForConditionalGeneration\nfrom transformers import AutoModelForSequenceClassification\nfrom transformers.models.roberta.modeling_roberta import RobertaModel\nimport pickle\n\ndef sentence_ranking_by_BertSum(samples, configs):\n sent_with_score = train.main(configs)\n for idx, sample in enumerate(samples):\n fulltext = sample['fulltext']\n if fulltext[0] in [\"\u201c\", \"'\", \"\u201d\"] and fulltext[-1] in [\"\u201c\", \"'\", \"\u201d\"]:\n fulltext = fulltext[1:-1]\n sentences = sent_tokenize(fulltext)\n sample['sents_id_selected_by_bertsum'] = sent_with_score[idx][2]\n sample['sents_selected_by_bertsum'] = sent_with_score[idx][0]\n sample['sents_with_scores_by_bertsum'] = sent_with_score[idx][1].tolist()\n sample['sents_order_by_bertsum'] = sent_with_score[idx][4]\n sample['sent_texts_order_by_bertsum'] = sent_with_score[idx][5]\n sample['sentences'] = sentences\n return samples\n\ndef get_phrases(tree, label):\n if tree.is_leaf():\n return []\n results = []\n for child in tree.children:\n results += get_phrases(child, label)\n if tree.label == label:\n return [' '.join(tree.leaf_labels())] + results\n else:\n return results\n\ndef candidate_answer_extraction(samples):\n nlp = spacy.load('en_core_web_lg')\n stanza_nlp = stanza.Pipeline(lang='en', processors='tokenize,pos,constituency')\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Candidate Generation\"):\n fulltext = sample['fulltext']\n chrf_all_sents = [sentence_chrf(sample['claim'].split(), sent.split()) for sent in sample['sentences']]\n top3_sent_id_in_all_sents = np.argsort(-np.array(chrf_all_sents)).tolist()[:3]\n top3_chrf_in_all_sents = [chrf_all_sents[i] for i in top3_sent_id_in_all_sents]\n sample['top3_sent_in_all_sents'] = [top3_sent_id_in_all_sents, top3_chrf_in_all_sents]\n chrf_ext_sents = [sentence_chrf(sample['claim'].split(), sample['sentences'][_id].split()) for _id in\n sample['sents_order_by_bertsum']]\n order_top3_sent_id_in_ext_sents = np.argsort(-np.array(chrf_ext_sents)).tolist()[:3]\n top3_sent_id_in_ext_sents = [sample['sents_order_by_bertsum'][j] for j in order_top3_sent_id_in_ext_sents]\n top3_chrf_in_ext_sents = [chrf_ext_sents[i] for i in order_top3_sent_id_in_ext_sents]\n sample['top3_sent_in_ext_sents'] = [top3_sent_id_in_ext_sents, top3_chrf_in_ext_sents]\n if fulltext not in fulltext_processed.keys():\n sample['candidate_answers'] = []\n central_sents_sel_by_bertsum = [i for i in sample['sents_order_by_bertsum']]\n candidate_central_sentences = [sample['sentences'][i] for i in central_sents_sel_by_bertsum]\n candidate_answers = []\n for sent in candidate_central_sentences:\n if sent:\n candidate_answers_list = []\n doc = nlp(sent)\n stanza_doc = stanza_nlp(sent)\n ents = [ent.text for sent in doc.sents for ent in sent.noun_chunks]\n ents += [ent.text for sent in doc.sents for ent in sent.ents]\n ents += [phrase for sent in stanza_doc.sentences for phrase in get_phrases(sent.constituency, 'NP')]\n ents += [phrase for sent in stanza_doc.sentences for phrase in get_phrases(sent.constituency, 'VP')]\n ents += [word.text for sent in stanza_doc.sentences for word in sent.words if\n word.upos in ['VERB', 'ADV', 'ADJ', 'NOUN']]\n negations = [word for word in ['not', 'never'] if word in sample['fulltext']]\n candidate_answers_list.extend(sorted(set(ents + negations)))\n candidate_answers.append(candidate_answers_list)\n sample['candidate_answers'].extend(candidate_answers)\n fulltext_processed[fulltext] = sample['candidate_answers']\n else:\n print(\"Load the processed fulltext\")\n sample['candidate_answers'] = fulltext_processed[fulltext]\n return samples\n\ndef question_generation(samples, tokenizer, model, batch_size, max_length_gen=32, max_length_tokenizer=1024):\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Generating Questions\"):\n fulltext = sample['fulltext']\n if fulltext not in fulltext_processed.keys():\n sample['generated_question'] = []\n cand_sents = [i for i in sample['sents_order_by_bertsum']]\n assert len(cand_sents) == len(sample['candidate_answers'])\n for idx in range(len(sample['candidate_answers'])):\n texts = []\n _sentence = sample['sentences'][cand_sents[idx]]\n _candidate_ansewrs = sample['candidate_answers'][idx]\n for cand_ans in _candidate_ansewrs:\n texts.append(f\"{_sentence} \\\\n {cand_ans}\")\n gen_question = []\n if texts:\n for idy in range(0, len(texts), batch_size):\n input_ids = tokenizer(\n texts[idy:idy + batch_size],\n return_tensors=\"pt\",\n padding='longest',\n truncation=True,\n max_length=max_length_tokenizer\n ).input_ids.to(model.device)\n generated_ids = model.generate(input_ids, max_length=max_length_gen, do_sample=False)\n output = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)\n gen_question.extend(output)\n sample['generated_question'].append(gen_question)\n else:\n sample['generated_question'].append(gen_question)\n fulltext_processed[fulltext] = sample['generated_question']\n else:\n sample['generated_question'] = fulltext_processed[fulltext]\n return samples\n\ndef qa_generation(samples, model, tokenizer):\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Generating Answers\"):\n fulltext = sample['fulltext']\n cand_sents = [i for i in sample['sents_order_by_bertsum']]\n if fulltext not in fulltext_processed.keys():\n sample['answer'] = []\n for idx, questions in enumerate(sample['generated_question']):\n print(\"id={}/{}\".format(idx, len(sample['generated_question'])))\n if len(fulltext) <= 400:\n context = fulltext\n else:\n if cand_sents[idx] >= 10:\n context = sample['sentences'][\n (cand_sents[idx] - 10):(cand_sents[idx] + 10)\n ]\n else:\n context = sample['sentences'][0:(cand_sents[idx] + 10)]\n current_answers = []\n question_processed = dict()\n for idy, question in enumerate(questions):\n if question not in question_processed.keys():\n input_ids = tokenizer.encode(\n f\"{question} \\n {context}\",\n return_tensors='pt'\n ).to(model.device)\n with torch.no_grad():\n outputs = model.generate(\n input_ids,\n num_beams=4,\n do_sample=False\n )\n predict_answer_tokens_string = tokenizer.batch_decode(\n outputs,\n skip_special_tokens=True\n )[0]\n current_answers.append(predict_answer_tokens_string.strip())\n question_processed[question] = predict_answer_tokens_string.strip()\n else:\n print(\"Load the processed question\")\n current_answers.append(question_processed[question])\n sample['answer'].append(current_answers)\n fulltext_processed[fulltext] = sample['answer']\n else:\n print(\"Load the processed fulltext\")\n sample['answer'] = fulltext_processed[fulltext]\n return samples\n\ndef qa_to_context(samples, model, tokenizer, max_length_tokenizer=512, max_length_gen=64):\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Converting QA to statements\"):\n fulltext = sample['fulltext']\n if fulltext not in fulltext_processed.keys():\n generated_questions = sample['generated_question']\n generated_answers = sample['answer']\n sample['candidate_claims'] = []\n for questions, answers in zip(generated_questions, generated_answers):\n candidate_corrections_list = []\n qa_pair_processed = dict()\n for idx, answer in enumerate(answers):\n input_text = f\"{answer} \\\\n {questions[idx]}\"\n if input_text not in qa_pair_processed.keys():\n input_ids = tokenizer(\n input_text,\n return_tensors=\"pt\",\n padding='longest',\n truncation=True,\n max_length=max_length_tokenizer\n ).input_ids.to(model.device)\n generated_ids = model.generate(\n input_ids,\n max_length=max_length_gen,\n do_sample=False,\n early_stopping=True\n )\n candidate_corrections = tokenizer.batch_decode(\n generated_ids,\n skip_special_tokens=True\n )\n candidate_corrections_list.append(candidate_corrections)\n qa_pair_processed[input_text] = candidate_corrections\n else:\n print(\"Load the processed qa pair\")\n candidate_corrections_list.append(qa_pair_processed[input_text])\n sample['candidate_claims'].append(candidate_corrections_list)\n fulltext_processed[fulltext] = sample['candidate_claims']\n else:\n print(\"Load the processed fulltext\")\n sample['candidate_claims'] = fulltext_processed[fulltext]\n return samples\n\ndef gen_highquality_context(samples):\n simcse_model = SimCSE(\"princeton-nlp/sup-simcse-roberta-large\")\n cw_labels = ['Non-Factual Statement(NFS)', 'Unimportant Factual Statement(UFS)', 'Check-worthy Factual Statement(CFS)']\n cw_tokenizer = AutoTokenizer.from_pretrained(\"whispAI/ClaimBuster-DeBERTaV2\", use_auth_token=True)\n cw_model = AutoModelForSequenceClassification.from_pretrained(\"whispAI/ClaimBuster-DeBERTaV2\", use_auth_token=True)\n class RobertaForSequenceClassification(nn.Module):\n def __init__(self, tagset_size):\n super(RobertaForSequenceClassification, self).__init__()\n self.tagset_size = tagset_size\n self.roberta_single = RobertaModel.from_pretrained(pretrain_model_dir)\n self.single_hidden2tag = RobertaClassificationHead(bert_hidden_dim, tagset_size)\n def forward(self, input_ids, input_mask):\n outputs_single = self.roberta_single(input_ids, input_mask, None)\n hidden_states_single = outputs_single[1]\n score_single = self.single_hidden2tag(hidden_states_single)\n return score_single\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n bert_hidden_dim = 1024\n pretrain_model_dir = 'roberta-large'\n label_list = [\"entailment\", \"not_entailment\"]\n num_labels = len(label_list)\n class RobertaClassificationHead(nn.Module):\n def __init__(self, bert_hidden_dim, num_labels):\n super(RobertaClassificationHead, self).__init__()\n self.dense = nn.Linear(bert_hidden_dim, bert_hidden_dim)\n self.dropout = nn.Dropout(0.1)\n self.out_proj = nn.Linear(bert_hidden_dim, num_labels)\n def forward(self, features):\n x = features\n x = self.dropout(x)\n x = self.dense(x)\n x = torch.tanh(x)\n x = self.dropout(x)\n x = self.out_proj(x)\n return x\n model = RobertaForSequenceClassification(num_labels).to(device)\n tokenizer = AutoTokenizer.from_pretrained(pretrain_model_dir)\n checkpoint = torch.load('docnli_model/DocNLI.pretrained.RoBERTA.model.pt')\n model.load_state_dict(checkpoint, strict=False)\n def entailment_score(text1, text2):\n encoded_ctx = tokenizer.encode(text1)[:-1]\n encoded_correction = tokenizer.encode(text2)[1:]\n encoded_ctx_truncated = encoded_ctx[:512 - 1 - len(encoded_correction)]\n input_ids = torch.LongTensor(encoded_ctx_truncated + [tokenizer.sep_token_id] + encoded_correction).unsqueeze(\n 0).to(device)\n attention_mask = torch.LongTensor([1] * len(input_ids)).unsqueeze(0).to(device)\n inputs = {'input_ids': input_ids, 'input_mask': attention_mask}\n with torch.no_grad():\n model.eval()\n logits = model(**inputs)\n probs = torch.nn.Softmax(dim=1)(logits)\n correct_prob = probs[0][0].item()\n return correct_prob\n fulltext_processed = dict()\n for sample in tqdm(samples, desc=\"Running DocNLI\"):\n fulltext = sample['fulltext']\n cand_sents = [i for i in sample['sents_order_by_bertsum']]\n if fulltext not in fulltext_processed.keys():\n sample['claim_rank_by_entail_score'] = []\n sample['claim_rank_by_simcse_score'] = []\n sample['final_claims_cw'] = []\n sample['final_claims'] = []\n for idx, gen_claim in enumerate(sample['candidate_claims']):\n cand_claim_by_entail = []\n cand_claim_by_simcse = []\n cand_claim_rmv_dup = []\n if gen_claim:\n gen_claim_entail_scores = []\n gen_claim_simcse_scores = []\n claim_processed = dict()\n for idy, _claim in enumerate(gen_claim):\n if _claim[0] not in claim_processed.keys():\n correct_prob = entailment_score(sample['sentences'][cand_sents[idx]], _claim[0])\n gen_claim_entail_scores.append(correct_prob)\n claim_processed[_claim[0]] = correct_prob\n else:\n print(\"load the processed claim\")\n gen_claim_entail_scores.append(claim_processed[_claim[0]])\n topk_claims_id = range(len(gen_claim_entail_scores))\n if not topk_claims_id:\n topk_claims_id = np.argsort(-np.array(gen_claim_entail_scores)).tolist()[:5]\n for idz, _claim in enumerate(gen_claim):\n if idz in topk_claims_id:\n if [_claim[0], gen_claim_entail_scores[idz]] not in cand_claim_by_entail:\n cand_claim_by_entail.append([_claim[0], gen_claim_entail_scores[idz]])\n cand_claim_by_entail = sorted(cand_claim_by_entail, key=lambda x: x[1], reverse=True)\n if cand_claim_by_entail:\n cand_claim_by_entail_list = [c for c, s in cand_claim_by_entail]\n simcse_score = (simcse_model.similarity(sample['sentences'][cand_sents[idx]],\n cand_claim_by_entail_list)).ravel().tolist()\n gen_claim_simcse_scores.extend(simcse_score)\n cand_claim_by_simcse_id = np.argsort(-np.array(gen_claim_simcse_scores)).tolist()\n cand_claim_by_simcse.extend(\n [cand_claim_by_entail_list[i], gen_claim_simcse_scores[i]] for i in cand_claim_by_simcse_id)\n sample['claim_rank_by_entail_score'].append(cand_claim_by_entail)\n sample['claim_rank_by_simcse_score'].append(cand_claim_by_simcse)\n cand_claim_rmv_dup.extend([c for c, s in cand_claim_by_simcse])\n filter_by_entail_ids = []\n for i in reversed(range(len(cand_claim_rmv_dup))):\n for j in reversed(range(i)):\n if i not in filter_by_entail_ids:\n entail_prob = entailment_score(cand_claim_rmv_dup[j], cand_claim_rmv_dup[i])\n if entail_prob > 0.9:\n filter_by_entail_ids.append(i)\n for i in filter_by_entail_ids:\n del cand_claim_rmv_dup[i]\n simcse_sents = simcse_model.similarity(cand_claim_rmv_dup, cand_claim_rmv_dup)\n filter_by_simcse_ids = []\n for i in reversed(range(len(cand_claim_rmv_dup))):\n for j in reversed(range(i)):\n if i not in filter_by_simcse_ids:\n if simcse_sents[i][j] > 0.85:\n filter_by_simcse_ids.append(i)\n for i in filter_by_simcse_ids:\n del cand_claim_rmv_dup[i]\n cand_claim_with_check_worthy = []\n cand_claim_final = []\n for claim_text in cand_claim_rmv_dup:\n cw_sent_inputs = cw_tokenizer(claim_text, return_tensors=\"pt\")\n cw_sent_outputs = cw_model(**cw_sent_inputs)\n sent_logits = cw_sent_outputs.logits.tolist()[0]\n cw_sent_class = np.argmax(sent_logits)\n sent_label = cw_labels[int(cw_sent_class)]\n cand_claim_with_check_worthy.append([claim_text, sent_label, sent_logits])\n if sent_label in ['Unimportant Factual Statement(UFS)', 'Check-worthy Factual Statement(CFS)']:\n cand_claim_final.append([claim_text])\n sample['final_claims_cw'].append(cand_claim_with_check_worthy)\n sample['final_claims'].append(cand_claim_final)\n else:\n sample['claim_rank_by_entail_score'].append(cand_claim_by_entail)\n sample['claim_rank_by_simcse_score'].append(cand_claim_by_simcse)\n sample['final_claims_cw'].append([])\n sample['final_claims'].append([])\n fulltext_processed[fulltext] = [sample['claim_rank_by_entail_score'],\n sample['claim_rank_by_simcse_score'], sample['final_claims_cw'],\n sample['final_claims']]\n else:\n print(\"Load the processed fulltext\")\n sample['claim_rank_by_entail_score'], sample['claim_rank_by_simcse_score'], sample['final_claims_cw'], sample['final_claims'] = fulltext_processed[fulltext]\n return samples\n\ndef main(args):\n import os, random\n os.environ['PYTHONHASHSEED'] = str(42)\n os.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\n np.random.seed(42)\n if torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\n torch.use_deterministic_algorithms(True)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n random.seed(42)\n torch.cuda.synchronize()\n data_path = \"all_data\"\n all_avail_url_files = \"{}/1_all_available_url_fulltext.json\".format(data_path)\n if not os.path.exists(all_avail_url_files):\n print(\"***** run python 1_extract_texts_from_url.py *****\")\n ranked_sentence_file = \"{}/2_sent_ranked_by_bertsum.json\".format(data_path)\n samples = json.load(open(all_avail_url_files, 'r'))\n if args.TestCode:\n samples = samples[:10]\n configs = dict()\n configs['task'] = 'ext'\n configs['mode'] = 'test_text'\n configs['test_from'] = 'presumm/save_model/bertext_cnndm_transformer.pt'\n configs['text_src'] = 'all_data/1_all_available_url_fulltext.json'\n configs['result_path'] = 'presumm/results/ootb_output'\n configs['alpha'] = 0.95\n configs['log_file'] = 'presumm/logs/test.log'\n configs['visible_gpus'] = '0'\n ranked_samples = sentence_ranking_by_BertSum(samples, configs)\n cand_ans_extraction_file = \"{}/3_generated_candidates.jsonl\".format(data_path)\n cand_ans_samples = candidate_answer_extraction(ranked_samples)\n gen_question_file = \"{}/4_generated_questions.jsonl\".format(data_path)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n tokenizer = AutoTokenizer.from_pretrained('t5-base')\n model = AutoModelForSeq2SeqLM.from_pretrained('Salesforce/mixqg-base').to(device)\n model.eval()\n batch_size = 10\n gen_que_samples = question_generation(cand_ans_samples, tokenizer, model, batch_size)\n gen_answer_file = \"{}/5_generated_answers.jsonl\".format(data_path)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model_name = 'allenai/unifiedqa-v2-t5-base-1251000'\n tokenizer = AutoTokenizer.from_pretrained('t5-base')\n model = T5ForConditionalGeneration.from_pretrained(model_name).to(device)\n model.eval()\n gen_answer_samples = qa_generation(gen_que_samples, model, tokenizer)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n pretrain_model_path = \"khhuang/zerofec-qa2claim-t5-base\"\n tokenizer = AutoTokenizer.from_pretrained('t5-base')\n model = AutoModelForSeq2SeqLM.from_pretrained(pretrain_model_path).to(device)\n model.eval()\n gen_context_file = \"{}/6_generated_context.jsonl\".format(data_path)\n gen_context_samples = qa_to_context(gen_answer_samples, model, tokenizer)\n gen_context_file = \"{}/7_highquality_context.jsonl\".format(data_path)\n gen_highcontext_samples = gen_highquality_context(gen_context_samples)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n main(args)" } ] }, { "paper_id": 12, "paper_details": { "title": "IRCAN: Mitigating Knowledge Conflicts in LLM Generation via Identifying and Reweighting Context-Aware Neurons", "url": "https://arxiv.org/abs/2406.18406" }, "enviorment_name": "IRCAN", "repo_original_url": "https://github.com/danshi777/ircan", "project_path": "Benchmark/12-IRCAN-main/IRCAN-main", "file_organization": "\nIRCAN-main/\n data/\n KRE/\n COSE/\n ECARE/\n MemoTrap/\n memo-trap_classification_dev.jsonl\n memo-trap_classification.jsonl\n memo-trap_classification_test.jsonl\n env.sh\n overview.png\n README.md\n results/\n attribution/\n Memo-llama2-7b-context.args.json\n Memo-llama2-7b-context.rlt.jsonl\n Memo-llama2-7b-context.time.json\n cn/\n Memo-llama2-7b-cn_bag-context.json\n src/\n 1_calculate_attribution_completion.py\n 1_calculate_attribution_mcq.py\n 1_run_calculate_completion_Memo_llama2-7b.sh\n 1_run_calculate_mcq_COSE_llama2-7b-chat.sh\n 2_get_cns.py\n 2_run_get_cns_COSE_llama2-7b-chat.sh\n 2_run_get_cns_Memo_llama2-7b.sh\n 3_enhance_and_evaluate.py\n 3_run_dev_COSE_llama2-7b-chat.sh\n 3_run_dev_Memo_llama2-7b.sh\n 4_run_test_COSE_enhanced_llama2-7b-chat.sh\n 4_run_test_COSE_origin_llama2-7b-chat.sh\n 4_run_test_Memo_enhanced_llama2-7b.sh\n 4_run_test_Memo_origin_llama2-7b.sh\n 5_run_test_COSE_randomly_llama2-7b-chat.sh\n 5_run_test_Memo_randomly_enhanced_llama2-7b.sh\n plot_cn_distribution.py\n run_plot_cn_distribution.sh\n utils/\n enhance_model.py\n", "latex_code_path": "Benchmark/12-IRCAN-main/arXiv-2406.18406v2", "task_details": [ { "task_id": 0, "indent": 1, "script": "\npython src/1_calculate_attribution_completion.py \\\n --model_path meta-llama/Llama-2-7b-hf \\\n --data_path data/MemoTrap/memo-trap_classification.jsonl \\\n --model_name llama2-7b \\\n --dataset_name Memo \\\n --output_dir results/attribution/ \\\n --gpu_id 0 \\\n --max_seq_length 128 \\\n --batch_size 20 \\\n --TestCode\n", "latex_code": "\n\\subsection{Context-Aware Attribution}\n\nPrevious work has found the existence of knowledge neurons that store and express factual knowledge in FFNs \\citep{DBLP:conf/acl/DaiDHSCW22}. We speculate that certain neurons responsible for processing contextual knowledge also exist in FFNs. Inspired by \\citet{DBLP:conf/aaai/Hao0W021}, who introduce an attribution method to interpret the information interactions inside Transformer, we propose a context-aware attribution method based on integrated gradients \\citep{DBLP:conf/icml/SundararajanTY17} to identify these neurons. Our method calculates the contribution scores of FFN neurons in perceiving the context towards predicting answers. This evaluation helps determine which neurons play a critical role in context processing.\n\nThe attribution score of each neuron to be evaluated is denoted as $\\mathrm{Attr}(n_i^l)$, where $n_i^l$ represents the intermediate neuron at the $i$-th position in the $l$-th FFN layer of the language model. Initially, we take only the question as input, record the activation value of each neuron and denote it as ${\\boldsymbol{v}_{q}}_i^l$. Subsequently, we input both the context and the question into the language model and record the new activation value, denoted as ${\\boldsymbol{v}_{(c,q)}}_i^l$. To calculate the attribution score $\\mathrm{Attr}(n_i^l)$, we gradually change the activation value of a neuron $n_i^l$ from ${\\boldsymbol{v}_{q}}_i^l$ to ${\\boldsymbol{v}_{(c,q)}}_i^l$ when the input consists of both context and question. At the same time, the output probability of the model changes accordingly. We calculate the probability of the correct answer predicted by the language model, denoted as: \n\n\\begin{equation}\n P(\\boldsymbol{v}_i^l)=p(y^*|c,q,\\mathbf{A}(n_i^l)=\\boldsymbol{v}_i^l) ,\n\\end{equation}\n\n\nwhere $y^{\\ast}$ denotes the correct answer; $\\boldsymbol{v}_i^l$ is a given value assigned to the neuron activation $\\mathbf{A}(n_i^l)$. We integrate the gradient of the probability during this process as the neuron's context-aware attribution score, as follows:\n\n\\begin{equation}\n \\mathrm{Attr}(n_i^l) = \\left({\\boldsymbol{v}_{(c,q)}}_i^l-{\\boldsymbol{v}_{q}}_i^l\\right) \\int_{\\alpha=0}^{1} \\frac{\\partial P\\left[{\\boldsymbol{v}_{q}}_i^l + \\alpha \\left({\\boldsymbol{v}_{(c,q)}}_i^l-{\\boldsymbol{v}_{q}}_i^l\\right)\\right]}{\\partial {\\boldsymbol{v}_{(c,q)}}_i^l} \\, d\\alpha ,\n\\end{equation}\n\nwhere $ \\frac{\\partial P\\left[{\\boldsymbol{v}_{q}}_i^l + \\alpha \\left({\\boldsymbol{v}_{(c,q)}}_i^l-{\\boldsymbol{v}_{q}}_i^l\\right)\\right]}{\\partial {\\boldsymbol{v}_{(c,q)}}_i^l} $ calculates the gradient of the model probability with regard to $ {\\boldsymbol{v}_{(c,q)}}_i^l $, $\\alpha$ controls the integration from ${\\boldsymbol{v}_{q}}_i^l$ to ${\\boldsymbol{v}_{(c,q)}}_i^l$.\n\nTheoretically, the integrated gradients technique adheres to two fundamental axioms of attribution methods: \\emph{Sensitivity} and \\emph{Implementation Invariance} \\citep{DBLP:conf/icml/SundararajanTY17}. The \\emph{Sensitivity} axiom stipulates that if modifying a neuron alters the prediction, that neuron should be assigned a non-zero attribution score. The \\emph{Implementation Invariance} axiom dictates that the attributions should remain identical for two networks with equivalent functionality. Adherence to these axioms ensures that the attribution scores accurately reflect the importance of neurons and are invariant to implementation details. The attribution scores facilitate the identification of neurons essential for context processing.\n\nIntuitively, by integrating over the gradient as $\\alpha$ changes from 0 to 1, $\\mathrm{Attr}(n_i^l)$ accumulates the output probability changes caused by the activation value changes from the absence to the presence of context. If the neuron has a strong perception and processing capability regarding the context, the gradient will be significant, resulting in a large integration value. Therefore, the attribution score can measure the neuron's sensitivity to the context and its contribution to processing the context.\n\nDirectly calculating continuous integrals is intractable. We instead use the Riemann approximation of the integration to efficiently compute the attribution score. Specifically, we sum the gradients at points occurring at sufficiently small intervals from ${\\boldsymbol{v}_{q}}_i^l$ to ${\\boldsymbol{v}_{(c,q)}}_i^l$:\n\n\\begin{equation}\n \\tilde{\\mathrm{Attr}}(n_i^l) = \\frac{\\left({\\boldsymbol{v}_{(c,q)}}_i^l-{\\boldsymbol{v}_{q}}_i^l\\right)}{m} \\sum_{k=1}^m \\frac{\\partial P\\left[{\\boldsymbol{v}_{q}}_i^l + \\frac{k}{m} \\left({\\boldsymbol{v}_{(c,q)}}_i^l-{\\boldsymbol{v}_{q}}_i^l\\right) \\right]}{\\partial {\\boldsymbol{v}_{(c,q)}}_i^l} ,\n\\end{equation}\n\n\nwhere $m$ is the number of approximation steps. Following previous work \\citep{DBLP:conf/acl/DaiDHSCW22}, we set $m$ to 20, which performs well in our experiments. \n", "completion_path": "./src/1_calculate_attribution_completion.py", "namespace": "src.1_calculate_attribution_completion.get_context_attr", "type": "function", "signature_position": [ 24, 31 ], "body_position": [ 32, 105 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Extracting gold label and tokenizing inputs\n# It tokenizes the provided answer text to determine the gold label identifier. Additionally, tokenizes the prompts (with and without context) to obtain the input IDs and attention masks required for model inference.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\ntokens = tokenizer.tokenize(answer_obj)\ngold_label_id = tokenizer.convert_tokens_to_ids(tokens[0])\n\nwo_tokenized_inputs = tokenizer(prompt_without_context, return_tensors=\"pt\")\nwo_input_ids = wo_tokenized_inputs[\"input_ids\"].to(device)\nwo_attention_mask = wo_tokenized_inputs[\"attention_mask\"].to(device)\n\nw_tokenized_inputs = tokenizer(prompt_with_context, return_tensors=\"pt\")\nw_input_ids = w_tokenized_inputs[\"input_ids\"].to(device)\nw_attention_mask = w_tokenized_inputs[\"attention_mask\"].to(device)\n# [End Snippet 1]\n\nres_dict = {\n 'idx': idx,\n 'wo_all_ffn_activations': [],\n 'w_all_ffn_activations': [],\n 'all_attr_gold': [],\n}\n\nfor tgt_layer in range(model.model.config.num_hidden_layers):\n\n # ---------------------------------------------------------------------------\n # Snippet 2: Setting up forward hook for capturing FFN activations without context.\n # It Defines and registers a hook that captures the input to the FFN (specifically, the down projection) when processing the prompt without context.\n # It Retrieves the baseline activations ${\\boldsymbol{v}_{q}}_i^l$ for the current layer.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 2]\n wo_ffn_activations_dict = dict()\n def wo_forward_hook_fn(module, inp, outp):\n wo_ffn_activations_dict['input'] = inp[0]\n # [End Snippet 2]\n\n # ---------------------------------------------------------------------------\n # Snippet 3: Setting up forward hook for capturing FFN activations with context.\n # It Defines and registers a hook that captures the input to the FFN when processing the prompt with context.\n # It Retrieves the perturbed activations ${\\boldsymbol{v}_{(c,q)}}_i^l$ for the current layer.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 3]\n w_ffn_activations_dict = dict()\n def w_forward_hook_fn(module, inp, outp):\n w_ffn_activations_dict['input'] = inp[0]\n # [End Snippet 3]\n\n # ---------------------------------------------------------------------------\n # Snippet 4: Capturing FFN activations without context via model forward pass.\n # It Registers the forward hook, runs the model on the prompt without context, extracts the final token's FFN activations, and removes the hook.\n # It corresponds to obtaining ${\\boldsymbol{v}_{q}}_i^l$, the baseline activation necessary for integrated gradients.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 4]\n wo_hook = model.model.layers[tgt_layer].mlp.down_proj.register_forward_hook(wo_forward_hook_fn)\n with torch.no_grad():\n wo_outputs = model(input_ids=wo_input_ids, attention_mask=wo_attention_mask)\n wo_ffn_activations = wo_ffn_activations_dict['input']\n wo_ffn_activations = wo_ffn_activations[:, -1, :]\n wo_logits = wo_outputs.logits[:, -1, :]\n wo_hook.remove()\n # [End Snippet 4]\n\n # ---------------------------------------------------------------------------\n # Snippet 5: Capturing FFN activations with context via model forward pass.\n # It Registers the forward hook, runs the model on the prompt with context, extracts the final token's FFN activations, and then removes the hook.\n # It Retrieves ${\\boldsymbol{v}_{(c,q)}}_i^l$, the activations with context.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 5]\n w_hook = model.model.layers[tgt_layer].mlp.down_proj.register_forward_hook(w_forward_hook_fn)\n with torch.no_grad():\n w_outputs = model(input_ids=w_input_ids, attention_mask=w_attention_mask)\n w_ffn_activations = w_ffn_activations_dict['input']\n w_ffn_activations = w_ffn_activations[:, -1, :]\n w_logits = w_outputs.logits[:, -1, :]\n w_hook.remove()\n # [End Snippet 5]\n\n # ---------------------------------------------------------------------------\n # Snippet 6: Preparing activations for gradient integration by enabling gradients and generating scaled activations. \n # It Enables gradient tracking on the captured activations and computes a series of interpolated activation values bridging the gap between the baseline and context activations using the scaled_input function.\n # It Implements the interpolation from ${\\boldsymbol{v}_{q}}_i^l$ to ${\\boldsymbol{v}_{(c,q)}}_i^l$ for integrated gradients.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 6]\n wo_ffn_activations.requires_grad_(True)\n w_ffn_activations.requires_grad_(True)\n\n scaled_activations, activations_step = scaled_input(wo_ffn_activations, \n w_ffn_activations, \n args.batch_size, \n args.num_batch)\n scaled_activations.requires_grad_(True)\n # [End Snippet 6]\n\n # ---------------------------------------------------------------------------\n # Snippet 7: Accumulating gradients over mini-batches to approximate the integrated gradients.\n # Iterates over mini-batches of the interpolated activations to compute the gradient of the target\n # output probability with respect to the activations. A forward pre-hook temporarily replaces\n # the activation with the interpolated value to capture the corresponding gradient. These gradients\n # are accumulated over batches to approximate the integral.\n # It Corresponds to the Riemann sum approximation where the gradient is computed at each interpolation step and then summed to form the integrated gradient.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 7]\n ig_gold = None\n\n for batch_idx in range(args.num_batch):\n grad = None\n all_grads = None\n\n for i in range(0, args.batch_size, args.batch_size_per_inference):\n batch_activations = scaled_activations[i: i + args.batch_size_per_inference]\n\n batch_w_activations = w_ffn_activations.repeat(args.batch_size_per_inference, 1)\n batched_w_input_ids = w_input_ids.repeat(args.batch_size_per_inference, 1)\n batched_w_attention_mask = w_attention_mask.repeat(args.batch_size_per_inference, 1)\n\n def i_forward_hook_change_fn(module, inp):\n inp0 = inp[0]\n inp0[:, -1, :] = batch_activations\n inp = tuple([inp0])\n return inp\n\n change_hook = model.model.layers[tgt_layer].mlp.down_proj.register_forward_pre_hook(i_forward_hook_change_fn)\n\n outputs = model(input_ids=batched_w_input_ids, attention_mask=batched_w_attention_mask)\n tgt_logits = outputs.logits[:, -1, :]\n tgt_probs = F.softmax(tgt_logits, dim=1)\n\n grads_i = torch.autograd.grad(\n torch.unbind(tgt_probs[:, gold_label_id]), \n w_ffn_activations, \n retain_graph=True\n )\n\n change_hook.remove()\n \n all_grads = grads_i[0] if all_grads is None else torch.cat((all_grads, grads_i[0]), dim=0)\n \n grad = all_grads.sum(dim=0)\n ig_gold = grad if ig_gold is None else torch.add(ig_gold, grad)\n # [End Snippet 7]\n\n # ---------------------------------------------------------------------------\n # Snippet 8: Finalizing the integrated gradients attribution score. \n # Multiplies the accumulated gradient sum by the integration step to yield the final attributionscore for the current layer.\n # It Implements the multiplication by (v(c,q) - v(q))/m as prescribed in the integrated gradients formula in latex code.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 8]\n ig_gold = ig_gold * activations_step\n # [End Snippet 8]\n\n res_dict['wo_all_ffn_activations'].append(wo_ffn_activations.squeeze().tolist())\n res_dict['w_all_ffn_activations'].append(w_ffn_activations.squeeze().tolist())\n res_dict['all_attr_gold'].append(ig_gold.tolist())\n\n# ---------------------------------------------------------------------------\n# Snippet 9: Returning the complete attribution results\n# ---------------------------------------------------------------------------\n# [Begin Snippet 9]\nreturn res_dict\n# [End Snippet 9]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - Intermediate Activation Overriding via Forward Pre-hook: The code should use a forward pre-hook (register_forward_pre_hook) to explicitly replace the intermediate FFN neuron activations (mlp.down_proj) with scaled activations during gradient computation.\n - The LaTeX code omits the batching mechanism for computing the Riemann approximation efficiently, which is critical in the reference Python code. The workflow in the reference code involves: (1) interpolating activations between \\( {\\boldsymbol{v}_{q}}_i^l \\) and \\( {\\boldsymbol{v}_{(c,q)}}_i^l \\) using a function like `scaled_input` to generate a batch of scaled activations (controlled by `args.batch_size` and `args.num_batch`), (2) processing these in mini-batches (via `args.batch_size_per_inference`) by repeating input IDs and attention masks, (3) computing gradients for each mini-batch using a pre-hook to inject scaled activations, and (4) accumulating gradients across batches before final scaling.\n - The LaTeX description lacks details on how gradients are computed with respect to a specific activation tensor. In the reference code, the workflow is: (1) enabling gradient tracking on the context activations \\( {\\boldsymbol{v}_{(c,q)}}_i^l \\) (`w_ffn_activations.requires_grad_(True)`), (2) injecting interpolated activations via a pre-hook on `mlp.down_proj` while keeping the original tensor as the gradient target, (3) computing the gradient of the softmax probability of the gold token ID with respect to \\( {\\boldsymbol{v}_{(c,q)}}_i^l \\) using `torch.autograd.grad`, and (4) summing these gradients over all steps.\n\n Mismatched Details:\n - Uses batch_size/num_batch instead of direct m=20 steps\n - The LaTeX equation for the Riemann approximation (\\( \\tilde{\\mathrm{Attr}}(n_i^l) = \\frac{\\left({\\boldsymbol{v}_{(c,q)}}_i^l-{\\boldsymbol{v}_{q}}_i^l\\right)}{m} \\sum_{k=1}^m \\frac{\\partial P}{\\partial {\\boldsymbol{v}_{(c,q)}}_i^l} \\)) implies that the gradient is computed at discrete points and scaled by the step size \\( \\frac{\\left({\\boldsymbol{v}_{(c,q)}}_i^l-{\\boldsymbol{v}_{q}}_i^l\\right)}{m} \\). The reference Python code aligns with this by accumulating gradients over `args.num_batch` steps and scaling by `activations_step` (computed as the activation difference divided by the number of steps).\n", "Missing_details": [ "Intermediate Activation Overriding via Forward Pre-hook: The code should use a forward pre-hook (register_forward_pre_hook) to explicitly replace the intermediate FFN neuron activations (mlp.down_proj) with scaled activations during gradient computation.", "The LaTeX code omits the batching mechanism for computing the Riemann approximation efficiently, which is critical in the reference Python code. The workflow in the reference code involves: (1) interpolating activations between \\( {\\boldsymbol{v}_{q}}_i^l \\) and \\( {\\boldsymbol{v}_{(c,q)}}_i^l \\) using a function like `scaled_input` to generate a batch of scaled activations (controlled by `args.batch_size` and `args.num_batch`), (2) processing these in mini-batches (via `args.batch_size_per_inference`) by repeating input IDs and attention masks, (3) computing gradients for each mini-batch using a pre-hook to inject scaled activations, and (4) accumulating gradients across batches before final scaling.", "The LaTeX description lacks details on how gradients are computed with respect to a specific activation tensor. In the reference code, the workflow is: (1) enabling gradient tracking on the context activations \\( {\\boldsymbol{v}_{(c,q)}}_i^l \\) (`w_ffn_activations.requires_grad_(True)`), (2) injecting interpolated activations via a pre-hook on `mlp.down_proj` while keeping the original tensor as the gradient target, (3) computing the gradient of the softmax probability of the gold token ID with respect to \\( {\\boldsymbol{v}_{(c,q)}}_i^l \\) using `torch.autograd.grad`, and (4) summing these gradients over all steps." ], "Mismatched_details": [ "Uses batch_size/num_batch instead of direct m=20 steps", "- The LaTeX equation for the Riemann approximation (\\( \\tilde{\\mathrm{Attr}}(n_i^l) = \\frac{\\left({\\boldsymbol{v}_{(c,q)}}_i^l-{\\boldsymbol{v}_{q}}_i^l\\right)}{m} \\sum_{k=1}^m \\frac{\\partial P}{\\partial {\\boldsymbol{v}_{(c,q)}}_i^l} \\)) implies that the gradient is computed at discrete points and scaled by the step size \\( \\frac{\\left({\\boldsymbol{v}_{(c,q)}}_i^l-{\\boldsymbol{v}_{q}}_i^l\\right)}{m} \\). The reference Python code aligns with this by accumulating gradients over `args.num_batch` steps and scaling by `activations_step` (computed as the activation difference divided by the number of steps)." ] }, "Arguments": { "string": "\nInput Variables:\n - idx (int): Index or identifier for the current sample. \n - prompt_without_context (str): A text prompt that does NOT include context.\n - prompt_with_context (str): A text prompt that includes both the question and the contextual information.\n - answer_obj (str): The correct answer or token string expected from the model (gold label).\n - args (Namespace): A collection of parameters controlling batch sizes and number of batches:\n - args.batch_size (int): The number of activation samples to be processed in one step.\n - args.num_batch (int): Total number of scaled steps used for Riemann approximation.\n - args.batch_size_per_inference (int): Chunk size for partial inference passes.\n - model (transformers.LLamaForCausalLM): Language model used for computing logits and activations.\n - tokenizer (transformers.LlamaTokenizerFast): Converts text into tokens and manages the mapping to input IDs.\n - device (torch.device): Specifies GPU or CPU.\n", "Arguments_list": [ { "name": "idx", "string": "- idx (int): Index or identifier for the current sample.", "dependency": null }, { "name": "prompt_without_context", "string": "- prompt_without_context (str): A text prompt that does NOT include context.", "dependency": null }, { "name": "prompt_with_context", "string": "- prompt_with_context (str): A text prompt that includes both the question and the contextual information.", "dependency": null }, { "name": "answer_obj", "string": "- answer_obj (str): The correct answer or token string expected from the model (gold label).", "dependency": null }, { "name": "args", "string": "\n- args (Namespace): A collection of parameters controlling batch sizes and number of batches:\n - args.batch_size (int): The number of activation samples to be processed in one step.\n - args.num_batch (int): Total number of scaled steps used for Riemann approximation.\n - args.batch_size_per_inference (int): Chunk size for partial inference passes.\n", "dependency": null }, { "name": "model", "string": "- model (transformers.LLamaForCausalLM): Language model used for computing logits and activations.", "dependency": null }, { "name": "tokenizer", "string": "- tokenizer (transformers.LlamaTokenizerFast): Converts text into tokens and manages the mapping to input IDs.", "dependency": null }, { "name": "device", "string": "- device (torch.device): Specifies GPU or CPU.", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File Dependency: \n - scaled_input\n\n Cross-File Dependency: \n - None\n", "intra_file": [ "scaled_input" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs: \n - torch.unbind\n - torch.add\n - torch.cat\n - torch.autograd.grad\n - torch.no_grad\n - torch.nn.functional.softmax\n", "list": [ "torch.unbind", "torch.add", "torch.cat", "torch.autograd.grad", "torch.no_grad", "torch.nn.functional.softmax" ] }, "Return": { "Return_String": "\nOutput Variables:\n - res_dict (dict): A dictionary containing:\n - 'idx' (int): Same as the function input 'idx', for reference.\n - 'wo_all_ffn_activations' (List[List]): list of lists (one per layer). Captures the final FFN neuron activations (shape: [1, ffn_size]) at each layer WITHOUT context.\n - 'w_all_ffn_activations': list of lists (one per layer). Captures the final FFN neuron activations (shape: [1, ffn_size]) at each layer WITH context.\n - 'all_attr_gold': list of lists (one per layer). Integrated gradients scores for the 'gold_label_id'(gold-label token ID) (shape: [ffn_size]) at each layer.\n", "Return_list": [ { "name": "res_dict", "string": "\n- res_dict (dict): A dictionary containing:\n - 'idx' (int): Same as the function input 'idx', for reference.\n - 'wo_all_ffn_activations' (List[List]): list of lists (one per layer). Captures the final FFN neuron activations (shape: [1, ffn_size]) at each layer WITHOUT context.\n - 'w_all_ffn_activations': list of lists (one per layer). Captures the final FFN neuron activations (shape: [1, ffn_size]) at each layer WITH context.\n - 'all_attr_gold': list of lists (one per layer). Integrated gradients scores for the 'gold_label_id'(gold-label token ID) (shape: [ffn_size]) at each layer.\n", "dependency": null } ] }, "ori_python_file": "import logging\nimport argparse\nimport math\nimport os\nimport torch\nimport random\nimport numpy as np\nimport json, jsonlines\nimport pickle\nimport time\nfrom tqdm import tqdm\nfrom transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig\nimport torch.nn.functional as F\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt='%m/%d/%Y %H:%M:%S',\n level=logging.INFO)\nlogger = logging.getLogger(__name__)\ndef scaled_input(minimum_activations, maximum_activations, batch_size, num_batch):\n num_points = batch_size * num_batch\n step = (maximum_activations - minimum_activations) / num_points\n res = torch.cat([torch.add(minimum_activations, step * i) for i in range(num_points)], dim=0)\n return res, step[0]\n\ndef get_context_attr(idx,\n prompt_without_context,\n prompt_with_context,\n answer_obj,\n args,\n model,\n tokenizer,\n device):\n tokens = tokenizer.tokenize(answer_obj)\n gold_label_id = tokenizer.convert_tokens_to_ids(tokens[0])\n wo_tokenized_inputs = tokenizer(prompt_without_context, return_tensors=\"pt\")\n wo_input_ids = wo_tokenized_inputs[\"input_ids\"].to(device)\n wo_attention_mask = wo_tokenized_inputs[\"attention_mask\"].to(device)\n w_tokenized_inputs = tokenizer(prompt_with_context, return_tensors=\"pt\")\n w_input_ids = w_tokenized_inputs[\"input_ids\"].to(device)\n w_attention_mask = w_tokenized_inputs[\"attention_mask\"].to(device)\n res_dict = {\n 'idx': idx,\n 'wo_all_ffn_activations': [],\n 'w_all_ffn_activations': [],\n 'all_attr_gold': [],\n }\n for tgt_layer in range(model.model.config.num_hidden_layers):\n wo_ffn_activations_dict = dict()\n def wo_forward_hook_fn(module, inp, outp):\n wo_ffn_activations_dict['input'] = inp[0]\n w_ffn_activations_dict = dict()\n def w_forward_hook_fn(module, inp, outp):\n w_ffn_activations_dict['input'] = inp[0]\n wo_hook = model.model.layers[tgt_layer].mlp.down_proj.register_forward_hook(wo_forward_hook_fn)\n with torch.no_grad():\n wo_outputs = model(input_ids=wo_input_ids, attention_mask=wo_attention_mask)\n wo_ffn_activations = wo_ffn_activations_dict['input']\n wo_ffn_activations = wo_ffn_activations[:, -1, :]\n wo_logits = wo_outputs.logits[:, -1, :]\n wo_hook.remove()\n w_hook = model.model.layers[tgt_layer].mlp.down_proj.register_forward_hook(w_forward_hook_fn)\n with torch.no_grad():\n w_outputs = model(input_ids=w_input_ids, attention_mask=w_attention_mask)\n w_ffn_activations = w_ffn_activations_dict['input']\n w_ffn_activations = w_ffn_activations[:, -1, :]\n w_logits = w_outputs.logits[:, -1, :]\n w_hook.remove()\n wo_ffn_activations.requires_grad_(True)\n w_ffn_activations.requires_grad_(True)\n scaled_activations, activations_step = scaled_input(wo_ffn_activations,\n w_ffn_activations,\n args.batch_size,\n args.num_batch)\n scaled_activations.requires_grad_(True)\n ig_gold = None\n for batch_idx in range(args.num_batch):\n grad = None\n all_grads = None\n for i in range(0, args.batch_size, args.batch_size_per_inference):\n batch_activations = scaled_activations[i: i + args.batch_size_per_inference]\n batch_w_activations = w_ffn_activations.repeat(args.batch_size_per_inference, 1)\n batched_w_input_ids = w_input_ids.repeat(args.batch_size_per_inference, 1)\n batched_w_attention_mask = w_attention_mask.repeat(args.batch_size_per_inference, 1)\n def i_forward_hook_change_fn(module, inp):\n inp0 = inp[0]\n inp0[:, -1, :] = batch_activations\n inp = tuple([inp0])\n return inp\n change_hook = model.model.layers[tgt_layer].mlp.down_proj.register_forward_pre_hook(i_forward_hook_change_fn)\n outputs = model(input_ids=batched_w_input_ids, attention_mask=batched_w_attention_mask)\n tgt_logits = outputs.logits[:, -1, :]\n tgt_probs = F.softmax(tgt_logits, dim=1)\n grads_i = torch.autograd.grad(\n torch.unbind(tgt_probs[:, gold_label_id]),\n w_ffn_activations,\n retain_graph=True\n )\n change_hook.remove()\n all_grads = grads_i[0] if all_grads is None else torch.cat((all_grads, grads_i[0]), dim=0)\n grad = all_grads.sum(dim=0)\n ig_gold = grad if ig_gold is None else torch.add(ig_gold, grad)\n ig_gold = ig_gold * activations_step\n res_dict['wo_all_ffn_activations'].append(wo_ffn_activations.squeeze().tolist())\n res_dict['w_all_ffn_activations'].append(w_ffn_activations.squeeze().tolist())\n res_dict['all_attr_gold'].append(ig_gold.tolist())\n return res_dict\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--data_path\",\n default=None,\n type=str,\n required=True,\n help=\"The input data path. Should be .json file for the MLM task. \")\n parser.add_argument(\"--model_path\",\n default=None,\n type=str,\n required=True,\n help=\"Path to local pretrained model or model identifier from huggingface.co/models.\")\n parser.add_argument(\"--output_dir\",\n default=None,\n type=str,\n required=True,\n help=\"The output directory where the model predictions and checkpoints will be written.\")\n parser.add_argument(\"--dataset_name\",\n type=str,\n default=None,\n help=\"Dataset name as output prefix to indentify each running of experiment.\")\n parser.add_argument(\"--model_name\",\n default=None,\n type=str,\n help=\"Model name as output prefix to indentify each running of experiment.\")\n parser.add_argument(\"--max_seq_length\",\n default=128,\n type=int,\n help=\"The maximum total input sequence length after WordPiece tokenization. \\n\"\n \"Sequences longer than this will be truncated, and sequences shorter \\n\"\n \"than this will be padded.\")\n parser.add_argument(\"--no_cuda\",\n default=False,\n action='store_true',\n help=\"Whether not to use CUDA when available\")\n parser.add_argument(\"--gpu_id\",\n type=str,\n default='0',\n help=\"available gpu id\")\n parser.add_argument('--seed',\n type=int,\n default=42,\n help=\"random seed for initialization\")\n parser.add_argument(\"--num_batch\",\n default=1,\n type=int,\n help=\"Number of examples for each run.\")\n parser.add_argument(\"--batch_size\",\n default=20,\n type=int,\n help=\"The m in the paper.\")\n parser.add_argument(\"--batch_size_per_inference\",\n default=2,\n type=int,\n choices=[1,2,4,5,10,20],\n help=\"The batch size for each inference, you can choose an appropriate value from 1, 2, 4, 5, 10, 20 according to the model size and CUDA mamory.\")\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n if args.no_cuda or not torch.cuda.is_available():\n device = torch.device(\"cpu\")\n n_gpu = 0\n elif len(args.gpu_id) == 1:\n device = torch.device(\"cuda:%s\" % args.gpu_id)\n n_gpu = 1\n else:\n pass\n print(\"device: {} n_gpu: {}, distributed training: {}\".format(device, n_gpu, bool(n_gpu > 1)))\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n output_prefix = f\"{args.dataset_name}-{args.model_name}-context\"\n os.makedirs(args.output_dir, exist_ok=True)\n json.dump(args.__dict__, open(os.path.join(args.output_dir, output_prefix + '.args.json'), 'w'), sort_keys=True, indent=2)\n with open(args.data_path, \"r\", encoding=\"utf-8\") as fin:\n data = []\n for json_line in fin:\n line = json.loads(json_line)\n data.append(line)\n if args.TestCode:\n data = data[:10]\n tokenizer = AutoTokenizer.from_pretrained(args.model_path)\n print(\"***** CUDA.empty_cache() *****\")\n torch.cuda.empty_cache()\n model = AutoModelForCausalLM.from_pretrained(args.model_path, use_cache=True, low_cpu_mem_usage=True, device_map='auto')\n model.eval()\n tic = time.perf_counter()\n count = 0\n print(f\"Start process, dataset size: {len(data)}\")\n with jsonlines.open(os.path.join(args.output_dir, output_prefix + '.rlt' + '.jsonl'), 'w') as fw:\n for idx, example in enumerate(tqdm(data)):\n classes = example[\"classes\"].strip('[').strip(']').split(',')\n classes = [answer.strip().strip(\"\\'\").strip(\".\").strip() for answer in classes]\n answer_index = example[\"answer_index\"]\n trap_index = 1 if example[\"answer_index\"]==0 else 0\n answer_obj = classes[answer_index]\n trap_obj= classes[trap_index]\n prompt_with_context = example[\"prompt\"]\n prompt_without_context = prompt_with_context.split(\": \")[-1]\n res_dict = get_context_attr(idx, prompt_without_context, prompt_with_context, answer_obj, args, model, tokenizer, device)\n fw.write(res_dict)\n count += 1\n toc = time.perf_counter()\n time_str = f\"***** Costing time: {toc - tic:0.4f} seconds *****\"\n print(time_str)\nif __name__ == \"__main__\":\n main()" }, { "task_id": 1, "indent": 1, "completion_path": "./src/2_get_cns.py", "namespace": "src.2_get_cns.analysis_context_file", "type": "function", "signature_position": [ 21, 21 ], "body_position": [ 22, 35 ], "script": "\npython src/2_get_cns.py \\\n --result_dir results/attribution/ \\\n --cn_dir results/cn/ \\\n --model_name llama2-7b \\\n --dataset_name Memo\n", "latex_code": "\n\\subsection{Context-Aware Neuron Identification}\n\\label{3.2}\n\nBased on the calculated neuron attribution scores $\\mathrm{Attr}(n_i^l)$, we first retain neurons with scores above the threshold $t$, creating a coarse set of context-aware neurons. Then, for each example, we select the top $z$ neurons with the highest attribution scores as the candidate set. In our experiments, $t$ and $z$ are set to 10\\% and 20 respectively. Ultimately, we count the number of co-occurrences of neurons in all candidate sets, and we select the top $h$ neurons with the highest number of co-occurrences as context-aware neurons. These identified context-aware neurons are shared across all data instances.\n", "ReferenceCode_With_Comments": "\ncn_bag_list = []\n\nfor rlt in rlts_bag:\n ig_triplet = []\n\n ig = np.array(rlt[metric]) # shape: (layer_num, ffn_size)\n\n max_ig = ig.max()\n\n # -----------------------------------------------------------------------\n # Snippet 1: Here, neurons with attribution scores above max_ig * threshold_ratio\n # are retained. This corresponds to the LaTeX description where neurons\n # exceeding the threshold t form a coarse set of context-aware neurons.\n # -----------------------------------------------------------------------\n # [Begin Snippet 1]\n for i in range(ig.shape[0]):\n for j in range(ig.shape[1]):\n if ig[i][j] >= max_ig * threshold_ratio:\n # Record the layer index, neuron index, and the score\n ig_triplet.append([i, j, ig[i][j]])\n # [End Snippet 1]\n\n # -----------------------------------------------------------------------\n # Snippet 2: Sort the retained neurons in descending order of their scores\n # to mimic selecting the top z=20 context-aware neurons for each example.\n # -----------------------------------------------------------------------\n # [Begin Snippet 2]\n metric_triplets = ig_triplet\n metric_triplets.sort(key=lambda x: x[2], reverse=True)\n cn_bag = metric_triplets[:20]\n cn_bag_list.append(cn_bag)\n # [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Return the per-example list of candidate context-aware neurons.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nreturn cn_bag_list\n# [End Snippet 3]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX description does not mention the exact method for calculating the threshold. Specifically, the LaTeX lacks clarity on whether the threshold is computed globally across all layers or separately per layer. In the reference Python code, the threshold is explicitly calculated per example globally, using the maximum attribution score across all layers (max_ig) multiplied by threshold_ratio.\n - The LaTeX description omits explicit instructions on handling situations when no neurons exceed the threshold. The reference Python code implicitly avoids fallback logic, simply proceeding without explicitly selecting a fallback neuron.\n - The LaTeX description does not specify how the attribution scores \\(\\mathrm{Attr}(n_i^l)\\) are computed or provided as input to the algorithm. In the reference Python code, these scores are accessed via the `rlts_bag` input, specifically under the `metric` key (defaulting to `'all_attr_gold'`), as a NumPy array with shape `(layer_num, ffn_size)`. The workflow assumes that for each data instance, a precomputed array of attribution scores is available, representing the importance of each neuron across all layers.\n\n Mismatched Details:\n - The LaTeX description states that neurons with scores above the threshold \\( t = 10\\% \\) form a \"coarse set,\" followed by selecting the top \\( z = 20 \\) neurons per example, implying a global threshold applied across all layers and neurons per instance. The reference code implements this by computing a single `max_ig` across the entire attribution array (`ig.max()`) and applying the threshold uniformly (`max_ig * threshold_ratio`).\n - The LaTeX description specifies that the final selection of context-aware neurons involves counting \"co-occurrences\" of neurons across all candidate sets and selecting the top \\( h \\) neurons, suggesting a frequency-based criterion. The reference code supports this by returning per-instance candidate sets (`cn_bag_list`), implying an external step to count how often each neuron appears across these sets.\n \n", "Missing_details": [ "\n- The LaTeX description does not mention the exact method for calculating the threshold. Specifically, the LaTeX lacks clarity on whether the threshold is computed globally across all layers or separately per layer. In the reference Python code, the threshold is explicitly calculated per example globally, using the maximum attribution score across all layers (max_ig) multiplied by threshold_ratio.\n", "\n- The LaTeX description omits explicit instructions on handling situations when no neurons exceed the threshold. The reference Python code implicitly avoids fallback logic, simply proceeding without explicitly selecting a fallback neuron.\n", "\n- The LaTeX description does not specify how the attribution scores \\(\\mathrm{Attr}(n_i^l)\\) are computed or provided as input to the algorithm. In the reference Python code, these scores are accessed via the `rlts_bag` input, specifically under the `metric` key (defaulting to `'all_attr_gold'`), as a NumPy array with shape `(layer_num, ffn_size)`. The workflow assumes that for each data instance, a precomputed array of attribution scores is available, representing the importance of each neuron across all layers.\n" ], "Mismatched_details": [ "\n- The LaTeX description states that neurons with scores above the threshold \\( t = 10\\% \\) form a \"coarse set,\" followed by selecting the top \\( z = 20 \\) neurons per example, implying a global threshold applied across all layers and neurons per instance. The reference code implements this by computing a single `max_ig` across the entire attribution array (`ig.max()`) and applying the threshold uniformly (`max_ig * threshold_ratio`).\n", "\n- The LaTeX description specifies that the final selection of context-aware neurons involves counting \"co-occurrences\" of neurons across all candidate sets and selecting the top \\( h \\) neurons, suggesting a frequency-based criterion. The reference code supports this by returning per-instance candidate sets (`cn_bag_list`), implying an external step to count how often each neuron appears across these sets.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - rlts_bag (List[dict]): rlts_bag is a list of dictionaries, where each dictionary corresponds to a single data instance or analysis result.\n - 'idx' (int): A unique index identifier for the data instance.\n - 'wo_all_ffn_activations' (List[List]): Feed-forward network (FFN) activations for each layer under a \"without X\" setup. Organized as a list of lists, e.g., shape might be [layer_count, hidden_neurons].\n - 'w_all_ffn_activations' (List[List]): FFN activations under a \"with X\" setup, with the same dimensionality as 'wo_all_ffn_activations'. Shape: [layer_count, hidden_neurons].\n - 'all_attr_gold' (List[List]): Integrated or \"gold-standard\" attribution scores for each neuron in each layer. Same dimensional structure as the other activation keys.\n - metric (string): The specific key within each result object that stores the attribution scores. Defaults to 'all_attr_gold'.\n - threshold_ratio (float): The percentage ratio (e.g., 0.1 for 10%) used to determine whether a neuron's attribution score is significantly high.\n", "Arguments_list": [ { "name": "rlts_bag", "string": "\n- rlts_bag (List[dict]): rlts_bag is a list of dictionaries, where each dictionary corresponds to a single data instance or analysis result.\n - 'idx' (int): A unique index identifier for the data instance.\n - 'wo_all_ffn_activations' (List[List]): Feed-forward network (FFN) activations for each layer under a \"without X\" setup. Organized as a list of lists, e.g., shape might be [layer_count, hidden_neurons].\n - 'w_all_ffn_activations' (List[List]): FFN activations under a \"with X\" setup, with the same dimensionality as 'wo_all_ffn_activations'. Shape: [layer_count, hidden_neurons].\n - 'all_attr_gold' (List[List]): Integrated or \"gold-standard\" attribution scores for each neuron in each layer. Same dimensional structure as the other activation keys.\n", "dependency": null }, { "name": "metric", "string": "- metric (string): The specific key within each result object that stores the attribution scores. Defaults to 'all_attr_gold'.", "dependency": null }, { "name": "threshold_ratio", "string": "- threshold_ratio (float): The percentage ratio (e.g., 0.1 for 10%) used to determine whether a neuron's attribution score is significantly high.", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File Dependency: \n - None\n\n Cross-File Dependency: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - numpy.array\n", "list": [ "numpy.array" ] }, "Return": { "Return_String": "\nOutput Variables:\n - cn_bag_list (list[list]): The output is a list of 20 sub-lists (triplets), each representing a high-scoring neuron\u2019s attributes.\n - Sub-list Format: [layer_index, neuron_index, attribution_score]\n - layer_index (int): \n Identifies the specific layer in the neural network.\n - neuron_index (int): \n Identifies the specific neuron within that layer.\n - attribution_score (np.float64):\n The computed attribution/importance score for the neuron.\n", "Return_list": [ { "name": "cn_bag_list", "string": "\n- cn_bag_list (list[list]): The output is a list of 20 sub-lists (triplets), each representing a high-scoring neuron\u2019s attributes.\n - Sub-list Format: [layer_index, neuron_index, attribution_score]\n - layer_index (int): \n Identifies the specific layer in the neural network.\n - neuron_index (int): \n Identifies the specific neuron within that layer.\n - attribution_score (np.float64):\n The computed attribution/importance score for the neuron.\n", "dependency": null } ] }, "ori_python_file": "import os\nfrom tqdm import tqdm\nimport json\nimport numpy as np\nimport argparse\nfrom collections import Counter\nthreshold_ratio = 0.2\ndef pos_list2str(pos_list):\n return '@'.join([str(pos) for pos in pos_list])\n\ndef pos_str2list(pos_str):\n return [int(pos) for pos in pos_str.split('@')]\n\ndef stat(cn_bag_list, pos_type, type):\n ave_len = 0\n for cn_bag in cn_bag_list:\n ave_len += len(cn_bag)\n ave_len /= len(cn_bag_list)\n print(f'{type}\\'s {pos_type} has on average {ave_len} imp pos. ')\n\ndef analysis_context_file(rlts_bag, metric='all_attr_gold', threshold_ratio=0.1):\n cn_bag_list = []\n for rlt in rlts_bag:\n ig_triplet = []\n ig = np.array(rlt[metric])\n max_ig = ig.max()\n for i in range(ig.shape[0]):\n for j in range(ig.shape[1]):\n if ig[i][j] >= max_ig * threshold_ratio:\n ig_triplet.append([i, j, ig[i][j]])\n metric_triplets = ig_triplet\n metric_triplets.sort(key=lambda x: x[2], reverse=True)\n cn_bag = metric_triplets[:20]\n cn_bag_list.append(cn_bag)\n return cn_bag_list\n\nif __name__==\"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--result_dir\",\n type=str,\n required=True,\n help=\"The directory where important positions are stored.\")\n parser.add_argument(\"--cn_dir\",\n type=str,\n required=True,\n help=\"The directory where context neurons will be stored.\")\n parser.add_argument(\"--dataset_name\",\n type=str,\n default=None,\n required=True,\n help=\"Dataset name as output prefix to indentify each running of experiment.\")\n parser.add_argument(\"--model_name\",\n type=str,\n default=None,\n required=True,\n help=\"Model name as output prefix to indentify each running of experiment.\")\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n if not os.path.exists(args.cn_dir):\n os.makedirs(args.cn_dir)\n filename = f\"{args.dataset_name}-{args.model_name}-context.rlt.jsonl\"\n rlts_bag = []\n with open(os.path.join(args.result_dir, filename), 'r') as fr:\n for idx, line in enumerate(tqdm(fr.readlines())):\n try:\n example = json.loads(line)\n rlts_bag.append(example)\n except Exception as e:\n print(f\"Exception {e} happend in line {idx}\")\n print(f\"Total examples: {len(rlts_bag)}\")\n cn_bag_list= analysis_context_file(rlts_bag)\n type = filename.split('.')[0].split('-')[-1]\n stat(cn_bag_list, 'cn_bag', type)" }, { "task_id": 2, "indent": 1, "completion_path": "./src/utils/enhance_model.py", "namespace": "src.utils.enhance_model.enhance_neurons", "type": "function", "signature_position": [ 13, 13 ], "body_position": [ 14, 24 ], "script": "\npython src/3_enhance_and_evaluate.py \\\n --model_path meta-llama/Llama-2-7b-hf \\\n --data_path data/MemoTrap/memo-trap_classification_dev.jsonl \\\n --cn_dir results/cn \\\n --output_dir eval_results/dev_results/Memo/outputs \\\n --metric_dir eval_results/dev_results/Memo/metrics \\\n --dataset_name Memo \\\n --model_name llama2-7b \\\n --gpu_id 0 \\\n --max_seq_length 128 \\\n --enhance_cn_num 1 \\\n --enhance_strength 16\n", "latex_code": "\n\\subsection{Context-Aware Neuron Reweighting}\n\\label{3.3}\nIn order to make LLMs generate outputs that are more faithful to the context, we enhance the identified context-aware neurons. We adopt a simple yet effective enhancement measure: \n\\begin{equation}\n \\boldsymbol{\\hat{W}}(n_i^l) = \\beta \\boldsymbol{W}(n_i^l) ,\n\\end{equation}\ni.e., amplifying the weights of these neurons to $\\beta$ (i.e., enhancement strength) times their original weights. This adjustment amplifies the role these neurons play as information flows through them, thus enhancing their influence on the model's output.\n", "ReferenceCode_With_Comments": "\ncns = []\ncn_counter = Counter()\n\nfor cn_bag in cn_bag_list:\n for cn in cn_bag:\n cn_counter.update([pos_list2str(cn[:2])])\n\n# ---------------------------------------------------------------------------\n# Snippet 1: We retrieve the most frequent neurons based on a threshold\n# ('args.enhance_cn_num'). These are the context-aware neurons selected for\n# reweighting, aligning with the notion of targeting neurons that\n# significantly process the context.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nmost_common_cn = cn_counter.most_common(args.enhance_cn_num)\n\ncns = [pos_str2list(cn_str[0]) for cn_str in most_common_cn]\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: For each identified neuron, we multiply its weights by\n# 'enhance_strength' (\u03b2). This implements the LaTeX equation:\n# \\(\\boldsymbol{\\hat{W}}(n_i^l) = \\beta \\boldsymbol{W}(n_i^l)\\).\n# Returns the modified model and the most common context-aware neurons.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nfor layer, pos in cns:\n with torch.no_grad():\n model.model.layers[layer].mlp.down_proj.weight[:, pos] *= args.enhance_strength\n\nreturn model, most_common_cn\n# [End Snippet 2]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX description does not specify the process of identifying and selecting the top context-aware neurons for enhancement. In the reference Python code, this involves a multi-step workflow: first, a `Counter` object (`cn_counter`) accumulates the frequency of neuron occurrences across all sub-lists in `cn_bag_list` by converting neuron positions (`[layer_index, neuron_index]`) into string keys (e.g., \"19@7471\") using `pos_list2str`. Then, the `most_common(args.enhance_cn_num)` method retrieves the top `args.enhance_cn_num` most frequent neurons, and these string keys are converted back to lists (`[layer, pos]`) using `pos_str2list` for weight modification.\n - The LaTeX description omits the specific structure of the neural network layer and the exact weight tensor to be modified. In the reference code, the enhancement targets the `down_proj.weight` tensor within the MLP component of each layer (`model.model.layers[layer].mlp.down_proj.weight`), modifying an entire column (`[:, pos]`) corresponding to the neuron at position `pos`.\n\n Mismatched Details:\n - The LaTeX description implies a straightforward scaling of neuron weights (\\(\\boldsymbol{\\hat{W}}(n_i^l) = \\beta \\boldsymbol{W}(n_i^l)\\)), suggesting that the enhancement applies to a single neuron\u2019s weight vector without specifying its scope or context within the network. In contrast, the reference Python code applies this scaling to an entire column of the `down_proj.weight` matrix (`[:, pos]`), which represents the neuron\u2019s outgoing weights across all input dimensions in the MLP\u2019s output projection.\n", "Missing_details": [ "The LaTeX description does not specify the process of identifying and selecting the top context-aware neurons for enhancement. In the reference Python code, this involves a multi-step workflow: first, a `Counter` object (`cn_counter`) accumulates the frequency of neuron occurrences across all sub-lists in `cn_bag_list` by converting neuron positions (`[layer_index, neuron_index]`) into string keys (e.g., \"19@7471\") using `pos_list2str`. Then, the `most_common(args.enhance_cn_num)` method retrieves the top `args.enhance_cn_num` most frequent neurons, and these string keys are converted back to lists (`[layer, pos]`) using `pos_str2list` for weight modification.", "The LaTeX description omits the specific structure of the neural network layer and the exact weight tensor to be modified. In the reference code, the enhancement targets the `down_proj.weight` tensor within the MLP component of each layer (`model.model.layers[layer].mlp.down_proj.weight`), modifying an entire column (`[:, pos]`) corresponding to the neuron at position `pos`." ], "Mismatched_details": [ "\n- The LaTeX description implies a straightforward scaling of neuron weights (\\(\\boldsymbol{\\hat{W}}(n_i^l) = \\beta \\boldsymbol{W}(n_i^l)\\)), suggesting that the enhancement applies to a single neuron\u2019s weight vector without specifying its scope or context within the network. In contrast, the reference Python code applies this scaling to an entire column of the `down_proj.weight` matrix (`[:, pos]`), which represents the neuron\u2019s outgoing weights across all input dimensions in the MLP\u2019s output projection.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - cn_bag_list (list[list]): The output is a list of 20 sub-lists (triplets), each representing a high-scoring neuron\u2019s attributes.\n - Sub-list Format: [layer_index, neuron_index, attribution_score]\n - layer_index (int): \n Identifies the specific layer in the neural network.\n - neuron_index (int): \n Identifies the specific neuron within that layer.\n - attribution_score (np.float64):\n The computed attribution/importance score for the neuron.\n - args (Namespace): Holds the configuration and hyperparameters necessary for neuron enhancement.\n - args.enhance_cn_num: Number of top context neurons to be enhanced.\n - args.enhance_strength: Multiplicative factor by which to scale the neuron weights.\n - model (transformers.LLamaForCausalLM): The LLM whose neuron weights need to be modified to emphasize context-aware neurons.\n", "Arguments_list": [ { "name": "cn_bag_list", "string": "\n- cn_bag_list (list[list]): The output is a list of 20 sub-lists (triplets), each representing a high-scoring neuron\u2019s attributes.\n - Sub-list Format: [layer_index, neuron_index, attribution_score]\n - layer_index (int): \n Identifies the specific layer in the neural network.\n - neuron_index (int): \n Identifies the specific neuron within that layer.\n - attribution_score (np.float64):\n The computed attribution/importance score for the neuron.\n", "dependency": null }, { "name": "args", "string": "\n- args (Namespace): Holds the configuration and hyperparameters necessary for neuron enhancement.\n - args.enhance_cn_num: Number of top context neurons to be enhanced.\n - args.enhance_strength: Multiplicative factor by which to scale the neuron weights.\n", "dependency": null }, { "name": "model", "string": "\n- model (transformers.LLamaForCausalLM): The LLM whose neuron weights need to be modified to emphasize context-aware neurons.\n", "dependency": null } ] }, "dependency": { "string": "\nRepository Dependencies:\n Intra-File Dependency:\n - pos_list2str\n - pos_str2list\n\n Cross-File Dependency: \n - None\n", "intra_file": [ "pos_list2str", "pos_str2list" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.no_grad\n - collections.Counter\n", "list": [ "torch.no_grad", "collections.Counter" ] }, "Return": { "Return_String": "\nOutput Variables:\n - model (transformers.LLamaForCausalLM): The same model passed in as input, but with updated (enhanced) neuron weights for the top identified context neurons.\n - most_common_cn (list[tuple]): A list of tuples indicating the most frequently occurring neurons (layer, position) and their associated counts. Each tuple generally follows the format: ((,), ).\n For example, for the tuple (\"19@7471\", 6):\n - The first element in the tuple, e.g. \"19@7471\", is a string representing a specific neuron, where:\n - The part before the @ (in this case, 19) corresponds to the neuron\u2019s layer index.\n - The part after the @ (in this case, 7471) corresponds to the neuron\u2019s position (index) within that layer.\n - The second element in the tuple (in this example, 6) indicates the frequency or count of how many times that particular neuron appeared across the context-neuron bags (cn_bag_list).\n", "Return_list": [ { "name": "model", "string": "\n- model (transformers.LLamaForCausalLM): The same model passed in as input, but with updated (enhanced) neuron weights for the top identified context neurons.\n", "dependency": null }, { "name": "most_common_cn", "string": "\n- most_common_cn (list[tuple]): A list of tuples indicating the most frequently occurring neurons (layer, position) and their associated counts. Each tuple generally follows the format: ((,), ).\n For example, for the tuple (\"19@7471\", 6):\n - The first element in the tuple, e.g. \"19@7471\", is a string representing a specific neuron, where:\n - The part before the @ (in this case, 19) corresponds to the neuron\u2019s layer index.\n - The part after the @ (in this case, 7471) corresponds to the neuron\u2019s position (index) within that layer.\n - The second element in the tuple (in this example, 6) indicates the frequency or count of how many times that particular neuron appeared across the context-neuron bags (cn_bag_list).\n", "dependency": null } ] }, "ori_python_file": "import torch\nimport json\nimport random\nimport os\nfrom collections import Counter\n\ndef pos_list2str(pos_list):\n return '@'.join([str(pos) for pos in pos_list])\n\ndef pos_str2list(pos_str):\n return [int(pos) for pos in pos_str.split('@')]\n\ndef enhance_neurons(cn_bag_list, args, model):\n cns = []\n cn_counter = Counter()\n for cn_bag in cn_bag_list:\n for cn in cn_bag:\n cn_counter.update([pos_list2str(cn[:2])])\n most_common_cn = cn_counter.most_common(args.enhance_cn_num)\n cns = [pos_str2list(cn_str[0]) for cn_str in most_common_cn]\n for layer, pos in cns:\n with torch.no_grad():\n model.model.layers[layer].mlp.down_proj.weight[:, pos] *= args.enhance_strength\n return model, most_common_cn" } ] }, { "paper_id": 13, "paper_details": { "title": "RouterDC: Query-Based Router by Dual Contrastive Learning for Assembling Large Language Models", "url": "https://arxiv.org/abs/2409.19886" }, "enviorment_name": "RouterDC", "repo_original_url": "https://github.com/shuhao02/routerdc", "project_path": "Benchmark/13-RouterDC-main/RouterDC-main", "file_organization": "\nRouterDC-main/\n cluster_generate.py\n convert_dataset_7_model.ipynb\n datasets/\n routerbench_cluster/\n arc_challenge_train.csv\n gsm8k_train.csv\n hellaswag_train.csv\n mbpp_train.csv\n mmlu_train.csv\n winograde_train.csv\n routerbench_zs/\n arc_challenge_test.csv\n arc_challenge_train.csv\n gsm8k_test.csv\n gsm8k_train.csv\n hellaswag_test.csv\n hellaswag_train.csv\n mbpp_test.csv\n mbpp_train.csv\n mmlu_test.csv\n mmlu_train.csv\n winograde_test.csv\n winograde_train.csv\n split2_model7/\n arc_challenge_test.json\n arc_challenge_train.json\n arc_easy_test.json\n arc_easy_train.json\n ceval.json\n cmmlu_test.json\n cmmlu_train.json\n gsm8k-test.json\n gsm8k-train.json\n humaneval_test.json\n humaneval_train.json\n javascript.json\n MATH_prealgebra.json\n mbpp.json\n mmlu_test.json\n mmlu_train.json\n split2_model7_cluster/\n arc_challenge_train.json\n cmmlu_train.json\n gsm8k-train.json\n humaneval_train.json\n mmlu_train.json\n env.sh\n eval_lora_retriever.py\n eval_scripts/\n auto_eval_alltask.sh\n auto_eval_humanevalpack.sh\n eval_alltask.sh\n eval_humanevalpack_cpp.sh\n eval_humanevalpack_java.sh\n eval_humanevalpack_js.sh\n evaluation_router.py\n readme.md\n src/\n cluster_generate.ipynb\n train_router_mdeberta.py\n train_router_mdeberta_routerbench.py\n train_scripts/\n router_train_routerbench.sh\n router_train.sh\n utils/\n meters.py\n", "latex_code_path": "Benchmark/13-RouterDC-main/arXiv-2409.19886v1", "task_details": [ { "task_id": 0, "indent": 2, "script": "\npython train_router_mdeberta_routerbench.py --training_steps 1000 --top_k 4 --last_k 4 --learning_rate 5e-5 --eval_steps 100 --tempreture 1 --similarity_function cos --sample_loss_weight 0 --cluster_loss_weight 1 --seed 7 --final_eval --cost_rate 0 --data_paths ./datasets/routerbench_cluster/gsm8k_train.csv ./datasets/routerbench_cluster/hellaswag_train.csv ./datasets/routerbench_cluster/mbpp_train.csv ./datasets/routerbench_cluster/mmlu_train.csv ./datasets/routerbench_cluster/winograde_train.csv ./datasets/routerbench_cluster/arc_challenge_train.csv --test_data_paths ./datasets/routerbench_zs/gsm8k_test.csv ./datasets/routerbench_zs/hellaswag_test.csv ./datasets/routerbench_zs/mbpp_test.csv ./datasets/routerbench_zs/mmlu_test.csv ./datasets/routerbench_zs/winograde_test.csv ./datasets/routerbench_zs/arc_challenge_test.csv --save_path ./logs/paper_result/routerbench/cr_0_slw_0_tk_4_lk_4_lr_5e-5_step_1000_t_1_seed_7 --TestCode \n", "latex_code": "\nWe draw inspiration from contrastive learning \\citep{ni2021sentence, izacard2021unsupervised} and propose a sample-LLM contrastive loss to learn the router.\nFor a query $\\vx_i$,\nwe construct its positive LLMs index set $\\hI_{i}^{+}$ and its negative LLMs index set $\\hI_{i}^{-}$ based on the scores $\\{s_{i}^{(t)}:t=1,\\dots,T\\}$ as:\n$\\hI_{i}^{+}$ consists of the indices of LLMs corresponding to the top-$K_+$ scores,\nwhile $\\hI_{i}^{-}$ consists of the indices of LLMs corresponding to the bottom-$K_-$ scores with $s_{i}^{(t)} < 0.5$.\nNote that $K_+$ can be larger than $1$ ($K_+=3$ in our experiments) as there can be multiple LLMs that are suitable for a query in practice.\nWe expect the router to pull the query embedding $\\hE(\\vx_i; \\vw)$ closer to the positive LLMs' embeddings $\\{\\vk_{t_+}: t_+\\in \\hI_{i}^{+}\\}$\n% embeddings of its positive LLMs $\\hI_{i}^{+}$ \nwhile pushing apart from the negative LLMs' embeddings $\\{\\vk_{t_-}: t_-\\in \\hI_{i}^{-}\\}$.\n% embeddings of its negative LLMs $\\hI_{i}^{-}$.\nTo this end, we propose the sample-LLM contrastive loss as\n\\begin{align}\n\\label{eqa:sample-LLM-loss}\n\\hL_{\\text{sample-LLM}}(\\vx_i, y_i; \\vtheta) = \\sum_{t_{+} \\in \\hI_{i}^+} - \\log \\frac{ e^{\\text{sim}(\\hE(\\vx_{i}; \\vw), \\vk_{t_{+}})} }{e^{\\text{sim}(\\hE(\\vx_{i}; \\vw), \\vk_{t_{+}})} + \\sum_{t_- \\in \\hI_i^-} e^{\\text{sim}(\\hE(\\vx_{i}; \\vw), \\vk_{t_-})} }.\n\\end{align}\n", "completion_path": "./train_router_mdeberta_routerbench.py", "namespace": "train_router_mdeberta_routerbench.RouterModule.compute_sample_llm_loss", "type": "method", "signature_position": [ 101, 101 ], "body_position": [ 102, 116 ], "ReferenceCode_With_Comments": "\nloss = 0\n# ---------------------------------------------------------------------------\n# Snippet 1: Identify top-K+ positive and bottom-K- negative LLM indices\n# Corresponds to constructing I_i^+ and I_i^- sets.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\ntop_index_true, top_index = index_true.sort(dim=-1, descending=True)\nlast_index_true, negtive_index = index_true.topk(k=last_k, largest=False, dim=-1)\n# [End Snippet 1]\n\n# -----------------------------------------------------------------------------\n# Snippet 2: We iterate over the top-K_+ LLMs for each query to gather the\n# positive set (hI_i^+) from the LaTeX. The mask ensures only queries\n# with sufficiently large \"true\" scores are accounted for as positives.\n# -----------------------------------------------------------------------------\n# [Begin Snippet 2]\nfor i in range(top_k):\n positive_index = top_index[:, i].view(-1, 1)\n\n mask = torch.where(top_index_true[:, i].view(-1, 1) > 0, 1, 0)\n# [End Snippet 2]\n\n # -------------------------------------------------------------------------\n # Snippet 3: We collect the similarity values for positives (top_x) and\n # negatives (last_x). According to the LaTeX, the negatives are those\n # with the smallest scores (and s_i^(t)<0.5). Here, we replace\n # non-qualifying entries with -\u221e to exclude them from the \n # exponential sum.\n # -------------------------------------------------------------------------\n # [Begin Snippet 3]\n top_x = torch.gather(x, 1, positive_index)\n last_x = torch.gather(x, 1, negtive_index)\n last_x = torch.where(last_index_true > 0.5, float(\"-inf\"), last_x)\n # [End Snippet 3]\n\n # -------------------------------------------------------------------------\n # Snippet 4: We compute the contrastive objective by combining positive\n # and negative similarities, applying Softmax, and taking the log\n # probability of the positive term. This corresponds to the \n # - log( e^{sim(...)} / [ e^{sim(...)} + sum(e^{sim(...)} ) ] )\n # definition in the LaTeX snippet, summing for each positive index.\n # -------------------------------------------------------------------------\n # [Begin Snippet 4]\n temp_x = torch.concat([top_x, last_x], dim=-1)\n softmax_x = nn.Softmax(dim=-1)(temp_x)\n log_x = torch.log(softmax_x[:, 0])\n log_x = log_x * mask\n loss += torch.mean(-log_x)\n # [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Return the total accumulated loss.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nreturn loss\n# [End Snippet 5]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX description does not specify a filtering mechanism for positive LLMs based on a threshold applied to the `index_true` values, which is present in the reference Python code. In the reference code, a mask is created (`mask = torch.where(top_index_true[:, i].view(-1, 1) > 0, 1, 0)`) to selectively include only those positive LLMs whose corresponding `index_true` values exceed 0 in the loss computation. This workflow involves: (1) sorting the `index_true` tensor to identify the top `K_+` indices, (2) evaluating each of these indices against a threshold (0), (3) generating a binary mask that zeros out contributions from positives failing the threshold, and (4) applying this mask to the log-probability terms (`log_x * mask`) before averaging.\n\n Mismatched Details:\n - The handling of negative LLMs in the LaTeX description states that `\ud835\udd40\u207b` consists of indices with scores `s_i^(t) < 0.5`, but the reference Python code applies this threshold by setting non-qualifying negative scores to `-\u221e` (`last_x = torch.where(last_index_true > 0.5, float(\"-inf\"), last_x)`), which is not explicitly described in LaTeX. The LaTeX implies a simple selection of the bottom `K_-` scores below 0.5, but the reference code\u2019s workflow: (1) identifies the bottom `K_-` indices via `topk(..., largest=False)`, (2) gathers their scores, (3) checks the corresponding `index_true` (or scores) against 0.5, and (4) replaces those exceeding 0.5 with `-\u221e` to exclude them from the exponential sum in the softmax.\n - The LaTeX description implies that the contrastive loss is computed as a sum over positive LLMs with a denominator including only the positive term and the sum of negative terms (`e^{sim(...)} + \u2211 e^{sim(...)}`), but the reference Python code implements this differently by using a softmax over all terms (positive and negatives combined). In LaTeX, the loss for each positive LLM is `-log(e^{sim(hE(x_i), k_{t_+})} / (e^{sim(hE(x_i), k_{t_+})} + \u2211 e^{sim(hE(x_i), k_{t_-})}))`, suggesting a direct ratio of exponentials. However, the reference code: (1) concatenates the positive score (`top_x`) with all negative scores (`last_x`), (2) applies softmax across this combined tensor, and (3) takes the log of the first element (the positive\u2019s normalized probability).\n", "Missing_details": [ "\n- The LaTeX description does not specify a filtering mechanism for positive LLMs based on a threshold applied to the `index_true` values, which is present in the reference Python code. In the reference code, a mask is created (`mask = torch.where(top_index_true[:, i].view(-1, 1) > 0, 1, 0)`) to selectively include only those positive LLMs whose corresponding `index_true` values exceed 0 in the loss computation. This workflow involves: (1) sorting the `index_true` tensor to identify the top `K_+` indices, (2) evaluating each of these indices against a threshold (0), (3) generating a binary mask that zeros out contributions from positives failing the threshold, and (4) applying this mask to the log-probability terms (`log_x * mask`) before averaging.\n" ], "Mismatched_details": [ "\n- The LaTeX description does not specify a filtering mechanism for positive LLMs based on a threshold applied to the `index_true` values, which is present in the reference Python code. In the reference code, a mask is created (`mask = torch.where(top_index_true[:, i].view(-1, 1) > 0, 1, 0)`) to selectively include only those positive LLMs whose corresponding `index_true` values exceed 0 in the loss computation. This workflow involves: (1) sorting the `index_true` tensor to identify the top `K_+` indices, (2) evaluating each of these indices against a threshold (0), (3) generating a binary mask that zeros out contributions from positives failing the threshold, and (4) applying this mask to the log-probability terms (`log_x * mask`) before averaging.\n", "\n- The LaTeX description implies that the contrastive loss is computed as a sum over positive LLMs with a denominator including only the positive term and the sum of negative terms (`e^{sim(...)} + \u2211 e^{sim(...)}`), but the reference Python code implements this differently by using a softmax over all terms (positive and negatives combined). In LaTeX, the loss for each positive LLM is `-log(e^{sim(hE(x_i), k_{t_+})} / (e^{sim(hE(x_i), k_{t_+})} + \u2211 e^{sim(hE(x_i), k_{t_-})}))`, suggesting a direct ratio of exponentials. However, the reference code: (1) concatenates the positive score (`top_x`) with all negative scores (`last_x`), (2) applies softmax across this combined tensor, and (3) takes the log of the first element (the positive\u2019s normalized probability).\n" ] }, "Arguments": { "string": "\nInput Variables:\n - x (torch.Tensor, shape: [batch_size, T], where T is the total number of LLMs.): A tensor containing the scores or similarity values (e.g., sim(hE(x), k_t)) for each query-LLM pair.\n - index_true (torch.Tensor, shape: [batch_size, T]): A tensor that helps identify the relative ordering of LLMs for each query, with higher values indicating more suitable LLMs for the query.\n - top_k (int): The number of top-scoring LLMs to treat as 'positives' for each query, corresponding to K_+ in the LaTeX formulation.\n - last_k (int): The number of bottom-scoring LLMs to treat as 'negatives' for each query, corresponding to K_- in the LaTeX formulation.\n", "Arguments_list": [ { "name": "x", "string": "- x (torch.Tensor, shape: [batch_size, T], where T is the total number of LLMs.): A tensor containing the scores or similarity values (e.g., sim(hE(x), k_t)) for each query-LLM pair.", "dependency": null }, { "name": "index_true", "string": "- index_true (torch.Tensor, shape: [batch_size, T]): A tensor that helps identify the relative ordering of LLMs for each query, with higher values indicating more suitable LLMs for the query.", "dependency": null }, { "name": "top_k", "string": "- top_k (int): The number of top-scoring LLMs to treat as \"positives\" for each query, corresponding to K_+ in the LaTeX formulation.", "dependency": null }, { "name": "last_k", "string": "- last_k (int): The number of bottom-scoring LLMs to treat as \"negatives\" for each query, corresponding to K_- in the LaTeX formulation.", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File dependency: \n - None\n\n Cross-File dependency: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.log\n - torch.mean\n - torch.where \n - torch.concat\n - torch.nn.Softmax\n - torch.gather \n\n", "list": [ "torch.log", "torch.mean", "torch.where", "torch.concat", "torch.nn.Softmax", "torch.gather" ] }, "Return": { "Return_String": "\nOutput Variables:\n - loss (torch.Tensor, scalar): The final computed sample-LLM contrastive loss (scalar) that aims to pull the query closer to the positive LLM embeddings and push it away from the negative LLM embeddings. \n", "Return_list": [ { "name": "loss", "string": "\n- loss (torch.Tensor, scalar): The final computed sample-LLM contrastive loss (scalar) that aims to pull the query closer to the positive LLM embeddings and push it away from the negative LLM embeddings.\n", "dependency": null } ] }, "ori_python_file": "import argparse\nimport json\nimport pandas as pd\nimport os\nimport random\nimport torch.nn as nn\nimport torch.optim\nfrom torch.utils.data import Dataset, DataLoader, ConcatDataset\nfrom tqdm import tqdm\nfrom transformers import AutoTokenizer, DebertaV2Model, DebertaV2Tokenizer\nfrom utils.meters import AverageMeter\nimport numpy as np\nimport torch\ndef setup_seed(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n np.random.seed(seed)\n random.seed(seed)\n torch.backends.cudnn.deterministic = True\n\nclass RouterDataset(Dataset):\n \n def __init__(self,\n data_path,\n source_max_token_len: int = 512,\n target_max_token_len: int = 512,\n size: int = None,\n dataset_id = 0,\n cost_rate = 0,\n ):\n if data_path.endswith('.json'):\n self.data = pd.read_json(data_path).dropna()\n elif data_path.endswith('.pkl'):\n self.data = pd.read_pickle(data_path).dropna()\n elif data_path.endswith('.csv'):\n self.data = pd.read_csv(data_path).dropna()\n if size:\n while(len(self.data) < size):\n self.data = pd.concat([self.data, self.data])\n self.data = self.data[:size]\n self.tokenizer = None\n self.router_node = ['WizardLM/WizardLM-13B-V1.2', 'claude-instant-v1', 'claude-v1', 'claude-v2', 'gpt-3.5-turbo-1106', 'gpt-4-1106-preview', 'meta/code-llama-instruct-34b-chat', 'meta/llama-2-70b-chat', 'mistralai/mistral-7b-chat', 'mistralai/mixtral-8x7b-chat', 'zero-one-ai/Yi-34B-Chat']\n self.source_max_token_len = source_max_token_len\n self.target_max_token_len = target_max_token_len\n self.dataset_id = dataset_id\n self.cost_rate = cost_rate\n \n def __getitem__(self, index):\n data_point = self.data.iloc[index]\n cost_index = [ index + \"|total_cost\" for index in self.router_node]\n scores = torch.tensor(data_point[self.router_node].values.tolist())\n costs = torch.tensor(data_point[cost_index].values.tolist())\n scores = scores - costs * self.cost_rate\n question = data_point['prompt'][:1400]\n question_id = self.tokenizer(\n question,\n max_length=self.target_max_token_len,\n padding=\"max_length\",\n truncation=True,\n return_attention_mask=True,\n add_special_tokens=True,\n return_tensors=\"pt\",\n )\n question_id['input_ids'] = question_id.input_ids.flatten()\n question_id['attention_mask'] = question_id.attention_mask.flatten()\n cluster_id = data_point['cluster_id'] if \"cluster_id\" in data_point else 0\n return question_id, scores, self.dataset_id, cluster_id, costs\n \n def __len__(self):\n return len(self.data)\n \n def register_tokenizer(self, tokenizer):\n self.tokenizer = tokenizer\n\nclass RouterModule(nn.Module):\n \n def __init__(self, backbone, hidden_state_dim=768, node_size=3, similarity_function = \"cos\"):\n super(RouterModule, self).__init__()\n self.backbone = backbone\n self.hidden_state_dim = hidden_state_dim\n self.node_size = node_size\n self.embeddings = nn.Embedding(node_size, hidden_state_dim)\n std_dev = 0.78\n with torch.no_grad():\n nn.init.normal_(self.embeddings.weight, mean=0, std=std_dev)\n self.similarity_function = similarity_function\n \n def compute_similarity(self, input1, input2):\n if self.similarity_function == \"cos\":\n return (input1 @ input2.T) / (torch.norm(input1,dim=1).unsqueeze(1) * torch.norm(input2,dim=1).unsqueeze(0))\n else:\n return input1 @ input2.T\n \n def forward(self, t=1, **input_kwargs):\n x = self.backbone(**input_kwargs)\n hidden_state = x['last_hidden_state'][:,0,:]\n x = self.compute_similarity(hidden_state, self.embeddings.weight)\n x = x / t\n return x, hidden_state\n \n def compute_sample_llm_loss(self, x, index_true, top_k, last_k):\n loss = 0\n top_index_true, top_index = index_true.sort(dim=-1, descending=True)\n last_index_true, negtive_index = index_true.topk(k=last_k, largest=False, dim=-1)\n for i in range(top_k):\n positive_index = top_index[:, i].view(-1, 1)\n mask = torch.where(top_index_true[:, i].view(-1, 1) > 0, 1, 0)\n top_x = torch.gather(x, 1, positive_index)\n last_x = torch.gather(x, 1, negtive_index)\n last_x = torch.where(last_index_true > 0.5, float(\"-inf\"), last_x)\n temp_x = torch.concat([top_x, last_x], dim=-1)\n softmax_x = nn.Softmax(dim=-1)(temp_x)\n log_x = torch.log(softmax_x[:, 0])\n log_x = log_x * mask\n loss += torch.mean(-log_x)\n return loss\n \n def compute_sample_sample_loss_with_task_tag(self, hidden_state, dataset_ids, t, H=3):\n similar_score = self.compute_similarity(hidden_state, hidden_state)\n last_k2 = H\n all_index = []\n for dataset_id in dataset_ids:\n positive_indexs = torch.nonzero(dataset_ids == dataset_id)\n select_positive_index = random.choice(positive_indexs)\n negtive_indexs = torch.nonzero(dataset_ids != dataset_id)\n if len(negtive_indexs) < last_k2:\n print(\"len of negtive index is smaller than last_k2. dataset_id:\", dataset_id)\n continue\n index_of_negtive_indexs = random.sample(range(0, len(negtive_indexs)), last_k2)\n select_negtive_index = negtive_indexs[index_of_negtive_indexs].squeeze()\n select_index = torch.concat([select_positive_index, select_negtive_index])\n all_index.append(select_index)\n all_index = torch.stack(all_index)\n rearrange_similar_score = torch.gather(similar_score, 1, all_index)\n similar_score = similar_score / t\n softmax_sample_x = torch.softmax(rearrange_similar_score, dim=-1)\n log_sample_x = torch.log(softmax_sample_x)\n loss = torch.mean(-log_sample_x[:,0])\n return loss\n \n def compute_orthogonal_regular_loss(self):\n embedding_similarity = self.compute_similarity(self.embeddings.weight, self.embeddings.weight)\n loss = torch.norm(embedding_similarity - torch.eye(self.node_size).type_as(embedding_similarity))\n return loss\n \n def compute_cluster_loss(self, hidden_state, cluster_ids, t, H=3):\n similar_score = self.compute_similarity(hidden_state, hidden_state)\n last_k2 = H\n all_index = []\n for cluster_id in cluster_ids:\n positive_indexs = torch.nonzero(cluster_ids == cluster_id)\n select_positive_index = random.choice(positive_indexs)\n negtive_indexs = torch.nonzero(cluster_ids != cluster_id)\n if len(negtive_indexs) < last_k2:\n print(\"len of negtive index is smaller than last_k2. cluster_id:\", cluster_id)\n continue\n index_of_negtive_indexs = random.sample(range(0, len(negtive_indexs)), last_k2)\n select_negtive_index = negtive_indexs[index_of_negtive_indexs].view(-1)\n select_index = torch.concat([select_positive_index, select_negtive_index])\n all_index.append(select_index)\n all_index = torch.stack(all_index)\n rearrange_similar_score = torch.gather(similar_score, 1, all_index)\n similar_score = similar_score / t\n softmax_sample_x = torch.softmax(rearrange_similar_score, dim=-1)\n log_sample_x = torch.log(softmax_sample_x)\n loss = torch.mean(-log_sample_x[:, 0])\n return loss\n\ndef evaluation(router_model, dataset_paths, dataset_types, tokenizer, batch_size, device):\n result = {}\n with torch.no_grad():\n for index, data_path in enumerate(dataset_paths):\n test_dataset = RouterDataset(data_path=data_path)\n test_dataset.register_tokenizer(tokenizer)\n data_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=True)\n correct_predict = 0\n correct = 0\n sum_cost = 0\n for batch in data_loader:\n inputs, scores, _, _, costs = batch\n inputs = inputs.to(device)\n scores = scores.to(device)\n costs = costs.to(device)\n scores = scores - test_dataset.cost_rate * costs\n x, _ = router_model.forward(**inputs)\n softmax_x = nn.Softmax(dim=1)(x)\n _, max_index = torch.max(softmax_x, dim=1)\n _, target_max_index = torch.max(scores, dim=1)\n equals = max_index.eq(target_max_index)\n select_costs = torch.gather(costs, 1, max_index.unsqueeze(1)).float()\n sum_cost += select_costs.sum().item()\n correct += equals.sum().item()\n mask = torch.zeros_like(scores)\n mask = mask.scatter_(1, max_index.unsqueeze(1), 1)\n if torch.isnan(mask).any() or torch.isnan(scores).any():\n print(\"scores\", scores)\n print(\"max_index\", max_index)\n print(\"target_max_index\", target_max_index)\n print(\"equals\", equals)\n correct_predict += (scores * mask).sum().item()\n acc_predict = correct_predict/len(test_dataset)\n acc = correct/len(test_dataset)\n avg_costs = sum_cost / len(test_dataset)\n print(f\"acc_{data_path}:\", acc_predict)\n print(\"acc\", acc)\n print(\"avg_cost\", avg_costs)\n result[data_path] = [acc, acc_predict, avg_costs]\n return result\n\nif __name__ == '__main__':\n device = \"cuda\"\n parser = argparse.ArgumentParser(description=\"the training code for router\")\n parser.add_argument('--data_paths', nargs='+')\n parser.add_argument('--test_data_paths',nargs='+')\n parser.add_argument('--test_data_type', nargs='+')\n parser.add_argument('--final_eval_data_paths', nargs='+', default=['./datasets/routerbench_zs/gsm8k_test.csv','./datasets/routerbench_zs/hellaswag_test.csv','./datasets/routerbench_zs/mbpp_test.csv','./datasets/routerbench_zs/mmlu_test.csv','./datasets/routerbench_zs/winograde_test.csv','./datasets/routerbench_zs/arc_challenge_test.csv'])\n parser.add_argument('--final_eval_data_type', nargs='+', default=[\"probability\", \"probability\", \"multi_attempt\",\"probability\", \"multi_attempt\", \"multi_attempt\", \"probability\", \"probability\"])\n parser.add_argument('--batch_size', type=int, default=64)\n parser.add_argument('--training_steps', type=int, default=100)\n parser.add_argument('--eval_steps',type=int,default=1000)\n parser.add_argument('--learning_rate', type=float, default=0.00005)\n parser.add_argument('--save_path', type=str, default='./logs/router_debug/')\n parser.add_argument('--top_k', type=int, default=2)\n parser.add_argument('--last_k',type=int, default=3)\n parser.add_argument('--tempreture', type=int, default=1)\n parser.add_argument('--gradient_accumulation', type=int, default=1)\n parser.add_argument('--similarity_function', type=str, default='cos')\n parser.add_argument('--sample_loss_weight', type=float, default=0)\n parser.add_argument('--regular_loss_weight', type=float, default=0)\n parser.add_argument('--cluster_loss_weight', type=float, default=0)\n parser.add_argument('--H', type=int, default=3)\n parser.add_argument('--final_eval', action=\"store_true\")\n parser.add_argument('--seed', type=int, default=42)\n parser.add_argument('--training_samples_per_dataset', type=int, default=1000)\n parser.add_argument('--cost_rate', type=float, default=0)\n parser.add_argument('--TestCode', action=\"store_true\")\n args = parser.parse_args()\n os.makedirs(args.save_path, exist_ok=True)\n setup_seed(args.seed)\n tokenizer = DebertaV2Tokenizer.from_pretrained(\"microsoft/mdeberta-v3-base\", truncation_side='left', padding=True)\n encoder_model = DebertaV2Model.from_pretrained(\"microsoft/mdeberta-v3-base\")\n router_datasets = [RouterDataset(data_path, size=args.training_samples_per_dataset, dataset_id = i, cost_rate=args.cost_rate) for i, data_path in enumerate(args.data_paths)]\n for router_dataset in router_datasets:\n router_dataset.register_tokenizer(tokenizer)\n router_dataset = ConcatDataset(router_datasets)\n print(f\"init_model, router_node: {router_datasets[0].router_node}\")\n router_model = RouterModule(encoder_model, hidden_state_dim=768, node_size=len(router_datasets[0].router_node), similarity_function=args.similarity_function).to(device)\n optimizer = torch.optim.AdamW(router_model.parameters(), lr=args.learning_rate)\n print(\"Training start!!!\")\n pbar = tqdm(range(args.training_steps))\n step = 0\n training_log = []\n max_average = 0\n max_training_average = 0\n while(True):\n losses = AverageMeter('Loss', ':3.2f')\n data_loader = DataLoader(router_dataset, batch_size=args.batch_size, shuffle=True)\n num_step = 0\n return_sign = False\n for batch in data_loader:\n optimizer.zero_grad()\n inputs, scores, dataset_ids, cluster_ids, costs = batch\n inputs = inputs.to(device)\n scores = scores.to(device)\n dataset_ids = dataset_ids.to(device)\n cluster_ids = cluster_ids.to(device)\n x, hidden_state = router_model.forward(t=args.tempreture, **inputs)\n loss = router_model.compute_sample_llm_loss(x = x, index_true=scores, top_k = args.top_k, last_k = args.last_k)\n if args.sample_loss_weight:\n sample_sample_loss = router_model.compute_sample_sample_loss_with_task_tag(hidden_state=hidden_state, dataset_ids=dataset_ids, t=args.tempreture, H=args.H)\n loss = loss + args.sample_loss_weight * sample_sample_loss\n if args.regular_loss_weight:\n regular_loss = router_model.compute_orthogonal_regular_loss()\n loss = loss + args.regular_loss_weight * regular_loss\n if args.cluster_loss_weight:\n cluster_loss = router_model.compute_cluster_loss(hidden_state=hidden_state, cluster_ids=cluster_ids, t=args.tempreture, H=args.H)\n loss = loss + args.cluster_loss_weight * cluster_loss\n losses.update(loss.item(), scores.size(0))\n loss.backward()\n if step % args.gradient_accumulation == 0:\n optimizer.step()\n pbar.set_postfix({\"step\": f\"{step}\",\"loss\": loss.item()})\n pbar.write(f\"step:{step}, loss:{loss.item()}\")\n pbar.update(1)\n step += 1\n if step >= args.training_steps:\n break\n if (step + 1) % args.eval_steps == 0:\n print(\"validation start\")\n val_result = evaluation(router_model, args.data_paths, args.test_data_type, tokenizer, batch_size = args.batch_size, device=device)\n print(\"test start\")\n test_result = evaluation(router_model, args.test_data_paths, args.test_data_type, tokenizer, batch_size = args.batch_size, device=device)\n result = {**val_result, **test_result}\n average = sum([ value[1] for value in test_result.values()]) / len(test_result)\n print(\"average testing\", average)\n if average > max_average:\n torch.save(router_model.state_dict(), os.path.join(args.save_path, \"best_model.pth\"))\n max_average = average\n training_log.append(result)\n training_average = sum([ value[1] for value in val_result.values()]) / len(test_result)\n print(\"average training\", training_average)\n if training_average > max_training_average:\n max_training_average = training_average\n num_step += 1\n if args.TestCode and num_step > 10:\n return_sign = True\n args.final_eval = False\n break\n if return_sign:\n break\n print(f\"step:{step}, avg_loss_per_epoch:{losses.avg}\")\n if step >= args.training_steps:\n break\n if args.final_eval:\n state_dict = torch.load(os.path.join(args.save_path, \"best_training_model.pth\"))\n router_model.load_state_dict(state_dict)\n print(\"test start\")\n test_result = evaluation(router_model, args.final_eval_data_paths, args.final_eval_data_type, tokenizer, batch_size=32, device=\"cuda\")\n print(test_result)\n output_order = ['mmlu', 'mbpp', 'hellaswag', 'winograde', 'gsm8k', 'arc_challenge']\n key_list = list(test_result.keys())\n key_order = []\n for key_candidate in output_order:\n for key in key_list:\n if key_candidate in key:\n key_order.append(key)\n break\n for key in key_order:\n print(f\"{test_result[key][1] * 100}\", end=' ')" }, { "task_id": 1, "indent": 2, "completion_path": "./train_router_mdeberta_routerbench.py", "namespace": "train_router_mdeberta_routerbench.RouterModule.compute_cluster_loss", "type": "method", "signature_position": [ 146, 146 ], "body_position": [ 147, 167 ], "script": "\npython train_router_mdeberta_routerbench.py --training_steps 1000 --top_k 4 --last_k 4 --learning_rate 5e-5 --eval_steps 100 --tempreture 1 --similarity_function cos --sample_loss_weight 0 --cluster_loss_weight 1 --seed 7 --final_eval --cost_rate 0 --data_paths ./datasets/routerbench_cluster/gsm8k_train.csv ./datasets/routerbench_cluster/hellaswag_train.csv ./datasets/routerbench_cluster/mbpp_train.csv ./datasets/routerbench_cluster/mmlu_train.csv ./datasets/routerbench_cluster/winograde_train.csv ./datasets/routerbench_cluster/arc_challenge_train.csv --test_data_paths ./datasets/routerbench_zs/gsm8k_test.csv ./datasets/routerbench_zs/hellaswag_test.csv ./datasets/routerbench_zs/mbpp_test.csv ./datasets/routerbench_zs/mmlu_test.csv ./datasets/routerbench_zs/winograde_test.csv ./datasets/routerbench_zs/arc_challenge_test.csv --save_path ./logs/paper_result/routerbench/cr_0_slw_0_tk_4_lk_4_lr_5e-5_step_1000_t_1_seed_7 --TestCode \n", "latex_code": "\nNext, we construct a sample-sample contrastive loss to encourage samples in the same group to have similar embeddings.\nSpecifically, for a query $\\vx_i \\in \\hK_j$, \nwe randomly select an in-group query $\\vx_i^{+} \\in \\hK_j$ and an out-group set $\\hX_i^{-} \\subset \\{ \\cup_{j'\\neq j} \\hK_{j'} \\}$ of $H$ queries from the training mini-batch at each iteration.\nSimilar to the sample-LLM contrastive loss,\nwe propose a sample-sample contrastive loss to pull the embedding of $\\vx_i$ closer to the embedding of $\\vx_i^+$ while pushing it away from the embedding of queries in $\\hX_i^{-}$.\nFormally, the sample-sample contrastive loss is formulated as\n\\begin{align}\n\\label{eqa:sample-sample-loss}\n\\hL_{\\text{sample-sample}}(\\vx_i; \\vtheta) = - \\log \\frac{ e^{\\text{sim}(\\hE(\\vx_{i}; \\vw), \\hE( \\vx_{i}^+; \\vw))} }{e^{\\text{sim}(\\hE(\\vx_{i}; \\vw), \\hE(\\vx_{i}^+; \\vw))} + \\sum_{\\vx_i^- \\in \\hX_i^-} e^{\\text{sim}(\\hE(\\vx_{i}; \\vw), \\hE(\\vx_{i}^-; \\vw))} }.\n\\end{align}\n", "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: First, Compute the pairwise similarities among all samples'\n# embeddings. This aligns with the exponent terms in the LaTeX formulation,\n# where we measure similarity between sample i and each sample j.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nsimilar_score = self.compute_similarity(hidden_state, hidden_state)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: For each sample in the batch, we gather all in-group samples\n# (sharing the same cluster_id) and select exactly one positive in-group query.\n# We also gather all out-group queries and randomly pick H negatives, consistent\n# with the in-group/out-group approach from the LaTeX snippet.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nlast_k2 = H\n\nall_index = []\nfor cluster_id in cluster_ids:\n positive_indexs = torch.nonzero(cluster_ids == cluster_id)\n \n select_positive_index = random.choice(positive_indexs)\n \n negtive_indexs = torch.nonzero(cluster_ids != cluster_id)\n \n if len(negtive_indexs) < last_k2:\n print(\"len of negtive index is smaller than last_k2. cluster_id:\", cluster_id)\n continue\n # [End Snippet 2]\n\n # ---------------------------------------------------------------------------\n # Snippet 3: We randomly sample H out-group indices and then combine these\n # H out-group indices with the single in-group index to form the index set\n # (mirroring the summation over \\(\\vx_i^-\\) in the LaTeX). \n # ---------------------------------------------------------------------------\n # [Begin Snippet 3]\n index_of_negtive_indexs = random.sample(range(0, len(negtive_indexs)), last_k2)\n select_negtive_index = negtive_indexs[index_of_negtive_indexs].view(-1)\n \n select_index = torch.concat([select_positive_index, select_negtive_index])\n all_index.append(select_index)\n # [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: We gather the corresponding similarities for the chosen indices,\n# apply temperature scaling, and compute the contrastive loss by taking the\n# negative log of the softmax over positive+negative samples, consistent with \n# Eq. (7) in the LaTeX snippet. Finally, we return the average loss.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nall_index = torch.stack(all_index)\nrearrange_similar_score = torch.gather(similar_score, 1, all_index)\n\nsimilar_score = similar_score / t\n\nsoftmax_sample_x = torch.softmax(rearrange_similar_score, dim=-1)\n\nlog_sample_x = torch.log(softmax_sample_x)\n\nloss = torch.mean(-log_sample_x[:, 0])\n\nreturn loss\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX code omits the workflow for applying the temperature parameter `t` to the similarity scores. In the reference code (Snippet 5), the temperature scaling is applied after computing the full similarity matrix (`similar_score = similar_score / t`), scaling all pairwise similarities uniformly before the softmax operation.\n \n Mismatched Details:\n - The LaTeX focuses on drawing in-group and out-group queries from the mini-batch explicitly, but this implementation randomly selects them from the current batch based on cluster membership.\n - Uses random negative sampling rather than explicit out-group clusters\n - The LaTeX formulation implies that the loss is computed per sample \\(\\vx_i\\) with a single positive \\(\\vx_i^+\\) and a set of negatives \\(\\hX_i^-\\), but it does not clarify whether similarities are precomputed across the batch or calculated on-the-fly. The reference code (Snippet 1 and 5) precomputes a full similarity matrix (`similar_score`) and then gathers specific indices, ensuring that all similarities are derived from a consistent batch-level computation.\n", "Missing_details": [ "\n- The LaTeX code omits the workflow for applying the temperature parameter `t` to the similarity scores. In the reference code (Snippet 5), the temperature scaling is applied after computing the full similarity matrix (`similar_score = similar_score / t`), scaling all pairwise similarities uniformly before the softmax operation.\n " ], "Mismatched_details": [ "\n- The LaTeX focuses on drawing in-group and out-group queries from the mini-batch explicitly, but this implementation randomly selects them from the current batch based on cluster membership.\n", "\n- Uses random negative sampling rather than explicit out-group clusters\n", "\n- The LaTeX formulation implies that the loss is computed per sample \\(\\vx_i\\) with a single positive \\(\\vx_i^+\\) and a set of negatives \\(\\hX_i^-\\), but it does not clarify whether similarities are precomputed across the batch or calculated on-the-fly. The reference code (Snippet 1 and 5) precomputes a full similarity matrix (`similar_score`) and then gathers specific indices, ensuring that all similarities are derived from a consistent batch-level computation.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - hidden_state (torch.Tensor, shape: [batch_size, embedding_dim]): The encoded representations (embeddings) of all samples from which we will compute similarity scores. \n - cluster_ids (torch.Tensor, [batch_size]): Identifiers that group the samples into specific clusters. Samples sharing the same ID belong to the same cluster.\n - t (float): Temperature parameter used to scale the similarity scores. This helps modulate the distribution\u2019s sharpness in the contrastive loss.\n - H (int, optional): Number of out-group samples (negatives) to select for each query. Defaults to 3 if not specified.\n", "Arguments_list": [ { "name": "hidden_state", "string": "\n- hidden_state (torch.Tensor, shape: [batch_size, embedding_dim]): The encoded representations (embeddings) of all samples from which we will compute similarity scores.\n", "dependency": null }, { "name": "cluster_ids", "string": "\n- cluster_ids (torch.Tensor, [batch_size]): Identifiers that group the samples into specific clusters. Samples sharing the same ID belong to the same cluster.\n", "dependency": null }, { "name": "t", "string": "\n- t (float): Temperature parameter used to scale the similarity scores. This helps modulate the distribution's sharpness in the contrastive loss.\n", "dependency": null }, { "name": "H", "string": "\n- H (int, optional): Number of out-group samples (negatives) to select for each query. Defaults to 3 if not specified.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File Dependency:\n - RouterModule.compute_similarity\n \n Cross-File Dependency: None\n", "intra_file": [ "RouterModule.compute_similarity" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.gather\n - torch.softmax\n - torch.log\n - random.sample\n - torch.stack\n - torch.mean\n - torch.nonzero\n - random.choice\n - torch.concat\n\n", "list": [ "random.choice", "random.sample", "torch.nonzero", "torch.concat", "torch.stack", "torch.gather", "torch.softmax", "torch.log", "torch.mean" ] }, "Return": { "Return_String": "\nOutput Variables:\n - loss (torch.Tensor, scalar): The mean contrastive loss that pulls samples in the same cluster closer in embedding space and pushes samples from different clusters apart.\n", "Return_list": [ { "name": "loss", "string": "\n- loss (torch.Tensor, scalar): The mean contrastive loss that pulls samples in the same cluster closer in embedding space and pushes samples from different clusters apart.\n", "dependency": null } ] }, "ori_python_file": "import argparse\nimport json\nimport pandas as pd\nimport os\nimport random\nimport torch.nn as nn\nimport torch.optim\nfrom torch.utils.data import Dataset, DataLoader, ConcatDataset\nfrom tqdm import tqdm\nfrom transformers import AutoTokenizer, DebertaV2Model, DebertaV2Tokenizer\nfrom utils.meters import AverageMeter\nimport numpy as np\nimport torch\ndef setup_seed(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n np.random.seed(seed)\n random.seed(seed)\n torch.backends.cudnn.deterministic = True\n\nclass RouterDataset(Dataset):\n \n def __init__(self,\n data_path,\n source_max_token_len: int = 512,\n target_max_token_len: int = 512,\n size: int = None,\n dataset_id = 0,\n cost_rate = 0,\n ):\n if data_path.endswith('.json'):\n self.data = pd.read_json(data_path).dropna()\n elif data_path.endswith('.pkl'):\n self.data = pd.read_pickle(data_path).dropna()\n elif data_path.endswith('.csv'):\n self.data = pd.read_csv(data_path).dropna()\n if size:\n while(len(self.data) < size):\n self.data = pd.concat([self.data, self.data])\n self.data = self.data[:size]\n self.tokenizer = None\n self.router_node = ['WizardLM/WizardLM-13B-V1.2', 'claude-instant-v1', 'claude-v1', 'claude-v2', 'gpt-3.5-turbo-1106', 'gpt-4-1106-preview', 'meta/code-llama-instruct-34b-chat', 'meta/llama-2-70b-chat', 'mistralai/mistral-7b-chat', 'mistralai/mixtral-8x7b-chat', 'zero-one-ai/Yi-34B-Chat']\n self.source_max_token_len = source_max_token_len\n self.target_max_token_len = target_max_token_len\n self.dataset_id = dataset_id\n self.cost_rate = cost_rate\n \n def __getitem__(self, index):\n data_point = self.data.iloc[index]\n cost_index = [ index + \"|total_cost\" for index in self.router_node]\n scores = torch.tensor(data_point[self.router_node].values.tolist())\n costs = torch.tensor(data_point[cost_index].values.tolist())\n scores = scores - costs * self.cost_rate\n question = data_point['prompt'][:1400]\n question_id = self.tokenizer(\n question,\n max_length=self.target_max_token_len,\n padding=\"max_length\",\n truncation=True,\n return_attention_mask=True,\n add_special_tokens=True,\n return_tensors=\"pt\",\n )\n question_id['input_ids'] = question_id.input_ids.flatten()\n question_id['attention_mask'] = question_id.attention_mask.flatten()\n cluster_id = data_point['cluster_id'] if \"cluster_id\" in data_point else 0\n return question_id, scores, self.dataset_id, cluster_id, costs\n \n def __len__(self):\n return len(self.data)\n \n def register_tokenizer(self, tokenizer):\n self.tokenizer = tokenizer\n\nclass RouterModule(nn.Module):\n \n def __init__(self, backbone, hidden_state_dim=768, node_size=3, similarity_function = \"cos\"):\n super(RouterModule, self).__init__()\n self.backbone = backbone\n self.hidden_state_dim = hidden_state_dim\n self.node_size = node_size\n self.embeddings = nn.Embedding(node_size, hidden_state_dim)\n std_dev = 0.78\n with torch.no_grad():\n nn.init.normal_(self.embeddings.weight, mean=0, std=std_dev)\n self.similarity_function = similarity_function\n \n def compute_similarity(self, input1, input2):\n if self.similarity_function == \"cos\":\n return (input1 @ input2.T) / (torch.norm(input1,dim=1).unsqueeze(1) * torch.norm(input2,dim=1).unsqueeze(0))\n else:\n return input1 @ input2.T\n \n def forward(self, t=1, **input_kwargs):\n x = self.backbone(**input_kwargs)\n hidden_state = x['last_hidden_state'][:,0,:]\n x = self.compute_similarity(hidden_state, self.embeddings.weight)\n x = x / t\n return x, hidden_state\n \n def compute_sample_llm_loss(self, x, index_true, top_k, last_k):\n loss = 0\n top_index_true, top_index = index_true.sort(dim=-1, descending=True)\n last_index_true, negtive_index = index_true.topk(k=last_k, largest=False, dim=-1)\n for i in range(top_k):\n positive_index = top_index[:, i].view(-1, 1)\n mask = torch.where(top_index_true[:, i].view(-1, 1) > 0, 1, 0)\n top_x = torch.gather(x, 1, positive_index)\n last_x = torch.gather(x, 1, negtive_index)\n last_x = torch.where(last_index_true > 0.5, float(\"-inf\"), last_x)\n temp_x = torch.concat([top_x, last_x], dim=-1)\n softmax_x = nn.Softmax(dim=-1)(temp_x)\n log_x = torch.log(softmax_x[:, 0])\n log_x = log_x * mask\n loss += torch.mean(-log_x)\n return loss\n \n def compute_sample_sample_loss_with_task_tag(self, hidden_state, dataset_ids, t, H=3):\n similar_score = self.compute_similarity(hidden_state, hidden_state)\n last_k2 = H\n all_index = []\n for dataset_id in dataset_ids:\n positive_indexs = torch.nonzero(dataset_ids == dataset_id)\n select_positive_index = random.choice(positive_indexs)\n negtive_indexs = torch.nonzero(dataset_ids != dataset_id)\n if len(negtive_indexs) < last_k2:\n print(\"len of negtive index is smaller than last_k2. dataset_id:\", dataset_id)\n continue\n index_of_negtive_indexs = random.sample(range(0, len(negtive_indexs)), last_k2)\n select_negtive_index = negtive_indexs[index_of_negtive_indexs].squeeze()\n select_index = torch.concat([select_positive_index, select_negtive_index])\n all_index.append(select_index)\n all_index = torch.stack(all_index)\n rearrange_similar_score = torch.gather(similar_score, 1, all_index)\n similar_score = similar_score / t\n softmax_sample_x = torch.softmax(rearrange_similar_score, dim=-1)\n log_sample_x = torch.log(softmax_sample_x)\n loss = torch.mean(-log_sample_x[:,0])\n return loss\n \n def compute_orthogonal_regular_loss(self):\n embedding_similarity = self.compute_similarity(self.embeddings.weight, self.embeddings.weight)\n loss = torch.norm(embedding_similarity - torch.eye(self.node_size).type_as(embedding_similarity))\n return loss\n \n def compute_cluster_loss(self, hidden_state, cluster_ids, t, H=3):\n similar_score = self.compute_similarity(hidden_state, hidden_state)\n last_k2 = H\n all_index = []\n for cluster_id in cluster_ids:\n positive_indexs = torch.nonzero(cluster_ids == cluster_id)\n select_positive_index = random.choice(positive_indexs)\n negtive_indexs = torch.nonzero(cluster_ids != cluster_id)\n if len(negtive_indexs) < last_k2:\n print(\"len of negtive index is smaller than last_k2. cluster_id:\", cluster_id)\n continue\n index_of_negtive_indexs = random.sample(range(0, len(negtive_indexs)), last_k2)\n select_negtive_index = negtive_indexs[index_of_negtive_indexs].view(-1)\n select_index = torch.concat([select_positive_index, select_negtive_index])\n all_index.append(select_index)\n all_index = torch.stack(all_index)\n rearrange_similar_score = torch.gather(similar_score, 1, all_index)\n similar_score = similar_score / t\n softmax_sample_x = torch.softmax(rearrange_similar_score, dim=-1)\n log_sample_x = torch.log(softmax_sample_x)\n loss = torch.mean(-log_sample_x[:, 0])\n return loss\n\ndef evaluation(router_model, dataset_paths, dataset_types, tokenizer, batch_size, device):\n result = {}\n with torch.no_grad():\n for index, data_path in enumerate(dataset_paths):\n test_dataset = RouterDataset(data_path=data_path)\n test_dataset.register_tokenizer(tokenizer)\n data_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=True)\n correct_predict = 0\n correct = 0\n sum_cost = 0\n for batch in data_loader:\n inputs, scores, _, _, costs = batch\n inputs = inputs.to(device)\n scores = scores.to(device)\n costs = costs.to(device)\n scores = scores - test_dataset.cost_rate * costs\n x, _ = router_model.forward(**inputs)\n softmax_x = nn.Softmax(dim=1)(x)\n _, max_index = torch.max(softmax_x, dim=1)\n _, target_max_index = torch.max(scores, dim=1)\n equals = max_index.eq(target_max_index)\n select_costs = torch.gather(costs, 1, max_index.unsqueeze(1)).float()\n sum_cost += select_costs.sum().item()\n correct += equals.sum().item()\n mask = torch.zeros_like(scores)\n mask = mask.scatter_(1, max_index.unsqueeze(1), 1)\n if torch.isnan(mask).any() or torch.isnan(scores).any():\n print(\"scores\", scores)\n print(\"max_index\", max_index)\n print(\"target_max_index\", target_max_index)\n print(\"equals\", equals)\n correct_predict += (scores * mask).sum().item()\n acc_predict = correct_predict/len(test_dataset)\n acc = correct/len(test_dataset)\n avg_costs = sum_cost / len(test_dataset)\n print(f\"acc_{data_path}:\", acc_predict)\n print(\"acc\", acc)\n print(\"avg_cost\", avg_costs)\n result[data_path] = [acc, acc_predict, avg_costs]\n return result\n\nif __name__ == '__main__':\n device = \"cuda\"\n parser = argparse.ArgumentParser(description=\"the training code for router\")\n parser.add_argument('--data_paths', nargs='+')\n parser.add_argument('--test_data_paths',nargs='+')\n parser.add_argument('--test_data_type', nargs='+')\n parser.add_argument('--final_eval_data_paths', nargs='+', default=['./datasets/routerbench_zs/gsm8k_test.csv','./datasets/routerbench_zs/hellaswag_test.csv','./datasets/routerbench_zs/mbpp_test.csv','./datasets/routerbench_zs/mmlu_test.csv','./datasets/routerbench_zs/winograde_test.csv','./datasets/routerbench_zs/arc_challenge_test.csv'])\n parser.add_argument('--final_eval_data_type', nargs='+', default=[\"probability\", \"probability\", \"multi_attempt\",\"probability\", \"multi_attempt\", \"multi_attempt\", \"probability\", \"probability\"])\n parser.add_argument('--batch_size', type=int, default=64)\n parser.add_argument('--training_steps', type=int, default=100)\n parser.add_argument('--eval_steps',type=int,default=1000)\n parser.add_argument('--learning_rate', type=float, default=0.00005)\n parser.add_argument('--save_path', type=str, default='./logs/router_debug/')\n parser.add_argument('--top_k', type=int, default=2)\n parser.add_argument('--last_k',type=int, default=3)\n parser.add_argument('--tempreture', type=int, default=1)\n parser.add_argument('--gradient_accumulation', type=int, default=1)\n parser.add_argument('--similarity_function', type=str, default='cos')\n parser.add_argument('--sample_loss_weight', type=float, default=0)\n parser.add_argument('--regular_loss_weight', type=float, default=0)\n parser.add_argument('--cluster_loss_weight', type=float, default=0)\n parser.add_argument('--H', type=int, default=3)\n parser.add_argument('--final_eval', action=\"store_true\")\n parser.add_argument('--seed', type=int, default=42)\n parser.add_argument('--training_samples_per_dataset', type=int, default=1000)\n parser.add_argument('--cost_rate', type=float, default=0)\n parser.add_argument('--TestCode', action=\"store_true\")\n args = parser.parse_args()\n os.makedirs(args.save_path, exist_ok=True)\n setup_seed(args.seed)\n tokenizer = DebertaV2Tokenizer.from_pretrained(\"microsoft/mdeberta-v3-base\", truncation_side='left', padding=True)\n encoder_model = DebertaV2Model.from_pretrained(\"microsoft/mdeberta-v3-base\")\n router_datasets = [RouterDataset(data_path, size=args.training_samples_per_dataset, dataset_id = i, cost_rate=args.cost_rate) for i, data_path in enumerate(args.data_paths)]\n for router_dataset in router_datasets:\n router_dataset.register_tokenizer(tokenizer)\n router_dataset = ConcatDataset(router_datasets)\n print(f\"init_model, router_node: {router_datasets[0].router_node}\")\n router_model = RouterModule(encoder_model, hidden_state_dim=768, node_size=len(router_datasets[0].router_node), similarity_function=args.similarity_function).to(device)\n optimizer = torch.optim.AdamW(router_model.parameters(), lr=args.learning_rate)\n print(\"Training start!!!\")\n pbar = tqdm(range(args.training_steps))\n step = 0\n training_log = []\n max_average = 0\n max_training_average = 0\n while(True):\n losses = AverageMeter('Loss', ':3.2f')\n data_loader = DataLoader(router_dataset, batch_size=args.batch_size, shuffle=True)\n num_step = 0\n return_sign = False\n for batch in data_loader:\n optimizer.zero_grad()\n inputs, scores, dataset_ids, cluster_ids, costs = batch\n inputs = inputs.to(device)\n scores = scores.to(device)\n dataset_ids = dataset_ids.to(device)\n cluster_ids = cluster_ids.to(device)\n x, hidden_state = router_model.forward(t=args.tempreture, **inputs)\n loss = router_model.compute_sample_llm_loss(x = x, index_true=scores, top_k = args.top_k, last_k = args.last_k)\n if args.sample_loss_weight:\n sample_sample_loss = router_model.compute_sample_sample_loss_with_task_tag(hidden_state=hidden_state, dataset_ids=dataset_ids, t=args.tempreture, H=args.H)\n loss = loss + args.sample_loss_weight * sample_sample_loss\n if args.regular_loss_weight:\n regular_loss = router_model.compute_orthogonal_regular_loss()\n loss = loss + args.regular_loss_weight * regular_loss\n if args.cluster_loss_weight:\n cluster_loss = router_model.compute_cluster_loss(hidden_state=hidden_state, cluster_ids=cluster_ids, t=args.tempreture, H=args.H)\n loss = loss + args.cluster_loss_weight * cluster_loss\n losses.update(loss.item(), scores.size(0))\n loss.backward()\n if step % args.gradient_accumulation == 0:\n optimizer.step()\n pbar.set_postfix({\"step\": f\"{step}\",\"loss\": loss.item()})\n pbar.write(f\"step:{step}, loss:{loss.item()}\")\n pbar.update(1)\n step += 1\n if step >= args.training_steps:\n break\n if (step + 1) % args.eval_steps == 0:\n print(\"validation start\")\n val_result = evaluation(router_model, args.data_paths, args.test_data_type, tokenizer, batch_size = args.batch_size, device=device)\n print(\"test start\")\n test_result = evaluation(router_model, args.test_data_paths, args.test_data_type, tokenizer, batch_size = args.batch_size, device=device)\n result = {**val_result, **test_result}\n average = sum([ value[1] for value in test_result.values()]) / len(test_result)\n print(\"average testing\", average)\n if average > max_average:\n torch.save(router_model.state_dict(), os.path.join(args.save_path, \"best_model.pth\"))\n max_average = average\n training_log.append(result)\n training_average = sum([ value[1] for value in val_result.values()]) / len(test_result)\n print(\"average training\", training_average)\n if training_average > max_training_average:\n max_training_average = training_average\n num_step += 1\n if args.TestCode and num_step > 10:\n return_sign = True\n args.final_eval = False\n break\n if return_sign:\n break\n print(f\"step:{step}, avg_loss_per_epoch:{losses.avg}\")\n if step >= args.training_steps:\n break\n if args.final_eval:\n state_dict = torch.load(os.path.join(args.save_path, \"best_training_model.pth\"))\n router_model.load_state_dict(state_dict)\n print(\"test start\")\n test_result = evaluation(router_model, args.final_eval_data_paths, args.final_eval_data_type, tokenizer, batch_size=32, device=\"cuda\")\n print(test_result)\n output_order = ['mmlu', 'mbpp', 'hellaswag', 'winograde', 'gsm8k', 'arc_challenge']\n key_list = list(test_result.keys())\n key_order = []\n for key_candidate in output_order:\n for key in key_list:\n if key_candidate in key:\n key_order.append(key)\n break\n for key in key_order:\n print(f\"{test_result[key][1] * 100}\", end=' ')" } ] }, { "paper_id": 14, "paper_details": { "title": "Unsupervised Homography Estimation on Multimodal Image Pair via Alternating Optimization", "url": "https://arxiv.org/abs/2411.13036" }, "enviorment_name": "alto", "repo_original_url": "https://github.com/songsang7/alto", "project_path": "Benchmark/14-AltO-main/AltO-main", "file_organization": "\nAltO-main/\n Dataset/\n DLKFM/\n GoogleEarth/\n train2014_input/\n 0_1.jpg\n ...\n train2014_label/\n 0_1_label.txt\n ...\n train2014_template/\n 0_1.jpg\n ...\n val2014_input/\n 0.jpg\n ...\n val2014_label/\n 0_label.txt\n ...\n val2014_template/\n 0.jpg\n ...\n GoogleMap/\n train2014_input/\n 0_Boston_0_0.jpg\n ...\n train2014_label/\n 0_Boston_0_0_label.txt\n ...\n train2014_template/\n 0_Boston_0_0.jpg\n ...\n val2014_input/\n 0.jpg\n ...\n val2014_label/\n 0_label.txt\n ...\n val2014_template/\n 0.jpg\n ...\n MSCOCO/\n generate_testing_sample.py\n generate_training_sample.py\n common/\n controller/\n base_controller.py\n dataset/\n dataset_info.py\n networks/\n activation_layers.py\n basic_blocks.py\n norm_layers.py\n definitions.py\n lr_schedules.py\n optimizers.py\n utils.py\n image_matching/\n controller/\n alto.py\n dataset/\n gg_mm.py\n labeled_pair.py\n selfgen_aligned_pair.py\n selfgen_solo.py\n spatial_transforms.py\n networks/\n alto_net.py\n dhn_net.py\n ihn_net.py\n raft.py\n rhwf_net.py\n ui/\n hardcoded.py\n definitions.py\n utils.py\n main.py\n README.md\n", "latex_code_path": "Benchmark/14-AltO-main/arXiv-2411.13036v1", "task_details": [ { "task_id": 0, "indent": 2, "script": "\npython main.py\n", "latex_code": "\nThe features of two images $\\widetilde{I}^A$ and $I^B$ are extracted with a shared encoder $\\mathcal{E}$, and the output feature maps are used to compute the GBT loss.\nThe GBT loss $\\mathcal{L}_g$, is different from the original Barlow Twins in that we consider the spatial axis of the features as the batch dimension of the original Barlow Twins formula:\n\\begin{equation}\n\\begin{split}\n \\mathcal{L}_{g} = \\mathbb{E}_n \\bigg[ \\sum_{i}(1-C_{(n, ii)})^2 + & \\lambda\\sum_{i}\\sum_{j\\neq i}C_{(n, ij)}^2 \\bigg], \\\\\n & \\text{where } C_{(n, ij)} = \\frac{\\sum_{h, w}(\\bar{f}_{(n, i, h, w)}^A \\bar{f}_{(n, j, h, w)}^B)}{\\sqrt{\\sum_{h,w} (\\bar{f}^A_{(n, i, h, w)})^2} \\sqrt{\\sum_{h,w} (\\bar{f}^B_{(n, j, h, w)})^2}}\n\\end{split}\n\\end{equation}\nwhere $\\bar{f}^A_{(n,i,h,w)}$ and $\\bar{f}^B_{(n,i,h,w)}$ are feature vectors in $\\mathbb{R}^{N \\times D \\times H \\times W}$ corresponding to $\\widetilde{I}^A$ and $I^B$, respectively, mean-normalized along the spatial dimensions, by subtracting the spatial mean from each unit. $n$ and $h, w$ each denote the batch and the spatial (horizontal and vertical) index and $i,j$ denote the index of channel dimension. Our objective can be considered as applying redundancy reduction on the spatial dimension of an image pair, maximizing the similarities of the local features at corresponding regions. By minimizing the geometric distance, or in other words, maximizing the geometrical similarity, the network $\\mathcal{R}$ learns to geometrically align the given image pair. Visualization of our Geometry Learning (GL) phase can be found at the bottom-left of Figure~\\ref{overall_archi}.\n", "completion_path": "./common/utils.py", "namespace": "common.utils.GeneralUtils.bt_loss_sub", "type": "method", "signature_position": [ 115, 115 ], "body_position": [ 116, 131 ], "ReferenceCode_With_Comments": "\n# ----------------------------------------------------------------------------\n# Snippet 1: This step corresponds to calculating mean-normalized features (f\u0304). We subtract the spatial mean along dim=1 and scale by the standard deviation, aligning with the \"mean-normalized along spatial dimensions\" requirement.\n# ----------------------------------------------------------------------------\n# [Begin Snippet 1]\nd1 = z1.shape[1]\n\nstd1, mean1 = torch.std_mean(z1, dim=1, keepdim=True)\nz_a = (z1 - mean1) / (eps + std1)\n# [End Snippet 1]\n\n# ----------------------------------------------------------------------------\n# Snippet 2: Similarly, we compute the mean-normalized features for z2, which\n# in the LaTeX corresponds to f\u0304^B. Both sets of normalized features are used\n# to form the correlation matrix C_(n, i, j).\n# ----------------------------------------------------------------------------\n# [Begin Snippet 2]\nstd2, mean2 = torch.std_mean(z2, dim=1, keepdim=True)\nz_b = (z2 - mean2) / (eps + std2)\n\nncc_mat = torch.bmm(z_a.transpose(1, 2), z_b) / (d1 - 1)\n# [End Snippet 2]\n\n# ----------------------------------------------------------------------------\n# Snippet 3: Per the LaTeX's Barlow Twins style objective, we isolate the\n# diagonal (on_diag) to enforce these correlations to be close to 1, and the\n# off-diagonal elements (off_diag) to be close to 0 via the redundancy\n# reduction principle. This mirrors C_(n, ij) separation into diagonal vs.\n# non-diagonal channels.\n# ----------------------------------------------------------------------------\n# [Begin Snippet 3]\non_diag = ncc_mat.diagonal(dim1=1, dim2=2) # Shape: (B, C)\n\nx = ncc_mat\nbatch_size = x.shape[0]\nl = x.shape[1]\n\nx = x.view(batch_size, -1)\nx = x[:, :-1].view(batch_size, l - 1, l + 1)\noff_diag = x[:, :, 1:].reshape(batch_size, -1)\n# [End Snippet 3]\n\n# ----------------------------------------------------------------------------\n# Snippet 4: This final snippet applies the loss formulation from the LaTeX,\n# with (on_diag - 1)^2 penalizing deviation from 1 on the diagonal and\n# alpha * off_diag^2 penalizing off-diagonal terms. The result is then\n# averaged over the batch, yielding the final GBT loss (L_g).\n# ----------------------------------------------------------------------------\n# [Begin Snippet 4]\nloss = (on_diag - 1).square().sum(dim=1) + alpha * off_diag.square().sum(dim=1)\nloss = loss.mean()\nreturn loss\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX description specifies that the features \\(\\bar{f}^A_{(n,i,h,w)}\\) and \\(\\bar{f}^B_{(n,i,h,w)}\\) are \"mean-normalized along the spatial dimensions, by subtracting the spatial mean from each unit,\" but it does not mention scaling by the standard deviation. In the reference Python code, the normalization process involves both subtracting the spatial mean and dividing by the standard deviation along the spatial dimension (dim=1).\n - The LaTeX formula for \\(C_{(n, ij)}\\) defines the cross-correlation but does not specify a scaling factor for the numerator. In the reference implementation, the workflow for computing the cross-correlation involves aggregating the product of the normalized features over the spatial dimension and then dividing the result by the number of spatial elements minus one.\n\n Mismatched Details:\n - The LaTeX loss function \\(\\mathcal{L}_{g} = \\mathbb{E}_n \\bigg[ \\sum_{i}(1-C_{(n, ii)})^2 + \\lambda\\sum_{i}\\sum_{j\\neq i}C_{(n, ij)}^2 \\bigg]\\) uses a summation notation to separate diagonal and off-diagonal terms, suggesting a straightforward aggregation of all off-diagonal elements. However, the reference implementation employs a more specific workflow for isolating these terms: after computing the full correlation matrix, the diagonal elements are extracted directly, and the off-diagonal elements are obtained through a process of reshaping the matrix to exclude the diagonal and then flattening the remaining terms for summation.\n", "Missing_details": [ "\n- The LaTeX description specifies that the features \\(\\bar{f}^A_{(n,i,h,w)}\\) and \\(\\bar{f}^B_{(n,i,h,w)}\\) are \"mean-normalized along the spatial dimensions, by subtracting the spatial mean from each unit,\" but it does not mention scaling by the standard deviation. In the reference Python code, the normalization process involves both subtracting the spatial mean and dividing by the standard deviation along the spatial dimension (dim=1).\n", "\n- The LaTeX formula for \\(C_{(n, ij)}\\) defines the cross-correlation but does not specify a scaling factor for the numerator. In the reference implementation, the workflow for computing the cross-correlation involves aggregating the product of the normalized features over the spatial dimension and then dividing the result by the number of spatial elements minus one.\n" ], "Mismatched_details": [ "\n- The LaTeX loss function \\(\\mathcal{L}_{g} = \\mathbb{E}_n \\bigg[ \\sum_{i}(1-C_{(n, ii)})^2 + \\lambda\\sum_{i}\\sum_{j\\neq i}C_{(n, ij)}^2 \\bigg]\\) uses a summation notation to separate diagonal and off-diagonal terms, suggesting a straightforward aggregation of all off-diagonal elements. However, the reference implementation employs a more specific workflow for isolating these terms: after computing the full correlation matrix, the diagonal elements are extracted directly, and the off-diagonal elements are obtained through a process of reshaping the matrix to exclude the diagonal and then flattening the remaining terms for summation.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - z1 (torch.Tensor): A 3D tensor of shape (B, N, C). \n * B denotes the true batch size (e.g., number of images or image pairs).\n * N denotes the \"spatial\" dimension in the GBT context, effectively\n playing the role of the 'batch' dimension in the original Barlow Twins.\n * C is the feature channel dimension.\n The tensor holds features that have been mean-normalized or are\n pending normalization.\n\n - z2 (torch.Tensor): A 3D tensor of the same shape (B, N, C) as z1,\n with the same dimensional meaning. This is typically a second view\n of the data or a differently augmented version of the same set\n of images.\n\n - alpha (float): A scalar weighting factor (akin to lambda in the\n LaTeX equation) that controls the penalty on off-diagonal\n correlation terms.\n\n - eps (float): A small constant (default=1e-5) added to the standard\n deviation to prevent division by zero during the feature normalization.\n", "Arguments_list": [ { "name": "z1", "string": "\n- z1 (torch.Tensor): A 3D tensor of shape (B, N, C). \n * B denotes the true batch size (e.g., number of images or image pairs).\n * N denotes the \"spatial\" dimension in the GBT context, effectively\n playing the role of the 'batch' dimension in the original Barlow Twins.\n * C is the feature channel dimension.\n The tensor holds features that have been mean-normalized or are\n pending normalization.\n", "dependency": null }, { "name": "z2", "string": "\n- z2 (torch.Tensor): A 3D tensor of the same shape (B, N, C) as z1,\n with the same dimensional meaning. This is typically a second view\n of the data or a differently augmented version of the same set\n of images.\n", "dependency": null }, { "name": "alpha", "string": "\n- alpha (float): A scalar weighting factor (akin to lambda in the\n LaTeX equation) that controls the penalty on off-diagonal\n correlation terms.\n", "dependency": null }, { "name": "eps", "string": "\n- eps (float): A small constant (default=1e-5) added to the standard\n deviation to prevent division by zero during the feature normalization.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File Dependencies: \n - None\n \n Cross-File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.std_mean\n - torch.bmm\n", "list": [ "torch.std_mean", "torch.bmm" ] }, "Return": { "Return_String": "\nOutput Variables:\n - loss (torch.Tensor): A scalar tensor (torch.float) representing the computed GBT (modified Barlow Twins) loss. \n", "Return_list": [ { "name": "loss", "string": "\n- loss (torch.Tensor): A scalar tensor (torch.float) representing the computed GBT (modified Barlow Twins) loss. \n", "dependency": null } ] }, "ori_python_file": "import logging\nimport os\nimport random\nimport re\nimport time\nimport cv2\nimport numpy as np\nimport torch\nimport kornia\nclass GeneralUtils:\n \n def __init__(self):\n pass\n \n @staticmethod\n def set_seed(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n \n @staticmethod\n def get_time_stamp(time_to_convert=None):\n if time_to_convert is None:\n time_to_convert = time.time()\n time_stamp = time.localtime(time_to_convert)\n time_stamp = f\"{time_stamp.tm_year}-{time_stamp.tm_mon:02d}-{time_stamp.tm_mday:02d} {time_stamp.tm_hour:02d}:{time_stamp.tm_min:02d}:{time_stamp.tm_sec:02d}\"\n return time_stamp\n \n @staticmethod\n def get_batch_categorical_accuracy(pred: torch.Tensor, target: torch.Tensor):\n top_pred = pred.argmax(dim=1)\n top_gt = target.argmax(dim=1)\n incorrect = (top_pred - top_gt).count_nonzero()\n acc = 1.0 - (incorrect.float() / target.shape[0])\n return acc\n \n @staticmethod\n def standardize(x, dim, eps=0.00001):\n std, mean = torch.std_mean(x, dim=dim, keepdim=True)\n return (x - mean) / (eps + std)\n \n @staticmethod\n def calc_batch_ncc_matrix(a, b):\n d1 = a.shape[1]\n z_a = GeneralUtils.standardize(a, dim=1)\n z_b = GeneralUtils.standardize(b, dim=1)\n ncc_mat = torch.bmm(z_a.transpose(1, 2), z_b) / (d1 - 1)\n return ncc_mat\n \n @staticmethod\n def off_diagonal(x):\n batch_size = x.shape[0]\n l = x.shape[1]\n x = x.view(batch_size, -1)\n x = x[:, :-1].view(batch_size, l - 1, l + 1)\n return x[:, :, 1:].reshape(batch_size, -1)\n \n @staticmethod\n def sampling_patch_nce_loss(prj_feats_a, prj_feats_b, max_samples_cnt=-1, mask_ori=None, normalize_lv=2, temperature=0.1):\n if mask_ori is not None:\n mask_ori = mask_ori.type(torch.float32)\n result = 0\n for prj_feat_a, prj_feat_b in zip(prj_feats_a, prj_feats_b):\n b, c, h, w = prj_feat_a.shape\n if mask_ori is None:\n mask = torch.ones((b, 1, h, w), device=prj_feat_a.device)\n else:\n mask = torch.nn.functional.interpolate(mask_ori, size=(h, w), mode=\"nearest\")\n min_mask_area = int(mask.sum(dim=(1, 2, 3)).min())\n if min_mask_area <= 0:\n min_mask_area = h * w\n mask += 1.0\n num_samples = int(min(max_samples_cnt, min_mask_area)) if max_samples_cnt > 0 else min_mask_area\n sampled_idx = torch.multinomial(mask.view(b, -1), num_samples)\n sampled_idx = sampled_idx.unsqueeze(2).repeat(1, 1, c)\n prj_feat_a = prj_feat_a.view(b, c, -1).permute(0, 2, 1)\n prj_feat_a = torch.gather(prj_feat_a, 1, sampled_idx)\n prj_feat_b = prj_feat_b.view(b, c, -1).permute(0, 2, 1)\n prj_feat_b = torch.gather(prj_feat_b, 1, sampled_idx)\n result += GeneralUtils.infonce_loss_sub(prj_feat_a, prj_feat_b, temperature, normalize_lv)\n return result / len(prj_feats_a)\n \n @staticmethod\n def infonce_loss_sub(z1, z2, temperature, normalize_lv):\n eps = 0.00001\n b, n, c = z1.shape\n if normalize_lv == 0:\n sim_mat = z1 @ z2.transpose(1, 2)\n elif normalize_lv == 1:\n z1_fnorm = z1.norm(dim=2, keepdim=True, p=\"fro\")\n z2_fnorm = z2.norm(dim=2, keepdim=True, p=\"fro\")\n sim_mat = (z1 @ z2.transpose(1, 2)) / (z1_fnorm * z2_fnorm)\n else:\n sim_mat = GeneralUtils.calc_batch_ncc_matrix(z1.transpose(1, 2), z2.transpose(1, 2))\n softmax_mat = torch.softmax(sim_mat / temperature, dim=2)\n on_diag = softmax_mat.diagonal(dim1=1, dim2=2)\n nll_loss = (-torch.log(eps + on_diag)).mean(dim=1)\n return nll_loss\n \n @staticmethod\n def infonce_loss_2d(z1, z2, temperature=0.1, normalize_lv=2):\n b, c, h, w = z1.shape\n z1 = z1.view(b, c, -1).transpose(1, 2)\n z2 = z2.view(b, c, -1).transpose(1, 2)\n return GeneralUtils.infonce_loss_sub(z1, z2, temperature, normalize_lv).mean()\n \n @staticmethod\n def infonce_loss_1d(z1, z2, temperature=0.1, normalize_lv=2):\n z1 = z1.unsqueeze(0)\n z2 = z2.unsqueeze(0)\n return GeneralUtils.infonce_loss_sub(z1, z2, temperature, normalize_lv).mean()\n \n @staticmethod\n def bt_loss_sub(z1, z2, alpha, eps=0.00001):\n d1 = z1.shape[1]\n std1, mean1 = torch.std_mean(z1, dim=1, keepdim=True)\n z_a = (z1 - mean1) / (eps + std1)\n std2, mean2 = torch.std_mean(z2, dim=1, keepdim=True)\n z_b = (z2 - mean2) / (eps + std2)\n ncc_mat = torch.bmm(z_a.transpose(1, 2), z_b) / (d1 - 1)\n on_diag = ncc_mat.diagonal(dim1=1, dim2=2)\n x = ncc_mat\n batch_size = x.shape[0]\n l = x.shape[1]\n x = x.view(batch_size, -1)\n x = x[:, :-1].view(batch_size, l - 1, l + 1)\n off_diag = x[:, :, 1:].reshape(batch_size, -1)\n loss = (on_diag - 1).square().sum(dim=1) + alpha * off_diag.square().sum(dim=1)\n loss = loss.mean()\n return loss\n \n @staticmethod\n def bt_loss_1d(z1, z2, alpha=0.005):\n z1 = z1.unsqueeze(0)\n z2 = z2.unsqueeze(0)\n return GeneralUtils.bt_loss_sub(z1, z2, alpha)\n \n @staticmethod\n def bt_loss_2d(z1, z2, alpha=0.005):\n b, c, h, w = z1.shape\n z1 = z1.view(b, c, -1).transpose(1, 2)\n z2 = z2.view(b, c, -1).transpose(1, 2)\n return GeneralUtils.bt_loss_sub(z1, z2, alpha)\n \n @staticmethod\n def vic_reg_loss_1d(z1, z2, lamb=25, mu=25, nu=1):\n z1 = z1.unsqueeze(0)\n z2 = z2.unsqueeze(0)\n return GeneralUtils.vic_reg_loss_sub(z1, z2, lamb, mu, nu)\n \n @staticmethod\n def vic_reg_loss_2d(z1, z2, lamb=25, mu=25, nu=1):\n b, c, h, w = z1.shape\n z1 = z1.view(b, c, -1).transpose(1, 2)\n z2 = z2.view(b, c, -1).transpose(1, 2)\n return GeneralUtils.vic_reg_loss_sub(z1, z2, lamb, mu, nu)\n \n @staticmethod\n def vic_reg_loss_sub(z1, z2, lamb, mu, nu):\n b, n, c = z1.shape\n std1, mean1 = torch.std_mean(z1, dim=1, keepdim=True)\n z1_bar = z1 - mean1\n std2, mean2 = torch.std_mean(z2, dim=1, keepdim=True)\n z2_bar = z2 - mean2\n loss_var = torch.relu(1 - std1).mean(dim=(1, 2)) + torch.relu(1 - std2).mean(dim=(1, 2))\n loss_inv = (z1 - z2).square().mean(dim=(1, 2))\n cov_mat_1 = (z1_bar.transpose(1, 2) @ z1_bar) / (n - 1)\n off_diag_1 = GeneralUtils.off_diagonal(cov_mat_1)\n cov_mat_2 = (z2_bar.transpose(1, 2) @ z2_bar) / (n - 1)\n off_diag_2 = GeneralUtils.off_diagonal(cov_mat_2)\n loss_cov = (off_diag_1.square().sum(dim=1) + off_diag_2.square().sum(dim=1)) / c\n total_loss = lamb * loss_var + mu * loss_inv + nu * loss_cov\n return total_loss.mean()\n \n @staticmethod\n def sim_siam_loss(f1, f2, p1, p2):\n loss_12 = -torch.cosine_similarity(p1, f2.detach(), dim=1).mean()\n loss_21 = -torch.cosine_similarity(p2, f1.detach(), dim=1).mean()\n total_loss = 0.5 * (loss_12 + loss_21)\n return total_loss\n \n @staticmethod\n def natural_keys(text):\n def atoi(t):\n return int(t) if t.isdigit() else t\n return [atoi(c) for c in re.split(r'(\\d+)', text)]\n \n @staticmethod\n def normalize_tensor(input_tensor, new_min=0.0, new_max=1.0):\n old_min = input_tensor.min()\n old_max = input_tensor.max()\n result = new_max + ((new_max - new_min) / (old_max - old_min)) * (input_tensor - old_max)\n return result\n \n @staticmethod\n def gradient_penalty(critics, real_samples, fake_samples):\n alpha = torch.rand(real_samples.size(0), 1, 1, 1, device=real_samples.device)\n interpolates = (alpha * real_samples + ((1 - alpha) * fake_samples)).requires_grad_(True)\n d_interpolates = critics(interpolates)\n fake = torch.ones(d_interpolates.size(), device=real_samples.device)\n gradients = torch.autograd.grad(\n outputs=d_interpolates,\n inputs=interpolates,\n grad_outputs=fake,\n create_graph=True,\n retain_graph=True,\n only_inputs=True,\n )[0]\n gradients = gradients.view(gradients.size(0), -1)\n gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean()\n return gradient_penalty\n \n @staticmethod\n def set_net_requires_grad(net, requires_grad):\n for param in net.parameters():\n param.requires_grad = requires_grad\n \n @staticmethod\n def init_weights(m):\n classname = m.__class__.__name__\n if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):\n torch.nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n if hasattr(m, 'bias') and m.bias is not None:\n torch.nn.init.constant_(m.bias.data, 0.0)\n elif classname.find('BatchNorm2d') != -1:\n torch.nn.init.normal_(m.weight.data, 1.0, 0.02)\n torch.nn.init.constant_(m.bias.data, 0.0)\n\nclass ImageUtils:\n def __init__(self):\n pass\n \n @staticmethod\n def imread(filename, flags=cv2.IMREAD_UNCHANGED, dtype=np.uint8):\n try:\n n = np.fromfile(filename, dtype)\n img = cv2.imdecode(n, flags)\n return img\n except Exception as e:\n logging.warning(e)\n return None\n \n @staticmethod\n def imwrite(filename, img, params=None):\n try:\n ext = os.path.splitext(filename)[1]\n result, n = cv2.imencode(ext, img, params)\n if result:\n with open(filename, mode='w+b') as f:\n n.tofile(f)\n return True\n else:\n return False\n except Exception as e:\n logging.warning(e)\n return False\n \n @staticmethod\n def is_image_file(path):\n path_lowercase = path.lower()\n if path_lowercase[-4:] == \".png\":\n return True\n if path_lowercase[-4:] == \".jpg\":\n return True\n if path_lowercase[-5:] == \".jpeg\":\n return True\n if path_lowercase[-4:] == \".tif\":\n return True\n if path_lowercase[-5:] == \".tiff\":\n return True\n if path_lowercase[-4:] == \".bmp\":\n return True\n return False\n \n @staticmethod\n def draw_mask_numpy(image, mask_generated, mask_color=(0, 1, 0), alpha=0.5):\n image_ori = image.copy()\n masked_image = image.copy()\n if len(image.shape) == 2:\n image_ori = np.expand_dims(image_ori, axis=-1).repeat(3, axis=-1)\n masked_image = np.expand_dims(masked_image, axis=-1)\n if len(mask_generated.shape) == 2:\n mask_generated = np.expand_dims(mask_generated, axis=-1)\n condition = 0 < mask_generated\n masked_image = np.where(condition, np.array(mask_color, dtype=masked_image.dtype), masked_image)\n return cv2.addWeighted(image_ori, alpha, masked_image, 1-alpha, 0)\n\nclass GeometryUtils:\n \n def __init__(self):\n pass\n \n @staticmethod\n def gen_corners_numpy(height: int, width: int):\n corners = [[0, 0],\n [width - 1, 0],\n [0, height - 1],\n [width - 1, height - 1]\n ]\n return np.array(corners, dtype=np.float32)\n \n @staticmethod\n def gen_corners_torch(height: int, width: int):\n corners = [[0, 0],\n [width - 1, 0],\n [0, height - 1],\n [width - 1, height - 1]\n ]\n return torch.tensor(corners, dtype=torch.float32).unsqueeze(0)\n \n @staticmethod\n def normalize_mesh_grid(grid, min_val, max_val):\n width, height = grid.shape[-2], grid.shape[-3]\n grid[..., 0] = min_val + (max_val - min_val) * grid[..., 0] / (width - 1)\n grid[..., 1] = min_val + (max_val - min_val) * grid[..., 1] / (height - 1)\n return grid\n \n @staticmethod\n def gen_2d_grid_numpy(height: int, width: int, normalized=False):\n vectors = [np.arange(0, s) for s in (width, height)]\n grids = np.meshgrid(vectors[0], vectors[1], indexing=\"xy\")\n grids = np.stack(grids, axis=-1).astype(np.float32)\n if normalized:\n grids[..., 0] = -1 + 2 * grids[..., 0] / (width - 1)\n grids[..., 1] = -1 + 2 * grids[..., 1] / (height - 1)\n return grids\n \n @staticmethod\n def gen_2d_grid_torch(height: int, width: int, normalized=False):\n vectors = [torch.arange(0, s) for s in (width, height)]\n grids = torch.meshgrid(vectors, indexing=\"xy\")\n grids = torch.stack(grids, dim=-1).unsqueeze(0).type(torch.FloatTensor)\n if normalized:\n grids = GeometryUtils.normalize_mesh_grid(grids, -1, +1)\n return grids\n \n @staticmethod\n def get_batch_roi_from_image(image, left_top, height_roi, width_roi, grid=None):\n batch_size = image.shape[0]\n height_ori = image.shape[2]\n width_ori = image.shape[3]\n if grid is None:\n grid = GeometryUtils.gen_2d_grid_torch(height_roi, width_roi).to(left_top.device)\n left_top = left_top.unsqueeze(1).unsqueeze(1)\n left_top = left_top.repeat(1, height_roi, width_roi, 1)\n grid_t = grid.repeat(batch_size, 1, 1, 1) + left_top\n grid_t = GeometryUtils.normalize_mesh_grid(grid_t, -1, +1)\n warped_patch_from_ori = torch.nn.functional.grid_sample(image, grid_t, align_corners=True, mode='bilinear', padding_mode='zeros')\n return warped_patch_from_ori\n \n @staticmethod\n def get_warped_image_from_homography(image, h):\n height, width = image.shape[0], image.shape[1]\n h_inv = np.linalg.inv(h)\n return cv2.warpPerspective(image, h_inv, (width, height), borderMode=cv2.BORDER_CONSTANT, borderValue=0)\n \n @staticmethod\n def get_pts_offset_from_homography(src_pts, h):\n h = torch.Tensor(h).unsqueeze(0)\n src_pts = torch.Tensor(src_pts).unsqueeze(0)\n dst_pts = kornia.geometry.homography.transform_points(h, src_pts)\n result = dst_pts - src_pts\n return result.squeeze(0).numpy()\n \n @staticmethod\n def get_corners_offset_from_homography(height, width, h):\n corners = GeometryUtils.gen_corners_numpy(height, width)\n return GeometryUtils.get_pts_offset_from_homography(corners, h)\n \n @staticmethod\n def get_flow_field_from_homography_sub(grid, h):\n height, width = grid.shape[0], grid.shape[1]\n h = torch.Tensor(h).unsqueeze(0)\n grid = torch.Tensor(grid).unsqueeze(0)\n src_pts = grid.view(1, -1, 2)\n offsets = GeometryUtils.get_pts_offset_from_homography(src_pts, h)\n flow_field = offsets.reshape(height, width, 2)\n return flow_field\n \n @staticmethod\n def get_flow_field_from_homography(height, width, h):\n grid = GeometryUtils.gen_2d_grid_numpy(height, width)\n return GeometryUtils.get_flow_field_from_homography_sub(grid, h)\n \n @staticmethod\n def get_homography_from_corners_offset(height, width, offsets, global_offset=None):\n corners_src = GeometryUtils.gen_corners_numpy(height, width)\n return GeometryUtils.get_homography_from_pts_offset(corners_src, offsets, global_offset)\n \n @staticmethod\n def get_homography_from_pts_offset(src_pts, offsets, global_offset=None):\n if global_offset is not None:\n src_pts = src_pts + np.expand_dims(global_offset, axis=0)\n dst_pts = src_pts + offsets\n h = cv2.getPerspectiveTransform(src_pts.astype(np.float32), dst_pts.astype(np.float32))\n return h.astype(np.float32)\n \n @staticmethod\n def get_homography_from_flow_field_sub(grid, flow_field, global_offset=None, method=cv2.USAC_MAGSAC):\n src_grid = np.array(grid, np.float32)\n if global_offset is not None:\n src_grid = src_grid + np.expand_dims(global_offset, axis=0)\n dst_grid = grid + flow_field\n h = cv2.findHomography(src_grid, dst_grid, method)[0]\n return h.astype(np.float32)\n \n @staticmethod\n def get_homography_from_flow_field(flow_field, global_offset=None, method=cv2.USAC_MAGSAC):\n height, width = flow_field.shape[0], flow_field.shape[1]\n grid = GeometryUtils.gen_2d_grid_numpy(height, width)\n return GeometryUtils.get_homography_from_flow_field_sub(grid, flow_field, global_offset, method)\n \n @staticmethod\n def get_batch_warpd_image_from_flow_field(image, flow, grid=None, interpolation=\"bilinear\", padding_mode=\"zeros\"):\n if grid is None:\n height, width = flow.shape[-3], flow.shape[-2]\n grid = GeometryUtils.gen_2d_grid_torch(height, width, False).to(flow.device)\n batch_size = flow.shape[0]\n grid = grid.repeat(batch_size, 1, 1, 1)\n new_locs = grid + flow\n new_locs = GeometryUtils.normalize_mesh_grid(new_locs, -1, +1)\n return torch.nn.functional.grid_sample(image, new_locs, align_corners=True, mode=interpolation, padding_mode=padding_mode)\n \n @staticmethod\n def get_batch_warped_image_from_homography(image, h):\n height, width = image.shape[-2], image.shape[-1]\n return kornia.geometry.warp_perspective(image, h.inverse(), (height, width))\n \n @staticmethod\n def get_batch_warped_mask_from_homography(height, width, h):\n batch_size = h.shape[0]\n mask = torch.ones(size=(batch_size, 1, height, width)).to(h.device)\n warped_mask = GeometryUtils.get_batch_warped_image_from_homography(mask, h)\n return warped_mask\n \n @staticmethod\n def get_batch_warped_mask_from_flow_field(flow_field):\n batch_size, height, width = flow_field.shape[0], flow_field.shape[1], flow_field.shape[2]\n mask = torch.ones(size=(batch_size, 1, height, width)).to(flow_field.device)\n warped_mask = GeometryUtils.get_batch_warpd_image_from_flow_field(mask, flow_field)\n return warped_mask\n \n @staticmethod\n def get_batch_pts_offset_from_homography(src_pts, h):\n batch_size = h.shape[0]\n if src_pts.shape[0] < batch_size:\n q = batch_size // src_pts.shape[0]\n src_pts = src_pts.repeat(q, 1, 1)\n dst_pts = kornia.geometry.homography.transform_points(h, src_pts)\n result = dst_pts - src_pts\n return result\n \n @staticmethod\n def get_batch_corners_offset_from_homography(height, width, h):\n corners = GeometryUtils.gen_corners_torch(height, width).to(h.device)\n return GeometryUtils.get_batch_pts_offset_from_homography(corners, h)\n \n @staticmethod\n def get_batch_flow_field_from_homography_sub(grid, h):\n batch_size = h.shape[0]\n height, width = grid.shape[1], grid.shape[2]\n src_pts = grid.view(grid.shape[0], -1, 2)\n offsets = GeometryUtils.get_batch_pts_offset_from_homography(src_pts, h)\n return offsets.view(batch_size, height, width, 2)\n \n @staticmethod\n def get_batch_flow_field_from_homography(height, width, h):\n grid = GeometryUtils.gen_2d_grid_torch(height, width).to(h.device)\n return GeometryUtils.get_batch_flow_field_from_homography_sub(grid, h)\n \n @staticmethod\n def get_batch_homography_from_pts_offsets(src_pts, offsets, global_offset=None):\n batch_size = offsets.shape[0]\n if src_pts.shape[0] < batch_size:\n q = batch_size // src_pts.shape[0]\n src_pts = src_pts.repeat(q, 1, 1)\n if global_offset is not None:\n n = src_pts.shape[1]\n src_pts = src_pts + global_offset.unsqueeze(1).repeat(1, n, 1)\n dst_pts = src_pts + offsets\n h = kornia.geometry.get_perspective_transform(src_pts, dst_pts)\n return h\n \n @staticmethod\n def get_batch_homography_from_corners_offset(height: int, width: int, offsets, global_offset=None):\n corners = GeometryUtils.gen_corners_torch(height, width).to(offsets.device)\n offsets = offsets.view(offsets.shape[0], 4, 2)\n return GeometryUtils.get_batch_homography_from_pts_offsets(corners, offsets, global_offset)\n \n @staticmethod\n def get_batch_homography_from_flow_field_sub(grid, flow_field, global_offset=None):\n src_pts = grid.view(grid.shape[0], -1, 2)\n batch_size = flow_field.shape[0]\n if src_pts.shape[0] < batch_size:\n q = batch_size // src_pts.shape[0]\n src_pts = src_pts.repeat(q, 1, 1)\n if global_offset is not None:\n n = src_pts.shape[1]\n src_pts = src_pts + global_offset.unsqueeze(1).repeat(1, n, 1)\n offsets = flow_field.view(batch_size, -1, 2)\n dst_pts = src_pts + offsets\n h = kornia.geometry.find_homography_dlt(src_pts, dst_pts)\n return h\n \n @staticmethod\n def get_batch_homography_from_flow_field(flow_field, global_offset=None):\n height, width = flow_field.shape[1], flow_field.shape[2]\n grid = GeometryUtils.gen_2d_grid_torch(height, width).to(flow_field.device)\n return GeometryUtils.get_batch_homography_from_flow_field_sub(grid, flow_field, global_offset)" } ] }, { "paper_id": 15, "paper_details": { "title": "RAPTOR: RECURSIVE ABSTRACTIVE PROCESSING FOR TREE-ORGANIZED RETRIEVAL", "url": "https://arxiv.org/pdf/2401.18059" }, "enviorment_name": "raptor", "repo_original_url": "https://github.com/parthsarthi03/raptor", "project_path": "Benchmark/15-raptor-master/raptor-master", "file_organization": "\nraptor-master/\n cache/\n 9b5ad71b2ce5302211f9c61530b329a4922fc6a4\n demo/\n cinderella/\n sample.txt\n demo.ipynb\n LICENSE.txt\n main.py\n promtp.txt\n raptor/\n cluster_tree_builder.py\n cluster_utils.py\n EmbeddingModels.py\n FaissRetriever.py\n __init__.py\n QAModels.py\n RetrievalAugmentation.py\n Retrievers.py\n SummarizationModels.py\n tree_builder.py\n tree_retriever.py\n tree_structures.py\n utils.py\n raptor_dark.png\n raptor.jpg\n README.md\n requirements.txt\n", "latex_code_path": "Benchmark/15-raptor-master/arXiv-2401.18059v1", "task_details": [ { "task_id": 0, "indent": 1, "script": "\npython main.py\n", "latex_code": "\nOur clustering algorithm is based on Gaussian Mixture Models (GMMs), an approach that offers both flexibility and a probabilistic framework. GMMs assume that data points are generated from a mixture of several Gaussian distributions. \n\nGiven a set of $N$ text segments, each represented as a $d$-dimensional dense vector embedding, the likelihood of a text vector, $\\mathbf{x}$, given its membership in the $k^{th}$ Gaussian distribution, is denoted by\n%\n$\nP(\\mathbf{x}|k) = \\mathcal{N}(\\mathbf{x}; \\mathbf{\\mu}_k, \\mathbf{\\Sigma}_k)\n$.\n%\nThe overall probability distribution is a weighted combination\n%\n$\nP(\\mathbf{x}) = \\sum_{k=1}^{K} \\pi_k \\mathcal{N}(\\mathbf{x}; \\mathbf{\\mu}_k, \\mathbf{\\Sigma}_k)\n$,\n% \nwhere $\\pi_k$ signifies the mixture weight for the $k^{\\mathrm{th}}$ Gaussian distribution.\n", "completion_path": "./raptor/cluster_utils.py", "namespace": "raptor.cluster_utils.GMM_cluster", "type": "function", "signature_position": [ 56, 56 ], "body_position": [ 57, 62 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: We determine K, the optimal number of Gaussian components\n# in the mixture, aligning with the model selection principle for GMMs discussed\n# in the LaTeX snippet.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nn_clusters = get_optimal_clusters(embeddings)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: This step corresponds to setting up the mixture model with\n# K Gaussian distributions, akin to forming the weighted combination\n# P(x) = \u2211 (\u03c0_k * N(x; \u03bc_k, \u03a3_k)) from the LaTeX description.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\ngm = GaussianMixture(n_components=n_clusters, random_state=random_state)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Fitting the GMM to the embeddings estimates \u03bc_k, \u03a3_k, and \u03c0_k,\n# matching the LaTeX mention of using a likelihood-based approach for\n# finding the parameters of each Gaussian distribution.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\ngm.fit(embeddings)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: The GMM generates a probability distribution over clusters for\n# each embedding, reflecting P(k|x) by applying Bayes' rule to the\n# Gaussian mixture. This aligns with the \"probabilistic framework\" noted\n# in the LaTeX text.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nprobs = gm.predict_proba(embeddings)\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: The threshold-based selection of cluster indices for each\n# embedding exemplifies a \"soft clustering\" approach, where text segments\n# can be assigned to multiple clusters if their membership probabilities\n# exceed the threshold.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nlabels = [np.where(prob > threshold)[0] for prob in probs]\n# [End Snippet 5]\n\n# ---------------------------------------------------------------------------\n# Snippet 6: Return the soft cluster assignments and the chosen number of components\n# ---------------------------------------------------------------------------\n# [Begin Snippet 6]\nreturn labels, n_clusters\n# [End Snippet 6]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The LaTeX description does not specify how the optimal number of Gaussian components is determined for the mixture model. In practice, this step involves assessing a range of possible component counts, up to a predefined maximum, and selecting the one that best fits the data based on a specific criterion. This process entails fitting a series of gaussian mixture models to the text embeddings, each with an increasing number of components, and computing the Bayesian Information Criterion (BIC) for each model. The BIC evaluates both the likelihood of the data given the model and a penalty for model complexity, and the number of components yielding the lowest BIC is chosen as optimal.\n - The LaTeX code omits the process of applying a threshold to the probabilities assigned by the mixture model to determine cluster membership. This workflow involves computing the probability that each text segment belongs to each Gaussian component, comparing these probabilities against a cutoff value, and assigning the segment to one or more clusters where the probability exceeds this cutoff.\n\n - Mismatched Details:\n - None\n", "Missing_details": [ "\n- The LaTeX description does not specify how the optimal number of Gaussian components is determined for the mixture model. In practice, this step involves assessing a range of possible component counts, up to a predefined maximum, and selecting the one that best fits the data based on a specific criterion. This process entails fitting a series of gaussian mixture models to the text embeddings, each with an increasing number of components, and computing the Bayesian Information Criterion (BIC) for each model. The BIC evaluates both the likelihood of the data given the model and a penalty for model complexity, and the number of components yielding the lowest BIC is chosen as optimal.\n", "\n- The LaTeX code omits the process of applying a threshold to the probabilities assigned by the mixture model to determine cluster membership. This workflow involves computing the probability that each text segment belongs to each Gaussian component, comparing these probabilities against a cutoff value, and assigning the segment to one or more clusters where the probability exceeds this cutoff.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - embeddings (np.ndarray, shape:[Number of text segments, Dimensionality of embeddings]): Contains the dense vector representations (embeddings) of N text segments, each embedding is d-dimensional.\n - threshold (float): Defines the cutoff level for assigning each text embedding to one or more clusters based on the probability returned by GMM.\n - random_state (int, optional): Purpose: Controls the random number generator for reproducible results in the GaussianMixture model.\n", "Arguments_list": [ { "name": "embeddings", "string": "\n- embeddings (np.ndarray, shape:[Number of text segments, Dimensionality of embeddings]): Contains the dense vector representations (embeddings) of N text segments, each embedding is d-dimensional.\n", "dependency": null }, { "name": "threshold", "string": "\n- threshold (float): Defines the cutoff level for assigning each text embedding to one or more clusters based on the probability returned by GMM.\n", "dependency": null }, { "name": "random_state", "string": "\n- random_state (int, optional): Purpose: Controls the random number generator for reproducible results in the GaussianMixture model.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File Dependency:\n - get_optimal_clusters\n\n Cross-File Dependency: \n - None\n", "intra_file": [ "get_optimal_clusters" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - sklearn.mixture.GaussianMixture\n - numpy.where\n", "list": [ "sklearn.mixture.GaussianMixture", "numpy.where" ] }, "Return": { "Return_String": "\nOutput Variables:\n - labels (List[np.ndarray]): A list of arrays, where each array contains the indices of the clusters to which a given embedding belongs. The assignment is based on whether the probability exceeds the specified threshold.\n - n_clusters (int): The number of clusters (Gaussian components) determined by the function get_optimal_clusters. This is used to instantiate and fit the GaussianMixture model. closer to the positive LLM embeddings and push it away from the negative LLM embeddings. \n", "Return_list": [ { "name": "labels", "string": "\n- labels (List[np.ndarray]): A list of arrays, where each array contains the indices of the clusters to which a given embedding belongs. The assignment is based on whether the probability exceeds the specified threshold.\n", "dependency": null }, { "name": "n_clusters", "string": "\n- n_clusters (int): The number of clusters (Gaussian components) determined by the function get_optimal_clusters. This is used to instantiate and fit the GaussianMixture model. closer to the positive LLM embeddings and push it away from the negative LLM embeddings. \n", "dependency": null } ] }, "ori_python_file": "import logging\nimport random\nfrom abc import ABC, abstractmethod\nfrom typing import List, Optional\nimport numpy as np\nimport tiktoken\nimport umap\nfrom sklearn.mixture import GaussianMixture\nlogging.basicConfig(format=\"%(asctime)s - %(message)s\", level=logging.INFO)\nfrom .tree_structures import Node\nfrom .utils import get_embeddings\nRANDOM_SEED = 42\nrandom.seed(42)\nnp.random.seed(42)\n\ndef global_cluster_embeddings(\n embeddings: np.ndarray,\n dim: int,\n n_neighbors: Optional[int] = None,\n metric: str = \"cosine\",\n random_state=42\n) -> np.ndarray:\n if n_neighbors is None:\n n_neighbors = int((len(embeddings) - 1) ** 0.5)\n reduced_embeddings = umap.UMAP(\n n_neighbors=n_neighbors,\n n_components=dim,\n metric=metric,\n random_state=random_state,\n ).fit_transform(embeddings)\n return reduced_embeddings\n\ndef local_cluster_embeddings(\n embeddings: np.ndarray, dim: int, num_neighbors: int = 10, metric: str = \"cosine\"\n) -> np.ndarray:\n reduced_embeddings = umap.UMAP(\n n_neighbors=num_neighbors, n_components=dim, metric=metric\n ).fit_transform(embeddings)\n return reduced_embeddings\n\ndef get_optimal_clusters(\n embeddings: np.ndarray,\n max_clusters: int = 50,\n random_state: int = RANDOM_SEED\n) -> int:\n max_clusters = min(max_clusters, len(embeddings))\n n_clusters = np.arange(1, max_clusters)\n bics = []\n for n in n_clusters:\n gm = GaussianMixture(n_components=n, random_state=random_state)\n gm.fit(embeddings)\n bics.append(gm.bic(embeddings))\n optimal_clusters = n_clusters[np.argmin(bics)]\n return optimal_clusters\n\ndef GMM_cluster(embeddings: np.ndarray, threshold: float, random_state: int = 0):\n n_clusters = get_optimal_clusters(embeddings)\n gm = GaussianMixture(n_components=n_clusters, random_state=random_state)\n gm.fit(embeddings)\n probs = gm.predict_proba(embeddings)\n labels = [np.where(prob > threshold)[0] for prob in probs]\n return labels, n_clusters\n\ndef perform_clustering(\n embeddings: np.ndarray, dim: int, threshold: float, verbose: bool = False\n) -> List[np.ndarray]:\n reduced_embeddings_global = global_cluster_embeddings(embeddings, min(dim, len(embeddings) -2))\n global_clusters, n_global_clusters = GMM_cluster(\n reduced_embeddings_global, threshold\n )\n if verbose:\n logging.info(f\"Global Clusters: {n_global_clusters}\")\n all_local_clusters = [np.array([]) for _ in range(len(embeddings))]\n total_clusters = 0\n for i in range(n_global_clusters):\n global_cluster_embeddings_ = embeddings[\n np.array([i in gc for gc in global_clusters])\n ]\n if verbose:\n logging.info(\n f\"Nodes in Global Cluster {i}: {len(global_cluster_embeddings_)}\"\n )\n if len(global_cluster_embeddings_) == 0:\n continue\n if len(global_cluster_embeddings_) <= dim + 1:\n local_clusters = [np.array([0]) for _ in global_cluster_embeddings_]\n n_local_clusters = 1\n else:\n reduced_embeddings_local = local_cluster_embeddings(\n global_cluster_embeddings_, dim\n )\n local_clusters, n_local_clusters = GMM_cluster(\n reduced_embeddings_local, threshold\n )\n if verbose:\n logging.info(f\"Local Clusters in Global Cluster {i}: {n_local_clusters}\")\n for j in range(n_local_clusters):\n local_cluster_embeddings_ = global_cluster_embeddings_[\n np.array([j in lc for lc in local_clusters])\n ]\n indices = np.where(\n (embeddings == local_cluster_embeddings_[:, None]).all(-1)\n )[1]\n for idx in indices:\n all_local_clusters[idx] = np.append(\n all_local_clusters[idx], j + total_clusters\n )\n total_clusters += n_local_clusters\n if verbose:\n logging.info(f\"Total Clusters: {total_clusters}\")\n return all_local_clusters\n\nclass ClusteringAlgorithm(ABC):\n @abstractmethod\n def perform_clustering(self, embeddings: np.ndarray, **kwargs) -> List[List[int]]:\n pass\n\nclass RAPTOR_Clustering(ClusteringAlgorithm):\n def perform_clustering(\n nodes: List[Node],\n embedding_model_name: str,\n max_length_in_cluster: int = 3500,\n tokenizer=tiktoken.get_encoding(\"cl100k_base\"),\n reduction_dimension: int = 10,\n threshold: float = 0.1,\n verbose: bool = False,\n ) -> List[List[Node]]:\n embeddings = np.array([node.embeddings[embedding_model_name] for node in nodes])\n clusters = perform_clustering(\n embeddings, dim=reduction_dimension, threshold=threshold\n )\n node_clusters = []\n for label in np.unique(np.concatenate(clusters)):\n indices = [i for i, cluster in enumerate(clusters) if label in cluster]\n cluster_nodes = [nodes[i] for i in indices]\n if len(cluster_nodes) == 1:\n node_clusters.append(cluster_nodes)\n continue\n total_length = sum(\n [len(tokenizer.encode(node.text)) for node in cluster_nodes]\n )\n if total_length > max_length_in_cluster:\n if verbose:\n logging.info(\n f\"reclustering cluster with {len(cluster_nodes)} nodes\"\n )\n node_clusters.extend(\n RAPTOR_Clustering.perform_clustering(\n cluster_nodes, embedding_model_name, max_length_in_cluster\n )\n )\n else:\n node_clusters.append(cluster_nodes)\n return node_clusters" }, { "task_id": 1, "indent": 1, "completion_path": "./raptor/cluster_utils.py", "namespace": "raptor.cluster_utils.global_cluster_embeddings", "type": "function", "signature_position": [ 16, 22 ], "body_position": [ 23, 31 ], "script": "\npython main.py\n", "latex_code": "\nThe high dimensionality of vector embeddings presents a challenge for traditional GMMs, as distance metrics may behave poorly when used to measure similarity in high-dimensional spaces \\citep{aggarwal2001surprising}. To mitigate this, we employ Uniform Manifold Approximation and Projection (UMAP), a manifold learning technique for dimensionality reduction \\citep{mcinnes2018umap}. The number of nearest neighbors parameter, $n\\_neighbors$, in UMAP determines the balance between the preservation of local and global structures. Our algorithm varies $n\\_neighbors$ to create a hierarchical clustering structure: it first identifies global clusters and then performs local clustering within these global clusters. This two-step clustering process captures a broad spectrum of relationships among the text data, from broad themes to specific details.\n", "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: If the parameter n_neighbors is None, compute it as the integer square root of (len(embeddings) - 1).\n# This heuristic balances local and global structure preservation in the UMAP algorithm.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nif n_neighbors is None:\n n_neighbors = int((len(embeddings) - 1) ** 0.5)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: This snippet initializes UMAP with the determined n_neighbors, target dimension (n_components=dim), \n# and specified metric. UMAP then transforms the high-dimensional embeddings into a lower-dimensional space.\n# This operation reflects the LaTeX functionality of using UMAP to mitigate the challenges of high-dimensional data.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nreduced_embeddings = umap.UMAP(\n n_neighbors=n_neighbors,\n n_components=dim,\n metric=metric,\n random_state=random_state,\n).fit_transform(embeddings)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: The final step returns the lower-dimensional embeddings as a NumPy array. This corresponds to delivering the output expected from the dimensionality reduction process as described in the LaTeX code.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nreturn reduced_embeddings\n# [End Snippet 3]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX description lacks mention of a fixed seed or mechanism to ensure reproducibility of the dimensionality reduction process.\n - The LaTeX description does not specify how the size of the local neighborhood is determined when it is not explicitly provided. In the workflow, if this parameter is unspecified, a heuristic is applied to calculate it based on the total number of data points. This calculation involves taking the square root of the number of data points minus one and rounding it to the nearest integer.\n\n Mismatched Details:\n - The LaTeX description emphasizes a hierarchical clustering process (global then local clustering) via UMAP. This function only implements the global dimensionality reduction step, which is consistent with the global clustering phase described.\n", "Missing_details": [ "\n- The LaTeX description lacks mention of a fixed seed or mechanism to ensure reproducibility of the dimensionality reduction process.\n", "\n- The LaTeX description does not specify how the size of the local neighborhood is determined when it is not explicitly provided. In the workflow, if this parameter is unspecified, a heuristic is applied to calculate it based on the total number of data points. This calculation involves taking the square root of the number of data points minus one and rounding it to the nearest integer.\n", "\n- The LaTeX description emphasizes a hierarchical clustering process (global then local clustering) via UMAP. This function only implements the global dimensionality reduction step, which is consistent with the global clustering phase described.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - embeddings (np.ndarray, shape:[num_samples, embedding_dim]): Represents the high-dimensional vector embeddings that need to be reduced.\n - dim (int): The target dimensionality for the reduced embeddings. This integer value tells UMAP how many dimensions to map the data down to.\n - n_neighbors (Optional[int]): Defines the size of the local neighborhood (in terms of the number of neighboring sample points) used by UMAP for manifold approximation. If None, it is computed as the integer square root of (len(embeddings) - 1).\n - metric (str): Specifies the distance metric used by UMAP (e.g., 'cosine' or 'euclidean'). By default, this is set to 'cosine'.\n - random_state (int): Seed for the random number generator to ensure reproducible results in the UMAP algorithm.\n", "Arguments_list": [ { "name": "embeddings", "string": "\n- embeddings (np.ndarray, shape:[num_samples, embedding_dim]): Represents the high-dimensional vector embeddings that need to be reduced.\n", "dependency": null }, { "name": "dim", "string": "\n- dim (int): The target dimensionality for the reduced embeddings. This integer value tells UMAP how many dimensions to map the data down to.\n", "dependency": null }, { "name": "n_neighbors", "string": "\n- n_neighbors (Optional[int]): Defines the size of the local neighborhood (in terms of the number of neighboring sample points) used by UMAP for manifold approximation. If None, it is computed as the integer square root of (len(embeddings) - 1).\n", "dependency": null }, { "name": "metric", "string": "\n- metric (str): Specifies the distance metric used by UMAP (e.g., 'cosine' or 'euclidean'). By default, this is set to 'cosine'.\n", "dependency": null }, { "name": "random_state", "string": " \n- random_state (int): Seed for the random number generator to ensure reproducible results in the UMAP algorithm.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File Dependencies: \n - None\n\n Cross-File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - umap.UMAP \n", "list": [ "umap.UMAP" ] }, "Return": { "Return_String": "\nOutput Variables:\n - reduced_embeddings (np.ndarray, shape=[num_samples, dim]): A 2D array of shape . Each row is the reduced dimensional embedding for the corresponding high-dimensional input.\n", "Return_list": [ { "name": "reduced_embeddings", "string": "\n- reduced_embeddings (np.ndarray, shape=[num_samples, dim]): A 2D array of shape . Each row is the reduced dimensional embedding for the corresponding high-dimensional input.\n", "dependency": null } ] }, "ori_python_file": "import logging\nimport random\nfrom abc import ABC, abstractmethod\nfrom typing import List, Optional\nimport numpy as np\nimport tiktoken\nimport umap\nfrom sklearn.mixture import GaussianMixture\nlogging.basicConfig(format=\"%(asctime)s - %(message)s\", level=logging.INFO)\nfrom .tree_structures import Node\nfrom .utils import get_embeddings\nRANDOM_SEED = 42\nrandom.seed(42)\nnp.random.seed(42)\n\ndef global_cluster_embeddings(\n embeddings: np.ndarray,\n dim: int,\n n_neighbors: Optional[int] = None,\n metric: str = \"cosine\",\n random_state=42\n) -> np.ndarray:\n if n_neighbors is None:\n n_neighbors = int((len(embeddings) - 1) ** 0.5)\n reduced_embeddings = umap.UMAP(\n n_neighbors=n_neighbors,\n n_components=dim,\n metric=metric,\n random_state=random_state,\n ).fit_transform(embeddings)\n return reduced_embeddings\n\ndef local_cluster_embeddings(\n embeddings: np.ndarray, dim: int, num_neighbors: int = 10, metric: str = \"cosine\"\n) -> np.ndarray:\n reduced_embeddings = umap.UMAP(\n n_neighbors=num_neighbors, n_components=dim, metric=metric\n ).fit_transform(embeddings)\n return reduced_embeddings\n\ndef get_optimal_clusters(\n embeddings: np.ndarray,\n max_clusters: int = 50,\n random_state: int = RANDOM_SEED\n) -> int:\n max_clusters = min(max_clusters, len(embeddings))\n n_clusters = np.arange(1, max_clusters)\n bics = []\n for n in n_clusters:\n gm = GaussianMixture(n_components=n, random_state=random_state)\n gm.fit(embeddings)\n bics.append(gm.bic(embeddings))\n optimal_clusters = n_clusters[np.argmin(bics)]\n return optimal_clusters\n\ndef GMM_cluster(embeddings: np.ndarray, threshold: float, random_state: int = 0):\n n_clusters = get_optimal_clusters(embeddings)\n gm = GaussianMixture(n_components=n_clusters, random_state=random_state)\n gm.fit(embeddings)\n probs = gm.predict_proba(embeddings)\n labels = [np.where(prob > threshold)[0] for prob in probs]\n return labels, n_clusters\n\ndef perform_clustering(\n embeddings: np.ndarray, dim: int, threshold: float, verbose: bool = False\n) -> List[np.ndarray]:\n reduced_embeddings_global = global_cluster_embeddings(embeddings, min(dim, len(embeddings) -2))\n global_clusters, n_global_clusters = GMM_cluster(\n reduced_embeddings_global, threshold\n )\n if verbose:\n logging.info(f\"Global Clusters: {n_global_clusters}\")\n all_local_clusters = [np.array([]) for _ in range(len(embeddings))]\n total_clusters = 0\n for i in range(n_global_clusters):\n global_cluster_embeddings_ = embeddings[\n np.array([i in gc for gc in global_clusters])\n ]\n if verbose:\n logging.info(\n f\"Nodes in Global Cluster {i}: {len(global_cluster_embeddings_)}\"\n )\n if len(global_cluster_embeddings_) == 0:\n continue\n if len(global_cluster_embeddings_) <= dim + 1:\n local_clusters = [np.array([0]) for _ in global_cluster_embeddings_]\n n_local_clusters = 1\n else:\n reduced_embeddings_local = local_cluster_embeddings(\n global_cluster_embeddings_, dim\n )\n local_clusters, n_local_clusters = GMM_cluster(\n reduced_embeddings_local, threshold\n )\n if verbose:\n logging.info(f\"Local Clusters in Global Cluster {i}: {n_local_clusters}\")\n for j in range(n_local_clusters):\n local_cluster_embeddings_ = global_cluster_embeddings_[\n np.array([j in lc for lc in local_clusters])\n ]\n indices = np.where(\n (embeddings == local_cluster_embeddings_[:, None]).all(-1)\n )[1]\n for idx in indices:\n all_local_clusters[idx] = np.append(\n all_local_clusters[idx], j + total_clusters\n )\n total_clusters += n_local_clusters\n if verbose:\n logging.info(f\"Total Clusters: {total_clusters}\")\n return all_local_clusters\n\nclass ClusteringAlgorithm(ABC):\n @abstractmethod\n def perform_clustering(self, embeddings: np.ndarray, **kwargs) -> List[List[int]]:\n pass\n\nclass RAPTOR_Clustering(ClusteringAlgorithm):\n def perform_clustering(\n nodes: List[Node],\n embedding_model_name: str,\n max_length_in_cluster: int = 3500,\n tokenizer=tiktoken.get_encoding(\"cl100k_base\"),\n reduction_dimension: int = 10,\n threshold: float = 0.1,\n verbose: bool = False,\n ) -> List[List[Node]]:\n embeddings = np.array([node.embeddings[embedding_model_name] for node in nodes])\n clusters = perform_clustering(\n embeddings, dim=reduction_dimension, threshold=threshold\n )\n node_clusters = []\n for label in np.unique(np.concatenate(clusters)):\n indices = [i for i, cluster in enumerate(clusters) if label in cluster]\n cluster_nodes = [nodes[i] for i in indices]\n if len(cluster_nodes) == 1:\n node_clusters.append(cluster_nodes)\n continue\n total_length = sum(\n [len(tokenizer.encode(node.text)) for node in cluster_nodes]\n )\n if total_length > max_length_in_cluster:\n if verbose:\n logging.info(\n f\"reclustering cluster with {len(cluster_nodes)} nodes\"\n )\n node_clusters.extend(\n RAPTOR_Clustering.perform_clustering(\n cluster_nodes, embedding_model_name, max_length_in_cluster\n )\n )\n else:\n node_clusters.append(cluster_nodes)\n return node_clusters" }, { "task_id": 2, "indent": 1, "completion_path": "./raptor/cluster_utils.py", "namespace": "raptor.cluster_utils.get_optimal_clusters", "type": "function", "signature_position": [ 41, 45 ], "body_position": [ 46, 54 ], "script": "\npython main.py\n", "latex_code": "\nTo determine the optimal number of clusters, we employ the Bayesian Information Criterion (BIC) for model selection. BIC not only penalizes model complexity but also rewards goodness of fit \\citep{schwarz1978estimating}.\n%\nThe BIC for a given GMM is\n%\n$\nBIC = \\ln(N)k - 2\\ln(\\hat{L})\n$,\n%\nwhere $N$ is the number of text segments (or data points), $k$ is the number of model parameters, and $\\hat{L}$ is the maximized value of the likelihood function of the model. In the context of GMM, the number of parameters $k$ is a function of the dimensionality of the input vectors and the number of clusters.\n", "ReferenceCode_With_Comments": "\nmax_clusters = min(max_clusters, len(embeddings))\nn_clusters = np.arange(1, max_clusters)\nbics = []\n\n# ---------------------------------------------------------------------------\n# Snippet 1: Iterate over each candidate number of clusters, instantiate a Gaussian Mixture Model, fit it to the embeddings, and compute its BIC score.\n# This loop implements the model selection process where the BIC reflects both model complexity and goodness of fit.\n# LaTeX Mapping: For each candidate model, computing BIC = ln(N)k - 2ln(\u0139).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nfor n in n_clusters:\n gm = GaussianMixture(n_components=n, random_state=random_state)\n gm.fit(embeddings)\n bics.append(gm.bic(embeddings))\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Identify the candidate cluster count corresponding to the minimum BIC score.\n# This selection method reflects the LaTeX description of rewarding goodness of fit while penalizing model complexity.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\noptimal_clusters = n_clusters[np.argmin(bics)]\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Return the optimal number of clusters as determined by the minimum BIC.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nreturn optimal_clusters\n# [End Snippet 3]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details: \n - The LaTeX description does not specify how to constrain the candidate cluster range based on the number of available data points. In the reference implementation, the maximum candidate count is limited to the number of samples to ensure that the candidate models are feasible, a step that is not explicitly described in the LaTeX.\n - The LaTeX does not describe the process of systematically storing and comparing BIC values across all candidate models to identify the optimal number of clusters. The workflow would entail initializing a collection to hold BIC scores, calculating the BIC for each candidate model after fitting it to the data, adding each score to the collection, and then selecting the cluster count associated with the smallest BIC value as the optimal solution.\n\n Mismatched Details: \n - None\n", "Missing_details": [ "\n- The LaTeX description does not specify how to constrain the candidate cluster range based on the number of available data points. In the reference implementation, the maximum candidate count is limited to the number of samples to ensure that the candidate models are feasible, a step that is not explicitly described in the LaTeX.\n", "\n- The LaTeX does not describe the process of systematically storing and comparing BIC values across all candidate models to identify the optimal number of clusters. The workflow would entail initializing a collection to hold BIC scores, calculating the BIC for each candidate model after fitting it to the data, adding each score to the collection, and then selecting the cluster count associated with the smallest BIC value as the optimal solution.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - embeddings (np.ndarray, shape=[num_samples, num_features]): Numerical representations (embeddings) of text segments or data points to be clustered.\n - max_clusters (int): An upper bound on the number of clusters to evaluate when searching for the optimal cluster count.\n - random_state (int): Seed for the random number generator to ensure reproducible clustering results.\n", "Arguments_list": [ { "name": "embeddings", "string": "\n- embeddings (np.ndarray, shape=[num_samples, num_features]): Numerical representations (embeddings) of text segments or data points to be clustered.\n", "dependency": null }, { "name": "max_clusters", "string": "\n- max_clusters (int): An upper bound on the number of clusters to evaluate when searching for the optimal cluster count.\n", "dependency": null }, { "name": "random_state", "string": "\n- random_state (int): Seed for the random number generator to ensure reproducible clustering results.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-File Dependencies:\n - None\n \n - Cross-File Dependencies: None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - sklearn.mixture.GaussianMixture\n - numpy.arange\n - numpy.argmin\n", "list": [ "sklearn.mixture.GaussianMixture", "numpy.arange", "numpy.argmin" ] }, "Return": { "Return_String": "\nOutput Variables:\n - optimal_clusters (int): The number of clusters that minimizes the Bayesian Information Criterion (BIC), indicating the optimal cluster count for the data.\n", "Return_list": [ { "name": "optimal_clusters", "string": "\n- optimal_clusters (int): The number of clusters that minimizes the Bayesian Information Criterion (BIC), indicating the optimal cluster count for the data.\n", "dependency": null } ] }, "ori_python_file": "import logging\nimport random\nfrom abc import ABC, abstractmethod\nfrom typing import List, Optional\nimport numpy as np\nimport tiktoken\nimport umap\nfrom sklearn.mixture import GaussianMixture\nlogging.basicConfig(format=\"%(asctime)s - %(message)s\", level=logging.INFO)\nfrom .tree_structures import Node\nfrom .utils import get_embeddings\nRANDOM_SEED = 42\nrandom.seed(42)\nnp.random.seed(42)\n\ndef global_cluster_embeddings(\n embeddings: np.ndarray,\n dim: int,\n n_neighbors: Optional[int] = None,\n metric: str = \"cosine\",\n random_state=42\n) -> np.ndarray:\n if n_neighbors is None:\n n_neighbors = int((len(embeddings) - 1) ** 0.5)\n reduced_embeddings = umap.UMAP(\n n_neighbors=n_neighbors,\n n_components=dim,\n metric=metric,\n random_state=random_state,\n ).fit_transform(embeddings)\n return reduced_embeddings\n\ndef local_cluster_embeddings(\n embeddings: np.ndarray, dim: int, num_neighbors: int = 10, metric: str = \"cosine\"\n) -> np.ndarray:\n reduced_embeddings = umap.UMAP(\n n_neighbors=num_neighbors, n_components=dim, metric=metric\n ).fit_transform(embeddings)\n return reduced_embeddings\n\ndef get_optimal_clusters(\n embeddings: np.ndarray,\n max_clusters: int = 50,\n random_state: int = RANDOM_SEED\n) -> int:\n max_clusters = min(max_clusters, len(embeddings))\n n_clusters = np.arange(1, max_clusters)\n bics = []\n for n in n_clusters:\n gm = GaussianMixture(n_components=n, random_state=random_state)\n gm.fit(embeddings)\n bics.append(gm.bic(embeddings))\n optimal_clusters = n_clusters[np.argmin(bics)]\n return optimal_clusters\n\ndef GMM_cluster(embeddings: np.ndarray, threshold: float, random_state: int = 0):\n n_clusters = get_optimal_clusters(embeddings)\n gm = GaussianMixture(n_components=n_clusters, random_state=random_state)\n gm.fit(embeddings)\n probs = gm.predict_proba(embeddings)\n labels = [np.where(prob > threshold)[0] for prob in probs]\n return labels, n_clusters\n\ndef perform_clustering(\n embeddings: np.ndarray, dim: int, threshold: float, verbose: bool = False\n) -> List[np.ndarray]:\n reduced_embeddings_global = global_cluster_embeddings(embeddings, min(dim, len(embeddings) -2))\n global_clusters, n_global_clusters = GMM_cluster(\n reduced_embeddings_global, threshold\n )\n if verbose:\n logging.info(f\"Global Clusters: {n_global_clusters}\")\n all_local_clusters = [np.array([]) for _ in range(len(embeddings))]\n total_clusters = 0\n for i in range(n_global_clusters):\n global_cluster_embeddings_ = embeddings[\n np.array([i in gc for gc in global_clusters])\n ]\n if verbose:\n logging.info(\n f\"Nodes in Global Cluster {i}: {len(global_cluster_embeddings_)}\"\n )\n if len(global_cluster_embeddings_) == 0:\n continue\n if len(global_cluster_embeddings_) <= dim + 1:\n local_clusters = [np.array([0]) for _ in global_cluster_embeddings_]\n n_local_clusters = 1\n else:\n reduced_embeddings_local = local_cluster_embeddings(\n global_cluster_embeddings_, dim\n )\n local_clusters, n_local_clusters = GMM_cluster(\n reduced_embeddings_local, threshold\n )\n if verbose:\n logging.info(f\"Local Clusters in Global Cluster {i}: {n_local_clusters}\")\n for j in range(n_local_clusters):\n local_cluster_embeddings_ = global_cluster_embeddings_[\n np.array([j in lc for lc in local_clusters])\n ]\n indices = np.where(\n (embeddings == local_cluster_embeddings_[:, None]).all(-1)\n )[1]\n for idx in indices:\n all_local_clusters[idx] = np.append(\n all_local_clusters[idx], j + total_clusters\n )\n total_clusters += n_local_clusters\n if verbose:\n logging.info(f\"Total Clusters: {total_clusters}\")\n return all_local_clusters\n\nclass ClusteringAlgorithm(ABC):\n @abstractmethod\n def perform_clustering(self, embeddings: np.ndarray, **kwargs) -> List[List[int]]:\n pass\n\nclass RAPTOR_Clustering(ClusteringAlgorithm):\n def perform_clustering(\n nodes: List[Node],\n embedding_model_name: str,\n max_length_in_cluster: int = 3500,\n tokenizer=tiktoken.get_encoding(\"cl100k_base\"),\n reduction_dimension: int = 10,\n threshold: float = 0.1,\n verbose: bool = False,\n ) -> List[List[Node]]:\n embeddings = np.array([node.embeddings[embedding_model_name] for node in nodes])\n clusters = perform_clustering(\n embeddings, dim=reduction_dimension, threshold=threshold\n )\n node_clusters = []\n for label in np.unique(np.concatenate(clusters)):\n indices = [i for i, cluster in enumerate(clusters) if label in cluster]\n cluster_nodes = [nodes[i] for i in indices]\n if len(cluster_nodes) == 1:\n node_clusters.append(cluster_nodes)\n continue\n total_length = sum(\n [len(tokenizer.encode(node.text)) for node in cluster_nodes]\n )\n if total_length > max_length_in_cluster:\n if verbose:\n logging.info(\n f\"reclustering cluster with {len(cluster_nodes)} nodes\"\n )\n node_clusters.extend(\n RAPTOR_Clustering.perform_clustering(\n cluster_nodes, embedding_model_name, max_length_in_cluster\n )\n )\n else:\n node_clusters.append(cluster_nodes)\n return node_clusters" }, { "task_id": 3, "indent": 2, "completion_path": "./main.py", "namespace": "main.CustomSummarizationModel.summarize", "type": "method", "signature_position": [ 60, 60 ], "body_position": [ 61, 74 ], "script": "\npython main.py\n", "latex_code": "\n\\paragraph{Model-Based Summarization}\\label{subsec:summarization}\nAfter clustering the nodes using Gaussian Mixture Models, the nodes in each cluster are sent to a language model for summarization. This step allows the model to transform large chunks of text into concise, coherent summaries of the selected nodes. For our experiments, we use \\texttt{gpt-3.5-turbo} to generate the summaries. The summarization step condenses the potentially large volume of retrieved information into a manageable size. We provide statistics on the compression due to the summarization in Appendix \\ref{app:summarystats} and the prompt used for summarization in Appendix \\ref{app:prompt}. \n", "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Implements prompt construction per LaTeX Appendix prompt requirements\n# Maps to \"prompt used for summarization\" reference in LaTeX\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nprompt=f\"<|begin_of_text|><|start_header_id|>system<|end_header_id|>\\n\\nYou are a helpful assistant.<|eot_id|>\\n<|start_header_id|>user<|end_header_id|>\\n\\nWrite a summary of the following, including as many key details as possible: {context}:<|eot_id|>\\n<|start_header_id|>assistant<|end_header_id|>\"\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Converts text to model-compatible input tensors\n# Implements preprocessing step implied by LaTeX's model usage description\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\ninput_ids = self.tokenizer(prompt, return_tensors=\"pt\", padding=True).to(\n self.model.device\n)\ninput_length = input_ids['input_ids'].shape[-1]\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Executes summarization via autoregressive generation\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nres = self.model.generate(**input_ids, max_new_tokens=max_tokens, pad_token_id=self.tokenizer.eos_token_id, do_sample=False)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Converts model output to readable text\n# Return the summary\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nsummary = self.tokenizer.decode(res[0][input_length:], skip_special_tokens=True)\nreturn summary\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The decoding strategy used by the model is greedy search.\n \n Mismatched Details:\n - Appling LLama-3.1-8B-Instruct rather than GPT-3.5-turbo as the summrization model. \n", "Missing_details": [ "\n- The decoding strategy used by the model is greedy search.\n" ], "Mismatched_details": [ "\n- Appling LLama-3.1-8B-Instruct rather than GPT-3.5-turbo as the summrization model. \n" ] }, "Arguments": { "string": "\nInput Variables:\n - context (str): The textual content that needs to be summarized.\n - max_tokens (int, optional, default=500): The maximum number of tokens that the language model should generate in the summary.\n - self.model (str): The model used for summarization which is defined in the __init__ function.\n", "Arguments_list": [ { "name": "context", "string": "\n- context (str): The textual content that needs to be summarized.\n", "dependency": null }, { "name": "max_tokens", "string": "\n- max_tokens (int, optional, default=500): The maximum number of tokens that the language model should generate in the summary.\n", "dependency": null }, { "name": "self.model", "string": "\n- self.model (str): The model used for summarization which is defined in the __init__ function.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File Dependencies: \n - None\n \n Cross-File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs\n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - summary (str): The function returns a summarized string generated by the language model. In case of an error during API call, it returns \"\".\n", "Return_list": [ { "name": "summary", "string": "\n- summary (str): The function returns a summarized string generated by the language model. In case of an error during API call, it returns \"\".\n", "dependency": null } ] }, "ori_python_file": "# NOTE: An OpenAI API key must be set here for application initialization, even if not in use.\n# If you're not utilizing OpenAI models, assign a placeholder string (e.g., \"not_used\").\nimport os\nimport torch\nfrom raptor import RetrievalAugmentation, RetrievalAugmentationConfig, SBertEmbeddingModel, UnifiedQAModel\nfrom sentence_transformers import SentenceTransformer\nfrom transformers import AutoTokenizer, pipeline\nfrom transformers import LlamaForCausalLM, BitsAndBytesConfig, PreTrainedTokenizerFast\nfrom raptor import BaseSummarizationModel, BaseQAModel, BaseEmbeddingModel, RetrievalAugmentationConfig, RetrievalAugmentation\nimport random\nimport os\nimport numpy as np\nos.environ['PYTHONHASHSEED'] = str(42)\nos.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\n# print(f\"- current seed is {42}\\n\")\nnp.random.seed(42)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\ntorch.use_deterministic_algorithms(True)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nrandom.seed(42)\ntorch.cuda.synchronize()\n\nos.environ[\"DATA_GYM_CACHE_DIR\"] = \"./cache\"\n# Cinderella story defined in sample.txt\nimport argparse\nparser = argparse.ArgumentParser(description='')\nparser.add_argument('--TestCode', action='store_true')\nparser.add_argument('--collapse', action='store_false')\nargs = parser.parse_args()\n\n\n\nclass CustomSummarizationModel(BaseSummarizationModel):\n def __init__(self):\n # Initialize your model here\n bnb_config = BitsAndBytesConfig(\n load_in_4bit=True,\n bnb_4bit_use_double_quant=True,\n bnb_4bit_quant_type=\"nf4\",\n bnb_4bit_compute_dtype=torch.bfloat16\n )\n modelpath = \"meta-llama/Llama-3.1-8B-Instruct\"\n self.tokenizer = PreTrainedTokenizerFast.from_pretrained(\n modelpath,\n use_fast=False,\n padding_side=\"left\",\n )\n self.tokenizer.pad_token_id = 0 if self.tokenizer.pad_token_id is None else self.tokenizer.pad_token_id\n self.tokenizer.bos_token_id = 1\n self.model = LlamaForCausalLM.from_pretrained(\n modelpath,\n quantization_config=bnb_config,\n device_map=\"auto\",\n )\n self.model.eval()\n \n def summarize(self, context, max_tokens=150):\n prompt=f\"\"\"<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\n You are a helpful assistant.<|eot_id|>\n <|start_header_id|>user<|end_header_id|>\n\n Write a summary of the following, including as many key details as possible: {context}:<|eot_id|>\n <|start_header_id|>assistant<|end_header_id|>\"\"\"\n input_ids = self.tokenizer(prompt, return_tensors=\"pt\", padding=True).to(\n self.model.device\n )\n input_length = input_ids['input_ids'].shape[-1]\n res = self.model.generate(**input_ids, max_new_tokens=max_tokens, pad_token_id=self.tokenizer.eos_token_id, do_sample=False)\n summary = self.tokenizer.decode(res[0][input_length:], skip_special_tokens=True)\n return summary\n\nclass GEMMAQAModel(BaseQAModel):\n def __init__(self, model_name= \"meta-llama/Llama-3.1-8B-Instruct\"):\n bnb_config = BitsAndBytesConfig(\n load_in_4bit=True,\n bnb_4bit_use_double_quant=True,\n bnb_4bit_quant_type=\"nf4\",\n bnb_4bit_compute_dtype=torch.bfloat16\n )\n modelpath = \"meta-llama/Llama-3.1-8B-Instruct\"\n self.tokenizer = PreTrainedTokenizerFast.from_pretrained(\n modelpath,\n use_fast=False,\n padding_side=\"left\",\n )\n self.tokenizer.pad_token_id = 0 if self.tokenizer.pad_token_id is None else self.tokenizer.pad_token_id\n self.tokenizer.bos_token_id = 1\n self.model = LlamaForCausalLM.from_pretrained(\n modelpath,\n quantization_config=bnb_config,\n device_map=\"auto\",\n )\n self.model.eval()\n\n def answer_question(self, context, question):\n prompt=f\"\"\"<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n \n You are a question-answering portal.<|eot_id|>\n <|start_header_id|>user<|end_header_id|>\n \n Given the following information, answer the question as concisely as you can. Do not provide any explanation.\\n\\nDocuments:\\n{context}\\n\\nQuestion:\\n{question}\\n\\nAnswer the question as concisely as you can given the information. Do not provide any explanation.\\n\\nAnswer:<|eot_id|>\n <|start_header_id|>assistant<|end_header_id|>\"\"\"\n input_ids = self.tokenizer(prompt, return_tensors=\"pt\", padding=True).to(\n self.model.device\n )\n input_length = input_ids['input_ids'].shape[-1]\n res = self.model.generate(**input_ids, max_new_tokens=256, pad_token_id=self.tokenizer.eos_token_id, do_sample=False)\n answer = self.tokenizer.decode(res[0][input_length:], skip_special_tokens=True)\n return answer\n\nclass SBertEmbeddingModel(BaseEmbeddingModel):\n def __init__(self, model_name=\"sentence-transformers/multi-qa-mpnet-base-cos-v1\"):\n self.model = SentenceTransformer(model_name)\n\n def create_embedding(self, text):\n return self.model.encode(text)\n\n\nwith open('demo/sample.txt', 'r') as file:\n text = file.read()\n\nprint(text[:100])\n\nsummarization_model = CustomSummarizationModel()\nqamodel = GEMMAQAModel()\nembedmodel = SBertEmbeddingModel()\nconfig = RetrievalAugmentationConfig(qa_model=qamodel, embedding_model=embedmodel, summarization_model=summarization_model)\nRA = RetrievalAugmentation(config)\n\n# construct the tree\nRA.add_documents(text)\nquestion = list()\nquestion.append(\"How did Cinderella reach her happy ending ?\")\nquestion.append(\"Who is the main protagonist of the story?\")\nquestion.append(\"What role does the hazel-tree play in the narrative?\")\nquestion.append(\"How does Cinderella demonstrate her perseverance despite her hardships?\")\nquestion.append(\"What tasks does Cinderella\u2019s stepmother assign her, and how do they affect her?\")\nquestion.append(\"In what ways do the birds help Cinderella throughout the story?\")\nquestion.append(\"How is the theme of transformation portrayed, especially regarding Cinderella's appearance and fortune?\")\nquestion.append(\"What significance does the golden slipper hold in the prince\u2019s quest?\")\nquestion.append(\"How are the step-sisters depicted, and what consequences do they face for their actions?\")\nquestion.append(\"What challenges does Cinderella encounter when trying to attend the festival?\")\nfor q in question:\n answer = RA.answer_question(question=q, collapse_tree=args.collapse)\n print(\"Answer: \", answer)\n" }, { "task_id": 4, "indent": 2, "completion_path": "./raptor/tree_retriever.py", "namespace": "raptor.tree_retriever.TreeRetriever.retrieve_information", "type": "method", "signature_position": [ 149, 151 ], "body_position": [ 152, 174 ], "script": "\npython main.py --collapse\n", "latex_code": "\nThe \\textbf{tree traversal} method first selects the top-k most relevant root nodes based on their cosine similarity to the query embedding. The children of these selected nodes are considered at the next layer and the top-k nodes are selected from this pool again based on their cosine similarity to the query vector. This process is repeated until we reach the leaf nodes. Finally, the text from all selected nodes is concatenated to form the retrieved context. The algorithm's steps are outlined below:\n\n\\begin{enumerate}\n\\item Start at the root layer of the RAPTOR tree. Compute the cosine similarity between the query embedding and the embeddings of all nodes present at this initial layer.\n\\item Choose the top-$k$ nodes based on the highest cosine similarity scores, forming the set $S_1$.\n\\item Proceed to the child nodes of the elements in set $S_1$. Compute the cosine similarity between the query vector and the vector embeddings of these child nodes.\n\\item Select the top $k$ child nodes with the highest cosine similarity scores to the query, forming the set $S_2$.\n\\item Continue this process recursively for $d$ layers, producing sets $S_1, S_2, \\ldots, S_d$.\n\\item Concatenate sets $S_1$ through $S_d$ to assemble the relevant context to the query.\n\\end{enumerate}\n\nBy adjusting the depth $d$ and the number of nodes $k$ selected at each layer, the tree traversal method offers control over the specificity and breadth of the information retrieved. The algorithm starts with a broad outlook by considering the top layers of the tree and progressively focuses on finer details as it descends through the lower layers. \n", "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Generate the embedding for the query.\n# This corresponds to the LaTeX step where the query embedding is prepared for \n# similarity comparison against node embeddings.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nquery_embedding = self.create_embedding(query)\n# [End Snippet 1]\n\nselected_nodes = []\nnode_list = current_nodes\n\nfor layer in range(num_layers):\n\n # -----------------------------------------------------------------------\n # Snippet 2: Compute embeddings for all nodes in the current layer.\n # This implements the step where node texts are transformed into vector embeddings for similarity calculation.\n # -----------------------------------------------------------------------\n # [Begin Snippet 2]\n embeddings = get_embeddings(node_list, context_embedding_model)\n # [End Snippet 2]\n\n # -----------------------------------------------------------------------\n # Snippet 3: Calculate the similarity (or distance) between the query embedding and each node's embedding.\n # This corresponds to the LaTeX step of computing cosine similarity between the query and node embeddings.\n # -----------------------------------------------------------------------\n # [Begin Snippet 3]\n distances = distances_from_embeddings(query_embedding, embeddings)\n # [End Snippet 3]\n\n # -----------------------------------------------------------------------\n # Snippet 4: Obtain indices of nodes sorted by similarity (from most to least relevant).\n # This mirrors the LaTeX instruction to select the top-k nodes based on similarity scores.\n # -----------------------------------------------------------------------\n # [Begin Snippet 4]\n indices = indices_of_nearest_neighbors_from_distances(distances)\n # [End Snippet 4]\n\n # -----------------------------------------------------------------------\n # Snippet 5: Select the best indices based on the configured selection mode.\n # If 'threshold' mode is active, filter indices by a similarity threshold.\n # If 'top_k' mode is used, select the top-k indices.\n # This implements the LaTeX step of forming the set S_i (e.g., S_1, S_2, ...) of relevant nodes.\n # -----------------------------------------------------------------------\n # [Begin Snippet 5]\n if selection_mode == \"threshold\":\n best_indices = [\n index for index in indices if distances[index] > threshold\n ]\n elif selection_mode == \"top_k\":\n best_indices = indices[: top_k]\n # [End Snippet 5]\n\n nodes_to_add = [node_list[idx] for idx in best_indices]\n selected_nodes.extend(nodes_to_add)\n\n # -----------------------------------------------------------------------\n # Snippet 6: For all layers except the final one, gather the child nodes of the selected nodes.\n # This implements the recursive descent described in the LaTeX: proceeding to the children of S_i to form S_(i+1).\n # -----------------------------------------------------------------------\n # [Begin Snippet 6]\n if layer != num_layers - 1:\n child_nodes = []\n for index in best_indices:\n child_nodes.extend(node_list[index].children)\n child_nodes = list(dict.fromkeys(child_nodes))\n node_list = [tree.all_nodes[i] for i in child_nodes]\n # [End Snippet 6]\n\n# ---------------------------------------------------------------------------\n# Snippet 7: After processing all layers, concatenate the texts from the selected nodes.\n# This step forms the final retrieved context, as outlined in the LaTeX description.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 7]\ncontext = get_text(selected_nodes)\n# [End Snippet 7]\n\n# ---------------------------------------------------------------------------\n# Snippet 8: Return the selected nodes and the concatenated context.\n# This finalizes the retrieval process by outputting both the node selection and the assembled context.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 8]\nreturn selected_nodes, context\n# [End Snippet 8]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX description does not specify the exact procedure for obtaining and processing child nodes after selecting nodes at a given layer. In the reference code, after selecting the top nodes based on cosine similarity, a dedicated step retrieves the child nodes from a global tree structure and then removes duplicates before proceeding.\n - The LaTeX description does not mention the specific handling of the final layer in the traversal process. The workflow requires that, after selecting nodes at each layer and gathering their children for the next iteration, the process stops at the specified depth without attempting to fetch children of the nodes in the last layer.\n \n Mismatched Details:\n - The LaTeX description implies a uniform application of the top-k selection across all layers, but the reference code supports an alternative threshold-based selection mode in addition to top-k. The mismatched workflow here involves an optional step where, instead of always picking a fixed number of nodes with the highest similarity, nodes are filtered based on whether their similarity exceeds a predefined threshold.\n", "Missing_details": [ "\n- The LaTeX description does not specify the exact procedure for obtaining and processing child nodes after selecting nodes at a given layer. In the reference code, after selecting the top nodes based on cosine similarity, a dedicated step retrieves the child nodes from a global tree structure and then removes duplicates before proceeding.\n", "\n- The LaTeX description does not mention the specific handling of the final layer in the traversal process. The workflow requires that, after selecting nodes at each layer and gathering their children for the next iteration, the process stops at the specified depth without attempting to fetch children of the nodes in the last layer.\n" ], "Mismatched_details": [ "\n- The LaTeX description implies a uniform application of the top-k selection across all layers, but the reference code supports an alternative threshold-based selection mode in addition to top-k. The mismatched workflow here involves an optional step where, instead of always picking a fixed number of nodes with the highest similarity, nodes are filtered based on whether their similarity exceeds a predefined threshold.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - current_nodes (List[raptor.tree_structures.Node]): A list of the current nodes (raptor.tree_structures.Node objects) from which to begin the tree traversal.\n - query (str): The query string or text for which we aim to retrieve relevant context.\n - num_layers (int): The number of layers to traverse down the tree from the current nodes. \n - selection_mode (str): This attribute defines the retrieval strategy to be employed by the TreeRetriever. It typically accepts values such as \"threshold\" or \"top-k\".\n - threshold (float): This attribute specifies a threshold value used during the retrieval process.\n - top_k (int): This integer attribute sets the number of top nodes to select at each level during the tree traversal retrieval process.\n - context_embedding_model (str): A string identifier for the embedding model used to generate vector representations.\n - tree (an object of the Tree class defined in raptor/tree_structures.py): This attribute holds the RAPTOR tree data structure, which organizes text segments into a hierarchical cluster structure.\n", "Arguments_list": [ { "name": "current_nodes", "string": "\n- current_nodes (List[raptor.tree_structures.Node]): A list of the current nodes (raptor.tree_structures.Node objects) from which to begin the tree traversal.\n", "dependency": null }, { "name": "query", "string": "\n- query (str): The query string or text for which we aim to retrieve relevant context.\n", "dependency": null }, { "name": "num_layers", "string": "\n- num_layers (int): The number of layers to traverse down the tree from the current nodes.\n", "dependency": null }, { "name": "selection_mode", "string": "\n- selection_mode (str): This attribute defines the retrieval strategy to be employed by the TreeRetriever. It typically accepts values such as \"threshold\" or \"top-k\".\n", "dependency": null }, { "name": "threshold", "string": "\n- threshold (float): This attribute specifies a threshold value used during the retrieval process.\n", "dependency": null }, { "name": "top_k", "string": "\n- top_k (int): This integer attribute sets the number of top nodes to select at each level during the tree traversal retrieval process.\n", "dependency": null }, { "name": "context_embedding_model", "string": "\n- context_embedding_model (str): A string identifier for the embedding model used to generate vector representations.\n", "dependency": null }, { "name": "tree", "string": "\n- tree (an object of the Tree class defined in raptor/tree_structures.py): This attribute holds the RAPTOR tree data structure, which organizes text segments into a hierarchical cluster structure.\n", "dependency": "raptor.tree_structures.Tree" } ] }, "dependency": { "string": "\nDependencies:\n Intra-File Dependencies:\n - TreeRetriever.create_embedding\n\n Cross-File Dependencies:\n - utils.get_embeddings\n - utils.distances_from_embeddings\n - utils.indices_of_nearest_neighbors_from_distances\n - utils.get_text\n", "intra_file": [ "TreeRetriever.create_embedding" ], "cross_file": [ "utils.get_embeddings", "utils.distances_from_embeddings", "utils.indices_of_nearest_neighbors_from_distances" ] }, "external_APIs": { "string": "\nExternal APIs: \n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - selected_nodes (List[raptor.tree_structures.Node]): The list of nodes (raptor.tree_structures.Node objects) deemed most relevant to the query across all traversed layers.\n - context (str): A single string concatenating the text content of all the selected nodes. \n", "Return_list": [ { "name": "selected_nodes", "string": "\n- selected_nodes (List[raptor.tree_structures.Node]): The list of nodes (raptor.tree_structures.Node objects) deemed most relevant to the query across all traversed layers.\n", "dependency": "raptor.tree_structures.Node" }, { "name": "context", "string": "\n- context (str): A single string concatenating the text content of all the selected nodes. \n", "dependency": null } ] }, "ori_python_file": "import logging\nimport os\nfrom typing import Dict, List, Set\nimport tiktoken\nfrom tenacity import retry, stop_after_attempt, wait_random_exponential\nfrom .EmbeddingModels import BaseEmbeddingModel, OpenAIEmbeddingModel\nfrom .Retrievers import BaseRetriever\nfrom .tree_structures import Node, Tree\nfrom .utils import (distances_from_embeddings, get_children, get_embeddings,\n get_node_list, get_text,\n indices_of_nearest_neighbors_from_distances,\n reverse_mapping)\nlogging.basicConfig(format=\"%(asctime)s - %(message)s\", level=logging.INFO)\n\nclass TreeRetrieverConfig:\n def __init__(\n self,\n tokenizer=None,\n threshold=None,\n top_k=None,\n selection_mode=None,\n context_embedding_model=None,\n embedding_model=None,\n num_layers=None,\n start_layer=None,\n ):\n if tokenizer is None:\n tokenizer = tiktoken.get_encoding(\"cl100k_base\")\n self.tokenizer = tokenizer\n if threshold is None:\n threshold = 0.5\n if not isinstance(threshold, float) or not (0 <= threshold <= 1):\n raise ValueError(\"threshold must be a float between 0 and 1\")\n self.threshold = threshold\n if top_k is None:\n top_k = 5\n if not isinstance(top_k, int) or top_k < 1:\n raise ValueError(\"top_k must be an integer and at least 1\")\n self.top_k = top_k\n if selection_mode is None:\n selection_mode = \"top_k\"\n if not isinstance(selection_mode, str) or selection_mode not in [\n \"top_k\",\n \"threshold\",\n ]:\n raise ValueError(\n \"selection_mode must be a string and either 'top_k' or 'threshold'\"\n )\n self.selection_mode = selection_mode\n if context_embedding_model is None:\n context_embedding_model = \"OpenAI\"\n if not isinstance(context_embedding_model, str):\n raise ValueError(\"context_embedding_model must be a string\")\n self.context_embedding_model = context_embedding_model\n if embedding_model is None:\n embedding_model = OpenAIEmbeddingModel()\n if not isinstance(embedding_model, BaseEmbeddingModel):\n raise ValueError(\n \"embedding_model must be an instance of BaseEmbeddingModel\"\n )\n self.embedding_model = embedding_model\n if num_layers is not None:\n if not isinstance(num_layers, int) or num_layers < 0:\n raise ValueError(\"num_layers must be an integer and at least 0\")\n self.num_layers = num_layers\n if start_layer is not None:\n if not isinstance(start_layer, int) or start_layer < 0:\n raise ValueError(\"start_layer must be an integer and at least 0\")\n self.start_layer = start_layer\n \n\n def log_config(self):\n config_log = \"\"\"\n TreeRetrieverConfig:\n Tokenizer: {tokenizer}\n Threshold: {threshold}\n Top K: {top_k}\n Selection Mode: {selection_mode}\n Context Embedding Model: {context_embedding_model}\n Embedding Model: {embedding_model}\n Num Layers: {num_layers}\n Start Layer: {start_layer}\n \"\"\".format(\n tokenizer=self.tokenizer,\n threshold=self.threshold,\n top_k=self.top_k,\n selection_mode=self.selection_mode,\n context_embedding_model=self.context_embedding_model,\n embedding_model=self.embedding_model,\n num_layers=self.num_layers,\n start_layer=self.start_layer,\n )\n return config_log\n\nclass TreeRetriever(BaseRetriever):\n \n def __init__(self, config, tree) -> None:\n if not isinstance(tree, Tree):\n raise ValueError(\"tree must be an instance of Tree\")\n if config.num_layers is not None and config.num_layers > tree.num_layers + 1:\n raise ValueError(\n \"num_layers in config must be less than or equal to tree.num_layers + 1\"\n )\n if config.start_layer is not None and config.start_layer > tree.num_layers:\n raise ValueError(\n \"start_layer in config must be less than or equal to tree.num_layers\"\n )\n self.tree = tree\n self.num_layers = (\n config.num_layers if config.num_layers is not None else tree.num_layers + 1\n )\n self.start_layer = (\n config.start_layer if config.start_layer is not None else tree.num_layers\n )\n if self.num_layers > self.start_layer + 1:\n raise ValueError(\"num_layers must be less than or equal to start_layer + 1\")\n self.tokenizer = config.tokenizer\n self.top_k = config.top_k\n self.threshold = config.threshold\n self.selection_mode = config.selection_mode\n self.embedding_model = config.embedding_model\n self.context_embedding_model = config.context_embedding_model\n self.tree_node_index_to_layer = reverse_mapping(self.tree.layer_to_nodes)\n logging.info(\n f\"Successfully initialized TreeRetriever with Config {config.log_config()}\"\n )\n \n def create_embedding(self, text: str) -> List[float]:\n return self.embedding_model.create_embedding(text)\n \n def retrieve_information_collapse_tree(self, query: str, top_k: int, max_tokens: int, tokenizer, tree, context_embedding_model) -> str:\n query_embedding = self.create_embedding(query)\n selected_nodes = []\n node_list = get_node_list(tree.all_nodes)\n embeddings = get_embeddings(node_list, context_embedding_model)\n distances = distances_from_embeddings(query_embedding, embeddings)\n indices = indices_of_nearest_neighbors_from_distances(distances)\n total_tokens = 0\n for idx in indices[:top_k]:\n node = node_list[idx]\n node_tokens = len(tokenizer.encode(node.text))\n if total_tokens + node_tokens > max_tokens:\n break\n selected_nodes.append(node)\n total_tokens += node_tokens\n context = get_text(selected_nodes)\n return selected_nodes, context\n \n def retrieve_information(\n self, current_nodes: List[Node], query: str, num_layers: int, selection_mode, threshold, top_k, context_embedding_model, tree\n ) -> str:\n query_embedding = self.create_embedding(query)\n selected_nodes = []\n node_list = current_nodes\n for layer in range(num_layers):\n embeddings = get_embeddings(node_list, context_embedding_model)\n distances = distances_from_embeddings(query_embedding, embeddings)\n indices = indices_of_nearest_neighbors_from_distances(distances)\n if selection_mode == \"threshold\":\n best_indices = [\n index for index in indices if distances[index] > threshold\n ]\n elif selection_mode == \"top_k\":\n best_indices = indices[: top_k]\n nodes_to_add = [node_list[idx] for idx in best_indices]\n selected_nodes.extend(nodes_to_add)\n if layer != num_layers - 1:\n child_nodes = []\n for index in best_indices:\n child_nodes.extend(node_list[index].children)\n child_nodes = list(dict.fromkeys(child_nodes))\n node_list = [tree.all_nodes[i] for i in child_nodes]\n context = get_text(selected_nodes)\n return selected_nodes, context\n \n def retrieve(\n self,\n query: str,\n start_layer: int = None,\n num_layers: int = None,\n top_k: int = 10,\n max_tokens: int = 3500,\n collapse_tree: bool = True,\n return_layer_information: bool = False,\n ) -> str:\n if not isinstance(query, str):\n raise ValueError(\"query must be a string\")\n if not isinstance(max_tokens, int) or max_tokens < 1:\n raise ValueError(\"max_tokens must be an integer and at least 1\")\n if not isinstance(collapse_tree, bool):\n raise ValueError(\"collapse_tree must be a boolean\")\n start_layer = self.start_layer if start_layer is None else start_layer\n num_layers = self.num_layers if num_layers is None else num_layers\n if not isinstance(start_layer, int) or not (\n 0 <= start_layer <= self.tree.num_layers\n ):\n raise ValueError(\n \"start_layer must be an integer between 0 and tree.num_layers\"\n )\n if not isinstance(num_layers, int) or num_layers < 1:\n raise ValueError(\"num_layers must be an integer and at least 1\")\n if num_layers > (start_layer + 1):\n raise ValueError(\"num_layers must be less than or equal to start_layer + 1\")\n if collapse_tree:\n logging.info(f\"Using collapsed_tree\")\n selected_nodes, context = self.retrieve_information_collapse_tree(\n query, top_k, max_tokens, self.tokenizer, self.tree, self.context_embedding_model\n )\n else:\n layer_nodes = self.tree.layer_to_nodes[start_layer]\n selected_nodes, context = self.retrieve_information(\n layer_nodes, query, num_layers, self.selection_mode, self.threshold, self.top_k, self.context_embedding_model, self.tree\n )\n if return_layer_information:\n layer_information = []\n for node in selected_nodes:\n layer_information.append(\n {\n \"node_index\": node.index,\n \"layer_number\": self.tree_node_index_to_layer[node.index],\n }\n )\n return context, layer_information\n return context" }, { "task_id": 5, "indent": 2, "completion_path": "./raptor/tree_retriever.py", "namespace": "raptor.tree_retriever.TreeRetriever.retrieve_information_collapse_tree", "type": "method", "signature_position": [ 131, 131 ], "body_position": [ 132, 147 ], "script": "\npython main.py\n", "latex_code": "\nThe \\textbf{collapsed tree} approach offers a simpler way to search for relevant information by considering all nodes in the tree simultaneously, as depicted in Figure \\ref{fig:retrieval-mechanism}. Instead of going layer-by-layer, this method flattens the multi-layered tree into a single layer, essentially bringing all the nodes onto the same level for comparison. The steps for this method are outlined below:\n\\begin{enumerate}\n\\item First, collapse the entire RAPTOR tree into a single layer. This new set of nodes, denoted as \\(C\\), contains nodes from every layer of the original tree.\n\\item Next, calculate the cosine similarity between the query embedding and the embeddings of all nodes present in the collapsed set \\(C\\).\n\\item Finally, pick the top-\\(k\\) nodes that have the highest cosine similarity scores with the query. Keep adding nodes to the result set until you reach a predefined maximum number of tokens, ensuring you don't exceed the model's input limitations.\n\\end{enumerate}\n", "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Generate query embedding for similarity comparison\n# Implements LaTeX step 2: \"calculate cosine similarity between query embedding\"\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nquery_embedding = self.create_embedding(query)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Collapse tree into single layer node list\n# Implements LaTeX step 1: \"collapse entire RAPTOR tree into single layer\"\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nselected_nodes = []\nnode_list = get_node_list(tree.all_nodes)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Compute embeddings for all collapsed nodes\n# Implements LaTeX step 2 preparation for similarity calculation\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nembeddings = get_embeddings(node_list, context_embedding_model)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Calculate cosine distances between query and nodes\n# Implements LaTeX step 2: \"calculate cosine similarity between query embedding\"\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\ndistances = distances_from_embeddings(query_embedding, embeddings)\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Sort nodes by similarity to query\n# Implements LaTeX step 3: \"pick top-k nodes with highest similarity scores\"\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nindices = indices_of_nearest_neighbors_from_distances(distances)\n# [End Snippet 5]\n\n\n# ---------------------------------------------------------------------------\n# Snippet 6: Select nodes until token limit is reached\n# Implements LaTeX step 3: \"keep adding nodes until predefined maximum tokens\"\n# Discrepancy: Code uses dual top_k + token constraint vs paper's single token limit\n# ---------------------------------------------------------------------------\n# [Begin Snippet 6]\ntotal_tokens = 0\nfor idx in indices[:top_k]:\n node = node_list[idx]\n node_tokens = len(tokenizer.encode(node.text))\n\n if total_tokens + node_tokens > max_tokens:\n break\n\n selected_nodes.append(node)\n total_tokens += node_tokens\n# [End Snippet 6]\n\n# ---------------------------------------------------------------------------\n# Snippet 7: Aggregate text from selected nodes\n# Implements final LaTeX step output: \"concatenate to form retrieved context\"\n# Return output variables\n# ---------------------------------------------------------------------------\n# [Begin Snippet 7]\ncontext = get_text(selected_nodes)\n\nreturn selected_nodes, context\n# [End Snippet 7]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details: \n - The LaTeX description does not specify how the tree structure is accessed or traversed to collect all nodes into a single layer. The process requires a mechanism to systematically gather every node\u2014regardless of its position in the hierarchy\u2014into a unified collection. This involves either retrieving a precomputed list of all nodes or implementing a traversal method that explores the tree\u2019s structure, ensuring no nodes are omitted, before collapsing them into a single set for further processing.\n\n Mismatched Details:\n - The Python code implements this by iterating through the top-k nodes and stopping if adding the next node would exceed the token limit. \n \n", "Missing_details": [ "\n- The LaTeX description does not specify how the tree structure is accessed or traversed to collect all nodes into a single layer. The process requires a mechanism to systematically gather every node\u2014regardless of its position in the hierarchy\u2014into a unified collection. This involves either retrieving a precomputed list of all nodes or implementing a traversal method that explores the tree\u2019s structure, ensuring no nodes are omitted, before collapsing them into a single set for further processing.\n" ], "Mismatched_details": [ "\n- The Python code implements this by iterating through the top-k nodes and stopping if adding the next node would exceed the token limit. \n" ] }, "Arguments": { "string": "\nInput Variables:\n - query (str): The search string or user query for which relevant information should be retrieved from the tree.\n - top_k (int): The maximum number of nodes to consider based on their similarity to the query before checking token constraints.\n - max_tokens (int): The upper limit on the total number of tokens allowed in the retrieved context to avoid exceeding model input restrictions.\n - tokenizer (tiktoken.Encoding): An encoding object used to tokenize node texts,\n - tree (an object of the Tree class defined in raptor/tree_structures.py): This attribute holds the RAPTOR tree data structure, which organizes text segments into a hierarchical cluster structure.\n - context_embedding_model (str): A string identifier for the embedding model used to generate vector representations (embeddings)\n", "Arguments_list": [ { "name": "query", "string": "\n- query (str): The search string or user query for which relevant information should be retrieved from the tree.\n", "dependency": null }, { "name": "top_k", "string": "\n- top_k (int): The maximum number of nodes to consider based on their similarity to the query before checking token constraints.\n", "dependency": null }, { "name": "max_tokens", "string": "\n- max_tokens (int): The upper limit on the total number of tokens allowed in the retrieved context to avoid exceeding model input restrictions.\n", "dependency": null }, { "name": "tokenizer", "string": "\n- tokenizer (tiktoken.Encoding): An encoding object used to tokenize node texts,\n", "dependency": "tiktoken.Encoding" }, { "name": "tree", "string": "\n- tree (an object of the Tree class defined in raptor/tree_structures.py): This attribute holds the RAPTOR tree data structure, which organizes text segments into a hierarchical cluster structure.\n", "dependency": "raptor.tree_structures.Tree" }, { "name": "context_embedding_model", "string": "\n- context_embedding_model (str): A string identifier for the embedding model used to generate vector representations (embeddings)\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra-File Dependencies:\n - TreeRetriever.create_embedding\n\n Cross-File Dependencies:\n - utils.get_node_list\n - utils.get_embeddings\n - utils.distances_from_embeddings\n - utils.indices_of_nearest_neighbors_from_distances\n - utils.get_text\n", "intra_file": [ "TreeRetriever.create_embedding" ], "cross_file": [ "utils.get_node_list", "utils.get_embeddings", "utils.distances_from_embeddings", "utils.indices_of_nearest_neighbors_from_distances", "utils.get_text" ] }, "external_APIs": { "string": "\nExternal APIs: \n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - selected_nodes (list[raptor.tree_structures.Node]): A list of raptor.tree_structures.Node objects deemed most relevant to the query without exceeding the token limit. \n - context (str): A concatenated string composed of the selected node texts. \n", "Return_list": [ { "name": "selected_nodes", "string": "\n- selected_nodes (list[raptor.tree_structures.Node]): A list of raptor.tree_structures.Node objects deemed most relevant to the query without exceeding the token limit.\n", "dependency": "raptor.tree_structures.Node" }, { "name": "context", "string": "\n- context (str): A concatenated string composed of the selected node texts. \n", "dependency": null } ] }, "ori_python_file": "import logging\nimport os\nfrom typing import Dict, List, Set\nimport tiktoken\nfrom tenacity import retry, stop_after_attempt, wait_random_exponential\nfrom .EmbeddingModels import BaseEmbeddingModel, OpenAIEmbeddingModel\nfrom .Retrievers import BaseRetriever\nfrom .tree_structures import Node, Tree\nfrom .utils import (distances_from_embeddings, get_children, get_embeddings,\n get_node_list, get_text,\n indices_of_nearest_neighbors_from_distances,\n reverse_mapping)\nlogging.basicConfig(format=\"%(asctime)s - %(message)s\", level=logging.INFO)\n\nclass TreeRetrieverConfig:\n def __init__(\n self,\n tokenizer=None,\n threshold=None,\n top_k=None,\n selection_mode=None,\n context_embedding_model=None,\n embedding_model=None,\n num_layers=None,\n start_layer=None,\n ):\n if tokenizer is None:\n tokenizer = tiktoken.get_encoding(\"cl100k_base\")\n self.tokenizer = tokenizer\n if threshold is None:\n threshold = 0.5\n if not isinstance(threshold, float) or not (0 <= threshold <= 1):\n raise ValueError(\"threshold must be a float between 0 and 1\")\n self.threshold = threshold\n if top_k is None:\n top_k = 5\n if not isinstance(top_k, int) or top_k < 1:\n raise ValueError(\"top_k must be an integer and at least 1\")\n self.top_k = top_k\n if selection_mode is None:\n selection_mode = \"top_k\"\n if not isinstance(selection_mode, str) or selection_mode not in [\n \"top_k\",\n \"threshold\",\n ]:\n raise ValueError(\n \"selection_mode must be a string and either 'top_k' or 'threshold'\"\n )\n self.selection_mode = selection_mode\n if context_embedding_model is None:\n context_embedding_model = \"OpenAI\"\n if not isinstance(context_embedding_model, str):\n raise ValueError(\"context_embedding_model must be a string\")\n self.context_embedding_model = context_embedding_model\n if embedding_model is None:\n embedding_model = OpenAIEmbeddingModel()\n if not isinstance(embedding_model, BaseEmbeddingModel):\n raise ValueError(\n \"embedding_model must be an instance of BaseEmbeddingModel\"\n )\n self.embedding_model = embedding_model\n if num_layers is not None:\n if not isinstance(num_layers, int) or num_layers < 0:\n raise ValueError(\"num_layers must be an integer and at least 0\")\n self.num_layers = num_layers\n if start_layer is not None:\n if not isinstance(start_layer, int) or start_layer < 0:\n raise ValueError(\"start_layer must be an integer and at least 0\")\n self.start_layer = start_layer\n \n\n def log_config(self):\n config_log = \"\"\"\n TreeRetrieverConfig:\n Tokenizer: {tokenizer}\n Threshold: {threshold}\n Top K: {top_k}\n Selection Mode: {selection_mode}\n Context Embedding Model: {context_embedding_model}\n Embedding Model: {embedding_model}\n Num Layers: {num_layers}\n Start Layer: {start_layer}\n \"\"\".format(\n tokenizer=self.tokenizer,\n threshold=self.threshold,\n top_k=self.top_k,\n selection_mode=self.selection_mode,\n context_embedding_model=self.context_embedding_model,\n embedding_model=self.embedding_model,\n num_layers=self.num_layers,\n start_layer=self.start_layer,\n )\n return config_log\n\nclass TreeRetriever(BaseRetriever):\n \n def __init__(self, config, tree) -> None:\n if not isinstance(tree, Tree):\n raise ValueError(\"tree must be an instance of Tree\")\n if config.num_layers is not None and config.num_layers > tree.num_layers + 1:\n raise ValueError(\n \"num_layers in config must be less than or equal to tree.num_layers + 1\"\n )\n if config.start_layer is not None and config.start_layer > tree.num_layers:\n raise ValueError(\n \"start_layer in config must be less than or equal to tree.num_layers\"\n )\n self.tree = tree\n self.num_layers = (\n config.num_layers if config.num_layers is not None else tree.num_layers + 1\n )\n self.start_layer = (\n config.start_layer if config.start_layer is not None else tree.num_layers\n )\n if self.num_layers > self.start_layer + 1:\n raise ValueError(\"num_layers must be less than or equal to start_layer + 1\")\n self.tokenizer = config.tokenizer\n self.top_k = config.top_k\n self.threshold = config.threshold\n self.selection_mode = config.selection_mode\n self.embedding_model = config.embedding_model\n self.context_embedding_model = config.context_embedding_model\n self.tree_node_index_to_layer = reverse_mapping(self.tree.layer_to_nodes)\n logging.info(\n f\"Successfully initialized TreeRetriever with Config {config.log_config()}\"\n )\n \n def create_embedding(self, text: str) -> List[float]:\n return self.embedding_model.create_embedding(text)\n \n def retrieve_information_collapse_tree(self, query: str, top_k: int, max_tokens: int, tokenizer, tree, context_embedding_model) -> str:\n query_embedding = self.create_embedding(query)\n selected_nodes = []\n node_list = get_node_list(tree.all_nodes)\n embeddings = get_embeddings(node_list, context_embedding_model)\n distances = distances_from_embeddings(query_embedding, embeddings)\n indices = indices_of_nearest_neighbors_from_distances(distances)\n total_tokens = 0\n for idx in indices[:top_k]:\n node = node_list[idx]\n node_tokens = len(tokenizer.encode(node.text))\n if total_tokens + node_tokens > max_tokens:\n break\n selected_nodes.append(node)\n total_tokens += node_tokens\n context = get_text(selected_nodes)\n return selected_nodes, context\n \n def retrieve_information(\n self, current_nodes: List[Node], query: str, num_layers: int, selection_mode, threshold, top_k, context_embedding_model, tree\n ) -> str:\n query_embedding = self.create_embedding(query)\n selected_nodes = []\n node_list = current_nodes\n for layer in range(num_layers):\n embeddings = get_embeddings(node_list, context_embedding_model)\n distances = distances_from_embeddings(query_embedding, embeddings)\n indices = indices_of_nearest_neighbors_from_distances(distances)\n if selection_mode == \"threshold\":\n best_indices = [\n index for index in indices if distances[index] > threshold\n ]\n elif selection_mode == \"top_k\":\n best_indices = indices[: top_k]\n nodes_to_add = [node_list[idx] for idx in best_indices]\n selected_nodes.extend(nodes_to_add)\n if layer != num_layers - 1:\n child_nodes = []\n for index in best_indices:\n child_nodes.extend(node_list[index].children)\n child_nodes = list(dict.fromkeys(child_nodes))\n node_list = [tree.all_nodes[i] for i in child_nodes]\n context = get_text(selected_nodes)\n return selected_nodes, context\n \n def retrieve(\n self,\n query: str,\n start_layer: int = None,\n num_layers: int = None,\n top_k: int = 10,\n max_tokens: int = 3500,\n collapse_tree: bool = True,\n return_layer_information: bool = False,\n ) -> str:\n if not isinstance(query, str):\n raise ValueError(\"query must be a string\")\n if not isinstance(max_tokens, int) or max_tokens < 1:\n raise ValueError(\"max_tokens must be an integer and at least 1\")\n if not isinstance(collapse_tree, bool):\n raise ValueError(\"collapse_tree must be a boolean\")\n start_layer = self.start_layer if start_layer is None else start_layer\n num_layers = self.num_layers if num_layers is None else num_layers\n if not isinstance(start_layer, int) or not (\n 0 <= start_layer <= self.tree.num_layers\n ):\n raise ValueError(\n \"start_layer must be an integer between 0 and tree.num_layers\"\n )\n if not isinstance(num_layers, int) or num_layers < 1:\n raise ValueError(\"num_layers must be an integer and at least 1\")\n if num_layers > (start_layer + 1):\n raise ValueError(\"num_layers must be less than or equal to start_layer + 1\")\n if collapse_tree:\n logging.info(f\"Using collapsed_tree\")\n selected_nodes, context = self.retrieve_information_collapse_tree(\n query, top_k, max_tokens, self.tokenizer, self.tree, self.context_embedding_model\n )\n else:\n layer_nodes = self.tree.layer_to_nodes[start_layer]\n selected_nodes, context = self.retrieve_information(\n layer_nodes, query, num_layers, self.selection_mode, self.threshold, self.top_k, self.context_embedding_model, self.tree\n )\n if return_layer_information:\n layer_information = []\n for node in selected_nodes:\n layer_information.append(\n {\n \"node_index\": node.index,\n \"layer_number\": self.tree_node_index_to_layer[node.index],\n }\n )\n return context, layer_information\n return context" } ] }, { "paper_id": 16, "paper_details": { "title": "Less is KEN: a Universal and Simple Non-Parametric Pruning Algorithm for Large Language Models", "url": "https://arxiv.org/abs/2402.03142" }, "enviorment_name": "ken", "repo_original_url": "https://github.com/itsmattei/ken", "project_path": "Benchmark/16-KEN-main/KEN-main", "file_organization": "\nKEN-main/\n compare.py\n env.sh\n KEN/\n model_compression/\n compress_file.py\n pretrained_model_injection/\n inject_all_layers.py\n inject_attention_layers.py\n __pycache__/\n inject_all_layers.cpython-310.pyc\n setup/\n easy_train_large_models.py\n easy_train.py\n __pycache__/\n easy_train.cpython-310.pyc\n trained_model_injection/\n inject_all_layers.py\n inject_attention_layers.py\n LICENSE\n main.py\n README.md\n requirements.txt.txt\n trained_model/\n config.json\n model.safetensors\n", "latex_code_path": "Benchmark/16-KEN-main/arXiv-2402.03142v2", "task_details": [ { "task_id": 0, "indent": 2, "script": "\npython main.py\n", "latex_code": "\n\\paragraph{Step 1: Parameter Extraction and KDE Calculation} Given a pre-trained matrix $W^{0}$ of a layer $l$: \n\\begin{equation*}\n W^{0} = \\{w_{1,1}^0, ..., w_{n,m}^0\\} \\quad | \\quad W^{0}\\in \\mathbb{R}^{n \\times m}\n\\end{equation*}\nand its corresponding fine-tuned counterpart $W^{t}$:\n \\begin{equation*}\n W^{t} = \\{w_{1,1}^{t}, ..., w_{n,m}^{t}\\} \\quad | \\quad W^{t} \\in \\mathbb{R}^{n \\times m}\n\\end{equation*}\nfor each row $r_i^t$ of the fine-tuned matrix $W^t$:\n\\begin{equation*}\n r_{i}^t = \\{w_{i,1}^t, ... , w_{i,m}^t\\} \\quad \\forall i \\in [1,n]\n\\end{equation*}\nKEN calculates the KDE distribution of the row $r_i^t$ using a bandwidth parameter $h$ determined following Scott\u2019s rule of thumb \\cite{scott2015multivariate}.\n\\begin{equation*}\n h = 1.06 \\cdot \\hat{\\sigma}\\cdot n^{-\\frac{1}{5}}\n\\end{equation*}\nwhere $\\hat{\\sigma}$ is the standard deviation of $r_i^t$.\n", "completion_path": "./KEN/pretrained_model_injection/inject_all_layers.py", "namespace": "KEN.pretrained_model_injection.inject_all_layers.Kernel_Density.estimate_pdf", "type": "method", "signature_position": [ 15, 15 ], "body_position": [ 16, 28 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Compute the standard deviation of the input array, which is essential\n# for determining the bandwidth parameter using Scott\u2019s rule as described in the LaTeX section.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\ncont_samp_std = np.std(array)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Determine the minimum value in the array to establish the lower bound\n# for the range over which the KDE will be evaluated.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\ncont_samp_min = min(array)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Identify the maximum value in the array to set the upper bound\n# for the KDE evaluation range.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\ncont_samp_max = max(array)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Compute the optimal bandwidth using Scott\u2019s rule of thumb, which scales\n# the bandwidth based on the standard deviation and the number of samples.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\ncont_samp_len = len(array)\noptimal_bandwidth = 1.06 * cont_samp_std * np.power(cont_samp_len, -1 / 5)\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Ensure the bandwidth is a positive value by taking its absolute,\n# as required by the KDE algorithm.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nbandwidthKDE = abs(optimal_bandwidth)\n# [End Snippet 5]\n\n# ---------------------------------------------------------------------------\n# Snippet 6: Initialize and fit the Kernel Density Estimation model using the specified\n# kernel function and the calculated bandwidth.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 6]\nkde_object = KernelDensity(kernel=kernel_function, bandwidth=bandwidthKDE).fit(array.reshape(-1, 1))\n# [End Snippet 6]\n\n# ---------------------------------------------------------------------------\n# Snippet 7: Generate a range of values between the minimum and maximum of the array\n# over which the KDE will be evaluated, ensuring a sufficient number of points\n# as specified by num_of_example.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 7]\nX_plot = np.linspace(cont_samp_min, cont_samp_max, num_of_example)[:, np.newaxis]\n# [End Snippet 7]\n\n# ---------------------------------------------------------------------------\n# Snippet 8: Compute the log density estimates for the generated range of values\n# using the fitted KDE model.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 8]\nkde_LogDensity_estimate = kde_object.score_samples(X_plot)\n# [End Snippet 8]\n\n# ---------------------------------------------------------------------------\n# Snippet 9: Convert the log density estimates to actual density values by exponentiating,\n# and round the results for simplicity.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 9]\nkde_estimate = np.exp(kde_LogDensity_estimate)\nkde_estimate = list([round(elem) for elem in kde_estimate])\n# [End Snippet 9]\n\n# ---------------------------------------------------------------------------\n# Snippet 10: Return the estimated density values along with the corresponding\n# range of evaluation points.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 10]\nX = X_plot.flatten()\nreturn kde_estimate, X \n# [End Snippet 10]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX description does not specify how to ensure the bandwidth parameter remains positive before applying it to the kernel density estimation. In practice, after calculating the bandwidth using the provided formula (involving the standard deviation and sample size), an additional step is needed to take the absolute value of the result. This ensures the bandwidth is valid for the KDE algorithm, which requires a positive value, especially in edge cases where numerical errors or zero variance might occur.\n - The LaTeX code omits the process of generating a flattened array of evaluation points for the density estimate. After determining the range of values from the minimum to the maximum of the input data and creating evenly spaced points across this range, a step is required to convert this set of points into a one-dimensional format. This flattened array is then used to compute and return the density estimates, ensuring compatibility with subsequent operations or outputs.\n - The LaTeX description lacks instructions on transforming the logarithmic density estimates into actual density values. After fitting the KDE model and evaluating it over the range of points, the workflow should include exponentiating the logarithmic scores to obtain the probability density values, followed by rounding these values to integers for the final output.\n \n Mismatched Details:\n - None\n", "Missing_details": [ "\n- The LaTeX description does not specify how to ensure the bandwidth parameter remains positive before applying it to the kernel density estimation. In practice, after calculating the bandwidth using the provided formula (involving the standard deviation and sample size), an additional step is needed to take the absolute value of the result. This ensures the bandwidth is valid for the KDE algorithm, which requires a positive value, especially in edge cases where numerical errors or zero variance might occur.\n", "\n- The LaTeX code omits the process of generating a flattened array of evaluation points for the density estimate. After determining the range of values from the minimum to the maximum of the input data and creating evenly spaced points across this range, a step is required to convert this set of points into a one-dimensional format. This flattened array is then used to compute and return the density estimates, ensuring compatibility with subsequent operations or outputs.\n", "\n- The LaTeX description lacks instructions on transforming the logarithmic density estimates into actual density values. After fitting the KDE model and evaluating it over the range of points, the workflow should include exponentiating the logarithmic scores to obtain the probability density values, followed by rounding these values to integers for the final output.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - array (numpy.ndarray, dtype=float, shape=(m,)): Array containing the data points for which the PDF is to be estimated. Each element represents a feature value from a row of the fine-tuned matrix \\( W^{t} \\).\n - kernel_function (str): \n The kernel function to use for KDE (e.g., 'gaussian').\n - num_of_example (int): \n The number of points to generate in the evaluation range for the KDE.\n", "Arguments_list": [ { "name": "array", "string": "\n- array (numpy.ndarray, dtype=float, shape=(m,)):\n Array containing the data points for which the PDF is to be estimated. Each element represents a feature value from a row of the fine-tuned matrix \\( W^{t} \\).\n", "dependency": null }, { "name": "kernel_function", "string": "\n- kernel_function (str):\n The kernel function to use for KDE (e.g., 'gaussian').\n", "dependency": null }, { "name": "num_of_example", "string": "\n- num_of_example (int):\n The number of points to generate in the evaluation range for the KDE.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n Intra File Dependencies: \n - None\n\n Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - numpy.linspace\n - sklearn.neighbors.KernelDensity\n - numpy.exp\n - numpy.std\n - numpy.linspace\n - numpy.power\n", "list": [ "numpy.linspace", "sklearn.neighbors.KernelDensity", "numpy.exp", "numpy.std", "numpy.linspace", "numpy.power" ] }, "Return": { "Return_String": "\nOutput Variables:\n - kde_estimate (list[float]): A list containing the estimated density values computed by the KDE over the specified range.\n - X (numpy.ndarray, shape=(self.num_of_example, 1)): A flattened array of points at which the KDE has been evaluated, spanning from the minimum to the maximum of the input array.\n", "Return_list": [ { "name": "kde_estimate", "string": "\n- kde_estimate (list[float]): A list containing the estimated density values computed by the KDE over the specified range.\n", "dependency": null }, { "name": "X", "string": "\n- X (numpy.ndarray, shape=(self.num_of_example, 1)): A flattened array of points at which the KDE has been evaluated, spanning from the minimum to the maximum of the input array.\n", "dependency": null } ] }, "ori_python_file": "import numpy as np\nimport torch\nfrom sklearn.neighbors import KernelDensity\nnp.random.seed(42)\ntorch.manual_seed(42)\nclass Kernel_Density:\n def __init__(\n self,\n num_of_example,\n kernel_function='gaussian'\n ):\n self.num_of_example = num_of_example\n self.kernel_function = kernel_function\n \n def estimate_pdf(self, array, kernel_function, num_of_example):\n cont_samp_std = np.std(array)\n cont_samp_len = len(array)\n cont_samp_min = min(array)\n cont_samp_max = max(array)\n optimal_bandwidth = 1.06 * cont_samp_std * np.power(cont_samp_len, -1 / 5)\n bandwidthKDE = abs(optimal_bandwidth)\n kde_object = KernelDensity(kernel=kernel_function, bandwidth=bandwidthKDE).fit(array.reshape(-1, 1))\n X_plot = np.linspace(cont_samp_min, cont_samp_max, num_of_example)[:, np.newaxis]\n kde_LogDensity_estimate = kde_object.score_samples(X_plot)\n kde_estimate = np.exp(kde_LogDensity_estimate)\n kde_estimate = list([round(elem) for elem in kde_estimate])\n X = X_plot.flatten()\n return kde_estimate, X\n \n def closest(self, lst, K):\n lst = np.asarray(lst)\n idx = (np.abs(lst - K)).argmin()\n return idx\n \n def find_nearest(self, lista, element_to_find):\n closest_KDE_list = []\n for elem in element_to_find:\n index = self.closest(lista, elem)\n closest_KDE_list.append(lista[index])\n lista = np.delete(lista, index, axis=0)\n return closest_KDE_list\n \n def order_base_on_KDE_values(self, KDE_list, points_list):\n max_value = np.max(KDE_list)\n ordered_points_list = []\n for index in range(max_value, -1, -1):\n indices = [i for i, x in enumerate(KDE_list) if x == index]\n for idx in indices:\n ordered_points_list.append(points_list[idx])\n return ordered_points_list\n \n def light_matrix(self, matrix_row, cls_list):\n mask = np.isin(matrix_row, cls_list)\n matrix_row[~mask] = 0\n return matrix_row\n \n def extract_KDE(self, array):\n array = array.cpu().flatten().numpy()\n kde, points = self.estimate_pdf(array, self.kernel_function, self.num_of_example)\n ordered_points_list = self.order_base_on_KDE_values(kde, points)\n cls_list = self.find_nearest(array, ordered_points_list)\n light_matrix = self.light_matrix(array, cls_list)\n return light_matrix\n\nclass Kernel_injection:\n def __init__(\n self,\n model_trained,\n model_W0,\n num_param,\n kernel_function='gaussian'\n ):\n self.model_trained = model_trained\n self.model_W0 = model_W0\n self.num_param = num_param\n self.kernel_function = kernel_function\n self.state_dict_trained = self.model_trained.state_dict()\n self.state_dict_W0 = self.model_W0.state_dict()\n \n def substitute_array(self, array_a, array_b):\n output_array = np.where(array_a != 0, array_a, array_b)\n return output_array\n \n def injection_row(self, param_name, index):\n KD = Kernel_Density(self.num_param, self.kernel_function)\n W0_matrix = self.state_dict_W0[param_name][index]\n trained_matrix = self.state_dict_trained[param_name][index]\n lm = KD.extract_KDE(trained_matrix)\n lm = self.substitute_array(lm, W0_matrix.numpy())\n self.state_dict_W0[param_name][index] = torch.from_numpy(lm)\n return self.state_dict_W0\n \n def injection_array(self, param_name):\n KD = Kernel_Density(self.num_param, self.kernel_function)\n W0_matrix = self.state_dict_W0[param_name]\n trained_matrix = self.state_dict_trained[param_name]\n lm = KD.extract_KDE(trained_matrix)\n lm = self.substitute_array(lm, W0_matrix.numpy())\n self.state_dict_W0[param_name] = torch.from_numpy(lm)\n return self.state_dict_W0\n \n def injection_values(self, param):\n matrix = self.state_dict_W0[param]\n shape_matrix = len(matrix.shape)\n if shape_matrix == 1:\n injection_state_dict = self.injection_array(param)\n else:\n for index in range(0, matrix.shape[0]):\n injection_state_dict = self.injection_row(param, index)\n return injection_state_dict\n \n def inject_all_parameters_combined(self):\n params = [param for param in self.state_dict_W0][:-1]\n for param in params:\n matrix = self.state_dict_W0[param]\n shape_matrix = len(matrix.shape)\n if shape_matrix == 1:\n KD = Kernel_Density(self.num_param, self.kernel_function)\n W0_vector = matrix.numpy()\n trained_vector = self.state_dict_trained[param].cpu().flatten().numpy()\n optimized_vector = KD.extract_KDE(torch.tensor(trained_vector))\n optimized_vector = self.substitute_array(optimized_vector, W0_vector)\n self.state_dict_W0[param] = torch.from_numpy(optimized_vector)\n else:\n for index in range(matrix.shape[0]):\n KD = Kernel_Density(self.num_param, self.kernel_function)\n W0_row = self.state_dict_W0[param][index].numpy()\n trained_row = self.state_dict_trained[param][index].cpu().flatten().numpy()\n optimized_row = KD.extract_KDE(torch.tensor(trained_row))\n optimized_row = self.substitute_array(optimized_row, W0_row)\n self.state_dict_W0[param][index] = torch.from_numpy(optimized_row)\n self.model_W0.load_state_dict(self.state_dict_W0)\n model_W0 = self.model_W0\n return model_W0" }, { "task_id": 1, "indent": 2, "script": "\npython main.py\n", "latex_code": "\n\\paragraph{Step 2: Parameter Retention and Pre-trained Value Reset} \nThe $k$ points that best fit the $r_i^t$ row distribution are identified using the KDE likelihood, while the others are reset to their pre-trained values. This process results in an optimized row $\\hat{r}_i$:\n\n\\begin{equation*}\n \\hat{r}_{i} = \\{\\hat{w}_{i,1}, ... , \\hat{w}_{i,m}\\} \\quad \\forall i \\in [1,n]\n\\end{equation*}\ncomputed using the following binary function:\n\\begin{equation}\nf(\\hat{w}_{i,j}) = \n \\begin{cases}\n w_{i,j}^t \\tab $if$ \\quad w_{i,j}^t \\in \\tab $KDE \\tab likelihood$\\\\\n w_{i,j}^0 \\quad $otherwise$\n\\end{cases}\\\n\\end{equation}\n", "completion_path": "./KEN/pretrained_model_injection/inject_all_layers.py", "namespace": "KEN.pretrained_model_injection.inject_all_layers.Kernel_injection.substitute_array", "type": "method", "signature_position": [ 80, 80 ], "body_position": [ 81, 82 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Implements the binary function f(w_{i,j}) as described in the LaTeX code.\n# It retains the current parameter w_{i,j}^t from `array_a` if it satisfies the\n# KDE likelihood condition; otherwise, it substitutes it with the pre-trained \n# value w_{i,j}^0 from `array_b`.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\noutput_array = np.where(array_a != 0, array_a, array_b)\nreturn output_array\n# [End Snippet 1]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The LaTeX description does not specify the exact condition used to determine whether a current parameter value should be retained or reset to its pre-trained value. It mentions that retention is based on \"KDE likelihood,\" but it lacks a detailed workflow explaining how this likelihood is evaluated or what qualifies a value for retention. In practice, the process might involve comparing each current parameter against a simple rule\u2014such as checking if it is non-zero or meets a predefined threshold\u2014rather than performing a full statistical estimation. This step is critical to decide which values remain unchanged and which are substituted, yet the LaTeX omits the specific decision-making criterion and its implementation.\n \n - Mismatched Details:\n - None\n", "Missing_details": [ "\n- The LaTeX description does not specify the exact condition used to determine whether a current parameter value should be retained or reset to its pre-trained value. It mentions that retention is based on \"KDE likelihood,\" but it lacks a detailed workflow explaining how this likelihood is evaluated or what qualifies a value for retention. In practice, the process might involve comparing each current parameter against a simple rule\u2014such as checking if it is non-zero or meets a predefined threshold\u2014rather than performing a full statistical estimation. This step is critical to decide which values remain unchanged and which are substituted, yet the LaTeX omits the specific decision-making criterion and its implementation.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - array_a (numpy.ndarray, shape=(hideen_size,)): Numpy array containing the current parameter values (w_{i,j}^t) that may be subject to substitution based on KDE likelihood.\n - array_b (numpy.ndarray, shape=(hideen_size,)): Numpy array containing the pre-trained parameter values (w_{i,j}^0) to be used for substitution where the KDE likelihood condition is not met.\n", "Arguments_list": [ { "name": "array_a", "string": "\n- array_a (numpy.ndarray, shape=(hideen_size,)): Numpy array containing the current parameter values (w_{i,j}^t) that may be subject to substitution based on KDE likelihood.\n", "dependency": null }, { "name": "array_b", "string": "\n- array_b (numpy.ndarray, shape=(hideen_size,)): Numpy array containing the pre-trained parameter values (w_{i,j}^0) to be used for substitution where the KDE likelihood condition is not met.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n Intra File Dependencies: \n - None\n\n Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - numpy.where\n", "list": [ "numpy.where" ] }, "Return": { "Return_String": "\nOutput Variables:\n - output_array (numpy.ndarray, shape=(hideen_size,)): Numpy array resulting from the substitution process, where each element is taken from `array_a` if it satisfies the KDE likelihood condition, otherwise from `array_b`.\n", "Return_list": [ { "name": "output_array", "string": "\n- output_array (numpy.ndarray, shape=(hideen_size,)): Numpy array resulting from the substitution process, where each element is taken from `array_a` if it satisfies the KDE likelihood condition, otherwise from `array_b`.\n", "dependency": null } ] }, "ori_python_file": "import numpy as np\nimport torch\nfrom sklearn.neighbors import KernelDensity\nnp.random.seed(42)\ntorch.manual_seed(42)\nclass Kernel_Density:\n def __init__(\n self,\n num_of_example,\n kernel_function='gaussian'\n ):\n self.num_of_example = num_of_example\n self.kernel_function = kernel_function\n \n def estimate_pdf(self, array, kernel_function, num_of_example):\n cont_samp_std = np.std(array)\n cont_samp_len = len(array)\n cont_samp_min = min(array)\n cont_samp_max = max(array)\n optimal_bandwidth = 1.06 * cont_samp_std * np.power(cont_samp_len, -1 / 5)\n bandwidthKDE = abs(optimal_bandwidth)\n kde_object = KernelDensity(kernel=kernel_function, bandwidth=bandwidthKDE).fit(array.reshape(-1, 1))\n X_plot = np.linspace(cont_samp_min, cont_samp_max, num_of_example)[:, np.newaxis]\n kde_LogDensity_estimate = kde_object.score_samples(X_plot)\n kde_estimate = np.exp(kde_LogDensity_estimate)\n kde_estimate = list([round(elem) for elem in kde_estimate])\n X = X_plot.flatten()\n return kde_estimate, X\n \n def closest(self, lst, K):\n lst = np.asarray(lst)\n idx = (np.abs(lst - K)).argmin()\n return idx\n \n def find_nearest(self, lista, element_to_find):\n closest_KDE_list = []\n for elem in element_to_find:\n index = self.closest(lista, elem)\n closest_KDE_list.append(lista[index])\n lista = np.delete(lista, index, axis=0)\n return closest_KDE_list\n \n def order_base_on_KDE_values(self, KDE_list, points_list):\n max_value = np.max(KDE_list)\n ordered_points_list = []\n for index in range(max_value, -1, -1):\n indices = [i for i, x in enumerate(KDE_list) if x == index]\n for idx in indices:\n ordered_points_list.append(points_list[idx])\n return ordered_points_list\n \n def light_matrix(self, matrix_row, cls_list):\n mask = np.isin(matrix_row, cls_list)\n matrix_row[~mask] = 0\n return matrix_row\n \n def extract_KDE(self, array):\n array = array.cpu().flatten().numpy()\n kde, points = self.estimate_pdf(array, self.kernel_function, self.num_of_example)\n ordered_points_list = self.order_base_on_KDE_values(kde, points)\n cls_list = self.find_nearest(array, ordered_points_list)\n light_matrix = self.light_matrix(array, cls_list)\n return light_matrix\n\nclass Kernel_injection:\n def __init__(\n self,\n model_trained,\n model_W0,\n num_param,\n kernel_function='gaussian'\n ):\n self.model_trained = model_trained\n self.model_W0 = model_W0\n self.num_param = num_param\n self.kernel_function = kernel_function\n self.state_dict_trained = self.model_trained.state_dict()\n self.state_dict_W0 = self.model_W0.state_dict()\n \n def substitute_array(self, array_a, array_b):\n output_array = np.where(array_a != 0, array_a, array_b)\n return output_array\n \n def injection_row(self, param_name, index):\n KD = Kernel_Density(self.num_param, self.kernel_function)\n W0_matrix = self.state_dict_W0[param_name][index]\n trained_matrix = self.state_dict_trained[param_name][index]\n lm = KD.extract_KDE(trained_matrix)\n lm = self.substitute_array(lm, W0_matrix.numpy())\n self.state_dict_W0[param_name][index] = torch.from_numpy(lm)\n return self.state_dict_W0\n \n def injection_array(self, param_name):\n KD = Kernel_Density(self.num_param, self.kernel_function)\n W0_matrix = self.state_dict_W0[param_name]\n trained_matrix = self.state_dict_trained[param_name]\n lm = KD.extract_KDE(trained_matrix)\n lm = self.substitute_array(lm, W0_matrix.numpy())\n self.state_dict_W0[param_name] = torch.from_numpy(lm)\n return self.state_dict_W0\n \n def injection_values(self, param):\n matrix = self.state_dict_W0[param]\n shape_matrix = len(matrix.shape)\n if shape_matrix == 1:\n injection_state_dict = self.injection_array(param)\n else:\n for index in range(0, matrix.shape[0]):\n injection_state_dict = self.injection_row(param, index)\n return injection_state_dict\n \n def inject_all_parameters_combined(self):\n params = [param for param in self.state_dict_W0][:-1]\n for param in params:\n matrix = self.state_dict_W0[param]\n shape_matrix = len(matrix.shape)\n if shape_matrix == 1:\n KD = Kernel_Density(self.num_param, self.kernel_function)\n W0_vector = matrix.numpy()\n trained_vector = self.state_dict_trained[param].cpu().flatten().numpy()\n optimized_vector = KD.extract_KDE(torch.tensor(trained_vector))\n optimized_vector = self.substitute_array(optimized_vector, W0_vector)\n self.state_dict_W0[param] = torch.from_numpy(optimized_vector)\n else:\n for index in range(matrix.shape[0]):\n KD = Kernel_Density(self.num_param, self.kernel_function)\n W0_row = self.state_dict_W0[param][index].numpy()\n trained_row = self.state_dict_trained[param][index].cpu().flatten().numpy()\n optimized_row = KD.extract_KDE(torch.tensor(trained_row))\n optimized_row = self.substitute_array(optimized_row, W0_row)\n self.state_dict_W0[param][index] = torch.from_numpy(optimized_row)\n self.model_W0.load_state_dict(self.state_dict_W0)\n model_W0 = self.model_W0\n return model_W0" }, { "task_id": 2, "indent": 2, "script": "\npython main.py\n", "latex_code": "\n\\paragraph{Step 3: Matrix Replacement and Optimized Fine-tuned Model} After applying the previous step on each row, the optimized matrix $\\hat{W}$:\n\\begin{equation*}\n \\hat{W} = \\{ \\hat{w}_{1,1}, ..., \\hat{w}_{n,m} \\} \\quad | \\quad \\hat{W} \\in \\mathbb{R}^{n \\times m}\n\\end{equation*}\nwill replace the original fine-tuned matrix $W^t$ within the model.\n\nKEN operates iteratively, replacing the $W^t$ matrix with $\\hat{W}$ during each iteration. Therefore, after the $t-th$ iteration, the model will have $t-optimized$ matrices, effectively replacing the fine-tuned matrices without creating any additional versions of the model. This versatility allows KEN to prune the entire model or specific layer ranges.\n\n\\RestyleAlgo{ruled}\n\\begin{algorithm}\n\\caption{Generate the optimized $\\hat{W}$ matrix using KEN}\\label{alg: Define sparse matrix}\n\\KwData{$W^{0} = \\{w_{1,1}^0, ..., w_{n,m}^0\\}$, $W^{t} = \\{w_{1,1}^{t}, ..., w_{n,m}^{t}\\}, k$}\n\\KwResult{$\\hat{W}$}\n$\\hat{W}[n,m] \\gets 0 $\n\n\\For{i = 1 to n}{\n $\\texttt{best\\_points} \\gets KDE(r_{i}^{t}, k)$\n \n \\For{j = 1 to m}{\n $\\hat{r}_{i}^{t} \\gets []$\n \n \\eIf{$r_{i}^{t}[j]$ in \\texttt{best\\_points}}{\n $\\hat{r}_{i}^{t}[j] \\gets r_{i}^{t}[j]$\n }{\n $\\hat{r}_{i}^{t}[j]$$ \\gets r_{i}^{0}[j]$\n }\n }\n $\\hat{W}[i] \\gets \\hat{r}_{i}^{t} $\n}\n\\Return $\\hat{W}$\n\\end{algorithm}\n\nAlgorithm \\ref{alg: Define sparse matrix} provides a more formal explanation of the three steps described for generating the optimized matrix $\\hat{W}$. Additionally, the graphical representation in Fig. \\ref{fig:workflow} offers a clear and comprehensive visualization of all KEN steps, while Fig. \\ref{fig: Sparse carosel} displays different $\\hat{W}$ matrices obtained using various $k$ values.\n", "completion_path": "./KEN/pretrained_model_injection/inject_all_layers.py", "namespace": "KEN.pretrained_model_injection.inject_all_layers.Kernel_injection.inject_all_parameters_combined", "type": "method", "signature_position": [ 112, 112 ], "body_position": [ 113, 134 ], "ReferenceCode_With_Comments": "\nparams = [param for param in self.state_dict_W0][:-1]\n\nfor param in params:\n matrix = self.state_dict_W0[param]\n shape_matrix = len(matrix.shape)\n\n if shape_matrix == 1:\n # -------------------------------------------------------------------\n # Snippet 1: For one-dimensional parameter vectors, initialize the KDE with\n # the specified number of parameters and kernel function. Extract the trained\n # vector, apply KDE to obtain the optimized vector, and substitute it into\n # the original state dictionary.\n # -------------------------------------------------------------------\n # [Begin Snippet 1]\n KD = Kernel_Density(self.num_param, self.kernel_function)\n W0_vector = matrix.numpy()\n trained_vector = self.state_dict_trained[param].cpu().flatten().numpy()\n optimized_vector = KD.extract_KDE(torch.tensor(trained_vector))\n optimized_vector = self.substitute_array(optimized_vector, W0_vector)\n self.state_dict_W0[param] = torch.from_numpy(optimized_vector)\n # [End Snippet 1]\n else:\n # -------------------------------------------------------------------\n # Snippet 2: For multi-dimensional parameter matrices, iterate through each row.\n # For each row, initialize KDE, extract and optimize the trained row, substitute\n # the optimized row back into the state dictionary. This process ensures each\n # row of the weight matrix is individually optimized.\n # -------------------------------------------------------------------\n # [Begin Snippet 2]\n for index in range(matrix.shape[0]):\n KD = Kernel_Density(self.num_param, self.kernel_function)\n W0_row = self.state_dict_W0[param][index].numpy()\n trained_row = self.state_dict_trained[param][index].cpu().flatten().numpy()\n optimized_row = KD.extract_KDE(torch.tensor(trained_row))\n optimized_row = self.substitute_array(optimized_row, W0_row)\n self.state_dict_W0[param][index] = torch.from_numpy(optimized_row)\n # [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: After all parameters have been optimized, load the updated state dictionary\n# `state_dict_W0` into the model `model_W0`. This final step applies all substitutions,\n# resulting in the model incorporating the optimized weight matrices $\\hat{W}$.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nself.model_W0.load_state_dict(self.state_dict_W0)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Return the updated model `model_W0` with all optimized parameters injected.\n# This allows for subsequent use or evaluation of the optimized model.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nmodel_W0 = self.model_W0\nreturn model_W0\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - Exclusion of final layer parameters: The LaTeX does not mention excluding specific layers (e.g., classifier layers) during optimization. The reference code skips the last parameter during iteration (params = [...] [:-1]) to avoid modifying critical final layers.\n - The LaTeX description does not specify how the algorithm handles parameters that are not two-dimensional matrices, such as vectors. In the workflow, after identifying all parameters to be optimized, the process should include a step to check the dimensionality of each parameter. For one-dimensional parameters, the entire vector should undergo a density estimation process to select the most significant elements, retaining those values from the fine-tuned state while reverting others to their original pre-trained values. This optimized vector is then used to update the model.\n - The LaTeX description omits the specific mechanism for combining the selected significant points from the fine-tuned matrix with the original pre-trained values after density estimation. The workflow should include a step where, after identifying the top points in each row or vector via density estimation, a substitution process evaluates each element: if an element\u2019s position corresponds to one of the selected points, its fine-tuned value is kept; otherwise, it is replaced with the corresponding value from the original matrix.\n\n Mismatched Details:\n - In the LaTeX pseudocode, the density estimation step (denoted as KDE) is applied to each row of the fine-tuned matrix to identify the top k points, but it does not clarify how the bandwidth or scoring mechanism is determined. The reference approach, however, implies a more structured process where a density estimation object is initialized with specific parameters (e.g., number of points to retain and kernel type) before processing each row or vector.\n - The reference code provided does not explicitly implement the iterative process described in the LaTeX description. The code only implements the optimization for a single iteration, while the LaTeX suggests a continuous loop where the optimized matrix replaces the fine-tuned matrix in each iteration. This discrepancy may affect the overall optimization process and the final model quality.\n", "Missing_details": [ "\n- Exclusion of final layer parameters: The LaTeX does not mention excluding specific layers (e.g., classifier layers) during optimization. The reference code skips the last parameter during iteration (params = [...] [:-1]) to avoid modifying critical final layers.\n", "\n- The LaTeX description does not specify how the algorithm handles parameters that are not two-dimensional matrices, such as vectors. In the workflow, after identifying all parameters to be optimized, the process should include a step to check the dimensionality of each parameter. For one-dimensional parameters, the entire vector should undergo a density estimation process to select the most significant elements, retaining those values from the fine-tuned state while reverting others to their original pre-trained values. This optimized vector is then used to update the model.\n", "\n- The LaTeX description omits the specific mechanism for combining the selected significant points from the fine-tuned matrix with the original pre-trained values after density estimation. The workflow should include a step where, after identifying the top points in each row or vector via density estimation, a substitution process evaluates each element: if an element\u2019s position corresponds to one of the selected points, its fine-tuned value is kept; otherwise, it is replaced with the corresponding value from the original matrix.\n" ], "Mismatched_details": [ "\n- In the LaTeX pseudocode, the density estimation step (denoted as KDE) is applied to each row of the fine-tuned matrix to identify the top k points, but it does not clarify how the bandwidth or scoring mechanism is determined. The reference approach, however, implies a more structured process where a density estimation object is initialized with specific parameters (e.g., number of points to retain and kernel type) before processing each row or vector.\n", "\n- The reference code provided does not explicitly implement the iterative process described in the LaTeX description. The code only implements the optimization for a single iteration, while the LaTeX suggests a continuous loop where the optimized matrix replaces the fine-tuned matrix in each iteration. This discrepancy may affect the overall optimization process and the final model quality.\n" ] }, "Arguments": { "string": "\nInput Variables: \n There is no input variables for this function. However, It uses the following class attributes:\n - self.state_dict_W0 (dict): A dictionary containing the original weight matrices $W^0$ of the model, which is an object of BertForSequenceClassification. \n - self.state_dict_trained (dict): A dictionary containing the fine-tuned weight matrices $W^t$ of the model, which is an object of BertForSequenceClassification.\n - self.num_param (int): The number of parameters to be optimized,\n - self.kernel_function (str): The kernel function used for KDE,\n - self.model_W0 (BertForSequenceClassification): The model with the original weight matrices $W^0$,\n - self.model_trained (BertForSequenceClassification): The model with the fine-tuned weight matrices $W^t$.\n", "Arguments_list": [ { "name": "self.state_dict_W0", "string": "\n- self.state_dict_W0 (dict): A dictionary containing the original weight matrices $W^0$ of the model, which is an object of BertForSequenceClassification.\n", "dependency": "Kernel_injection" }, { "name": "self.state_dict_trained", "string": "\n- self.state_dict_trained (dict): A dictionary containing the fine-tuned weight matrices $W^t$ of the model, which is an object of BertForSequenceClassification.\n", "dependency": "Kernel_injection" }, { "name": "self.num_param", "string": "\n- self.num_param (int): The number of parameters to be optimized.\n", "dependency": "Kernel_injection" }, { "name": "self.kernel_function", "string": "\n- self.kernel_function (str): The kernel function used for KDE.\n", "dependency": "Kernel_injection" }, { "name": "self.model_W0", "string": "\n- self.model_W0 (BertForSequenceClassification): The model with the original weight matrices $W^0$.\n", "dependency": "Kernel_injection" }, { "name": "self.model_trained", "string": "\n- self.model_trained (BertForSequenceClassification): The model with the fine-tuned weight matrices $W^t$.\n", "dependency": "Kernel_injection" } ] }, "dependency": { "string": "\nDependencies: \n Intra File Dependencies: \n - Kernel_injection.substitute_array\n\n Cross File Dependencies: \n - None\n", "intra_file": [ "Kernel_injection.substitute_array" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.tensor\n - torch.from_numpy\n", "list": [ "torch.tensor", "torch.from_numpy" ] }, "Return": { "Return_String": "\nOutput Variables:\n - model_W0 (BertForSequenceClassification): The model with the updated state dictionary `state_dict_W0`, which now contains the optimized weight matrices $\\hat{W}$. This updated model reflects the pruning and optimization performed by the KEN method.\n", "Return_list": [ { "name": "model_W0", "string": "\n- model_W0 (BertForSequenceClassification): The model with the updated state dictionary `state_dict_W0`, which now contains the optimized weight matrices $\\hat{W}$. This updated model reflects the pruning and optimization performed by the KEN method.\n", "dependency": "BertForSequenceClassification" } ] }, "ori_python_file": "import numpy as np\nimport torch\nfrom sklearn.neighbors import KernelDensity\nnp.random.seed(42)\ntorch.manual_seed(42)\nclass Kernel_Density:\n def __init__(\n self,\n num_of_example,\n kernel_function='gaussian'\n ):\n self.num_of_example = num_of_example\n self.kernel_function = kernel_function\n \n def estimate_pdf(self, array, kernel_function, num_of_example):\n cont_samp_std = np.std(array)\n cont_samp_len = len(array)\n cont_samp_min = min(array)\n cont_samp_max = max(array)\n optimal_bandwidth = 1.06 * cont_samp_std * np.power(cont_samp_len, -1 / 5)\n bandwidthKDE = abs(optimal_bandwidth)\n kde_object = KernelDensity(kernel=kernel_function, bandwidth=bandwidthKDE).fit(array.reshape(-1, 1))\n X_plot = np.linspace(cont_samp_min, cont_samp_max, num_of_example)[:, np.newaxis]\n kde_LogDensity_estimate = kde_object.score_samples(X_plot)\n kde_estimate = np.exp(kde_LogDensity_estimate)\n kde_estimate = list([round(elem) for elem in kde_estimate])\n X = X_plot.flatten()\n return kde_estimate, X\n \n def closest(self, lst, K):\n lst = np.asarray(lst)\n idx = (np.abs(lst - K)).argmin()\n return idx\n \n def find_nearest(self, lista, element_to_find):\n closest_KDE_list = []\n for elem in element_to_find:\n index = self.closest(lista, elem)\n closest_KDE_list.append(lista[index])\n lista = np.delete(lista, index, axis=0)\n return closest_KDE_list\n \n def order_base_on_KDE_values(self, KDE_list, points_list):\n max_value = np.max(KDE_list)\n ordered_points_list = []\n for index in range(max_value, -1, -1):\n indices = [i for i, x in enumerate(KDE_list) if x == index]\n for idx in indices:\n ordered_points_list.append(points_list[idx])\n return ordered_points_list\n \n def light_matrix(self, matrix_row, cls_list):\n mask = np.isin(matrix_row, cls_list)\n matrix_row[~mask] = 0\n return matrix_row\n \n def extract_KDE(self, array):\n array = array.cpu().flatten().numpy()\n kde, points = self.estimate_pdf(array, self.kernel_function, self.num_of_example)\n ordered_points_list = self.order_base_on_KDE_values(kde, points)\n cls_list = self.find_nearest(array, ordered_points_list)\n light_matrix = self.light_matrix(array, cls_list)\n return light_matrix\n\nclass Kernel_injection:\n def __init__(\n self,\n model_trained,\n model_W0,\n num_param,\n kernel_function='gaussian'\n ):\n self.model_trained = model_trained\n self.model_W0 = model_W0\n self.num_param = num_param\n self.kernel_function = kernel_function\n self.state_dict_trained = self.model_trained.state_dict()\n self.state_dict_W0 = self.model_W0.state_dict()\n \n def substitute_array(self, array_a, array_b):\n output_array = np.where(array_a != 0, array_a, array_b)\n return output_array\n \n def injection_row(self, param_name, index):\n KD = Kernel_Density(self.num_param, self.kernel_function)\n W0_matrix = self.state_dict_W0[param_name][index]\n trained_matrix = self.state_dict_trained[param_name][index]\n lm = KD.extract_KDE(trained_matrix)\n lm = self.substitute_array(lm, W0_matrix.numpy())\n self.state_dict_W0[param_name][index] = torch.from_numpy(lm)\n return self.state_dict_W0\n \n def injection_array(self, param_name):\n KD = Kernel_Density(self.num_param, self.kernel_function)\n W0_matrix = self.state_dict_W0[param_name]\n trained_matrix = self.state_dict_trained[param_name]\n lm = KD.extract_KDE(trained_matrix)\n lm = self.substitute_array(lm, W0_matrix.numpy())\n self.state_dict_W0[param_name] = torch.from_numpy(lm)\n return self.state_dict_W0\n \n def injection_values(self, param):\n matrix = self.state_dict_W0[param]\n shape_matrix = len(matrix.shape)\n if shape_matrix == 1:\n injection_state_dict = self.injection_array(param)\n else:\n for index in range(0, matrix.shape[0]):\n injection_state_dict = self.injection_row(param, index)\n return injection_state_dict\n \n def inject_all_parameters_combined(self):\n params = [param for param in self.state_dict_W0][:-1]\n for param in params:\n matrix = self.state_dict_W0[param]\n shape_matrix = len(matrix.shape)\n if shape_matrix == 1:\n KD = Kernel_Density(self.num_param, self.kernel_function)\n W0_vector = matrix.numpy()\n trained_vector = self.state_dict_trained[param].cpu().flatten().numpy()\n optimized_vector = KD.extract_KDE(torch.tensor(trained_vector))\n optimized_vector = self.substitute_array(optimized_vector, W0_vector)\n self.state_dict_W0[param] = torch.from_numpy(optimized_vector)\n else:\n for index in range(matrix.shape[0]):\n KD = Kernel_Density(self.num_param, self.kernel_function)\n W0_row = self.state_dict_W0[param][index].numpy()\n trained_row = self.state_dict_trained[param][index].cpu().flatten().numpy()\n optimized_row = KD.extract_KDE(torch.tensor(trained_row))\n optimized_row = self.substitute_array(optimized_row, W0_row)\n self.state_dict_W0[param][index] = torch.from_numpy(optimized_row)\n self.model_W0.load_state_dict(self.state_dict_W0)\n model_W0 = self.model_W0\n return model_W0" } ] }, { "paper_id": 17, "paper_details": { "title": "Adaptive Contrastive Search: Uncertainty-Guided Decoding for Open-Ended Text Generation", "url": "https://arxiv.org/abs/2407.18698" }, "enviorment_name": "acs", "repo_original_url": "https://github.com/YecanLee/Adaptive-Contrastive-Search", "project_path": "Benchmark/17-Adaptive-Contrastive-Search-main/Adaptive-Contrastive-Search-main", "file_organization": "\nAdaptive-Contrastive-Search-main/\n data/\n book_contrastive_gpt2-xl_256.jsonl\n README.md\n wikinews_contrastive_gpt2-xl_256.jsonl\n wikitext_contrastive_gpt2-xl_256.jsonl\n helpers/\n process_data.py\n story_generation/\n adaptive_contrastive_search.py\n hf_acs.py\n loss_func.py\n loss_function.py\n repomix-output.txt\n simctg_acs_base.py\n simctg.py\n static_contrastive_search.py\n utils_acs.py\n utils.py\n utils/\n .gitignore\n compute_diversity.py\n compute_gen_length.py\n compute_mauve_160.py\n compute_mauve_192.py\n compute_mauve_64.py\n compute_mauve_96.py\n compute_mauve.py\n requirements.txt\n", "latex_code_path": "Benchmark/17-Adaptive-Contrastive-Search-main/arXiv-2407.18698v2", "task_details": [ { "task_id": 0, "indent": 2, "script": "\npython story_generation/hf_acs.py --model_name meta-llama/Llama-2-7b-chat-hf --dataset wikitext --save_path_prefix Llama-2-7b-chat-hf_ACS --q 8 --save_file results\n", "latex_code": "\n\\subsection{Incorporating Model Uncertainty}\n\nIn this work, we propose an adaptive method that considers the estimated uncertainty of the model at time step $t$ to automatically control $k$ and $\\alpha$. In other words, our adaptive approach consists in modifying Eq. \\eqref{eq:cs} as follows:\n\\begin{align}\nx_t = \\underset{v \\in V^{(k_t)}}{\\arg \\max} \\Bigg\\{(1-\\alpha_t) \\times \\underbrace{p_\\theta(v \\mid \\boldsymbol{x}_{ tuple[int, float]:\n epsilon = 1e-5\n delta_t_raw = (step_entropy[-1] - step_entropy[-2]) / max_entropy\n delta_t_raw = torch.as_tensor(delta_t_raw, device=step_entropy.device)\n delta_t = self.q * torch.atanh(torch.clamp(delta_t_raw, -1 + epsilon, 1 - epsilon))\n exp_value = torch.exp(delta_t)\n k_t = 10 * exp_value / (1 + exp_value) + 5\n if torch.isnan(k_t):\n k_t = torch.tensor(10, device=step_entropy.device)\n alpha_t = exp_value / (1 + exp_value)\n k_t = int(k_t.item())\n alpha_t = float(alpha_t.item())\n return k_t, alpha_t\n \n def _degeneration_penalty(self,\n scores: torch.Tensor,\n input_ids: torch.LongTensor,\n alpha_t: float,\n penalty,\n ) -> torch.FloatTensor:\n probs = torch.softmax(scores, dim=-1)\n if input_ids.dim() == 1:\n input_ids = input_ids.unsqueeze(0)\n batch_size, seq_length = input_ids.shape\n vocab_size = scores.shape[-1]\n pad_mask = (input_ids != self.pad_token_id).float()\n adjusted_probs = torch.zeros_like(probs)\n for b in range(batch_size):\n sequence = input_ids[b][pad_mask[b] == 1]\n token_counts = torch.bincount(sequence, minlength=vocab_size).to(scores.device)\n penalties = torch.pow(penalty, token_counts * alpha_t)\n adjusted_probs[b] = probs[b] * penalties\n adjusted_probs[b] = adjusted_probs[b] / adjusted_probs[b].sum()\n return adjusted_probs\n \n def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:\n probs = torch.softmax(scores, dim=-1)\n entropy = -torch.sum(probs * torch.log(probs + 1e-10))\n self.steps_entropy.append(entropy)\n if len(self.steps_entropy) < 2:\n return probs\n max_entropy = torch.log(torch.tensor(scores.size(-1), device=scores.device))\n k_t, alpha_t = self._dynamic_adjustment(torch.stack(self.steps_entropy), max_entropy)\n top_k_scores, top_k_indices = torch.topk(scores, k_t)\n mask = torch.zeros_like(scores).scatter_(-1, top_k_indices, 1.0)\n scores = scores.masked_fill(mask == 0, float('-inf'))\n adjusted_probs = self._degeneration_penalty(scores, input_ids, alpha_t, self.penalty)\n return adjusted_probs\n\nif torch.cuda.get_device_properties(0).major >= 8:\n torch.backends.cuda.matmul.allow_tf32 = True\n torch.backends.cudnn.allow_tf32 = True\n print('Fast inference setting for Ampere GPUs is enabled \ud83d\udd25\ud83d\udd25\ud83d\udd25.')\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--model_name', type=str, default=\"meta-llama/Llama-2-7b-chat-hf\")\n parser.add_argument('--dataset_prefix', type=str, default='./data')\n parser.add_argument('--dataset', type=str, default='wikitext')\n parser.add_argument('--save_path_prefix', type=str, default='Llama-2-7b-chat-hf')\n parser.add_argument('--cuda', type=int, default=0)\n parser.add_argument('--q', required=True, type=float, default=8)\n parser.add_argument('--penalty', type=float, default=1.2)\n parser.add_argument('--save_file', default='results', required=True, type=str)\n parser.add_argument('--batch_size', type=int, default=32)\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n if torch.cuda.is_available():\n print('Cuda is available.')\n cuda_available = torch.cuda.is_available()\n device = torch.device(f'cuda:{args.cuda}' if cuda_available else 'cpu')\n assert args.dataset in ['book', 'wikinews', 'wikitext'], \"Dataset must be one of 'book', 'wikinews', or 'wikitext'\"\n full_data_path = f'{args.dataset_prefix}/{args.dataset}_contrastive_gpt2-xl_256.jsonl'\n print(f'Full data path is {full_data_path}')\n save_path_prefix = f'{args.save_path_prefix}/{args.dataset}/'\n print(f\"Save path prefix is {save_path_prefix}\")\n if not os.path.exists(save_path_prefix):\n os.makedirs(save_path_prefix, exist_ok=True)\n save_name = f'{args.dataset}_{args.save_file}_q_{args.q}_penalty_{args.penalty}.json'\n save_path = os.path.join(save_path_prefix, save_name)\n print(f'Result saving path is {save_path}')\n print('Loading model... \ud83d\udd28\ud83d\udd28\ud83d\udd28')\n tokenizer = AutoTokenizer.from_pretrained(args.model_name, fast=True)\n tokenizer.pad_token_id = tokenizer.eos_token_id\n model = AutoModelForCausalLM.from_pretrained(args.model_name, torch_dtype=torch.bfloat16, device_map=\"cpu\")\n model = torch.compile(model)\n model.to(device)\n dynamic_warper = ACSLogitsWarper(\n pad_token_id=tokenizer.pad_token_id,\n q=args.q,\n penalty=args.penalty\n )\n logits_processor = LogitsProcessorList([dynamic_warper])\n prefix_text_list, prefix_token_id_list, reference_text_list = load_data(full_data_path, tokenizer, mode=args.dataset)\n print('Performing inference \ud83d\ude80\ud83d\ude80\ud83d\ude80...')\n data_num = len(prefix_text_list)\n if args.TestCode:\n data_num = 64\n result_list = []\n batch_size = args.batch_size\n max_len = max(len(tokenizer.encode(text)) for text in prefix_text_list)\n with torch.inference_mode():\n for index in trange(0, data_num, batch_size, desc='Inferring... \u231b\u231b\u231b'):\n torch.cuda.synchronize()\n batch_prefix_text = prefix_text_list[index:index+batch_size]\n batch_reference_text = reference_text_list[index:index+batch_size]\n model_inputs = tokenizer(batch_prefix_text, padding='max_length', padding_side=\"left\", max_length=max_len, truncation=False, return_tensors=\"pt\").to(device)\n generated_ids = model.generate(**model_inputs, logits_processor=logits_processor, max_new_tokens=256, pad_token_id=tokenizer.eos_token_id, do_sample = False)\n batch_generation_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)\n current_batch_size = min(batch_size, data_num - index)\n for i in range(current_batch_size):\n one_res_dict = {\n 'prefix_text': batch_prefix_text[i],\n 'reference_text': batch_reference_text[i],\n 'generated_result': {\n '0': batch_generation_text[i][len(batch_prefix_text[i]):]\n }\n }\n result_list.append(one_res_dict)\n torch.cuda.empty_cache()\n torch.cuda.synchronize()\n print('Inference completed! \ud83c\udf89\ud83c\udf89\ud83c\udf89')" }, { "task_id": 1, "indent": 2, "script": "\npython story_generation/hf_acs.py --model_name meta-llama/Llama-2-7b-chat-hf --dataset wikitext --save_path_prefix Llama-2-7b-chat-hf_ACS --q 8 --save_file results\n", "latex_code": "\n\\subsection{Incorporating Model Uncertainty}\n\nIn this work, we propose an adaptive method that considers the estimated uncertainty of the model at time step $t$ to automatically control $k$ and $\\alpha$. In other words, our adaptive approach consists in modifying Eq. \\eqref{eq:cs} as follows:\n\\begin{align}\nx_t = \\underset{v \\in V^{(k_t)}}{\\arg \\max} \\Bigg\\{(1-\\alpha_t) \\times \\underbrace{p_\\theta(v \\mid \\boldsymbol{x}_{ tuple[int, float]:\n epsilon = 1e-5\n delta_t_raw = (step_entropy[-1] - step_entropy[-2]) / max_entropy\n delta_t_raw = torch.as_tensor(delta_t_raw, device=step_entropy.device)\n delta_t = self.q * torch.atanh(torch.clamp(delta_t_raw, -1 + epsilon, 1 - epsilon))\n exp_value = torch.exp(delta_t)\n k_t = 10 * exp_value / (1 + exp_value) + 5\n if torch.isnan(k_t):\n k_t = torch.tensor(10, device=step_entropy.device)\n alpha_t = exp_value / (1 + exp_value)\n k_t = int(k_t.item())\n alpha_t = float(alpha_t.item())\n return k_t, alpha_t\n \n def _degeneration_penalty(self,\n scores: torch.Tensor,\n input_ids: torch.LongTensor,\n alpha_t: float,\n penalty,\n ) -> torch.FloatTensor:\n probs = torch.softmax(scores, dim=-1)\n if input_ids.dim() == 1:\n input_ids = input_ids.unsqueeze(0)\n batch_size, seq_length = input_ids.shape\n vocab_size = scores.shape[-1]\n pad_mask = (input_ids != self.pad_token_id).float()\n adjusted_probs = torch.zeros_like(probs)\n for b in range(batch_size):\n sequence = input_ids[b][pad_mask[b] == 1]\n token_counts = torch.bincount(sequence, minlength=vocab_size).to(scores.device)\n penalties = torch.pow(penalty, token_counts * alpha_t)\n adjusted_probs[b] = probs[b] * penalties\n adjusted_probs[b] = adjusted_probs[b] / adjusted_probs[b].sum()\n return adjusted_probs\n \n def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:\n probs = torch.softmax(scores, dim=-1)\n entropy = -torch.sum(probs * torch.log(probs + 1e-10))\n self.steps_entropy.append(entropy)\n if len(self.steps_entropy) < 2:\n return probs\n max_entropy = torch.log(torch.tensor(scores.size(-1), device=scores.device))\n k_t, alpha_t = self._dynamic_adjustment(torch.stack(self.steps_entropy), max_entropy)\n top_k_scores, top_k_indices = torch.topk(scores, k_t)\n mask = torch.zeros_like(scores).scatter_(-1, top_k_indices, 1.0)\n scores = scores.masked_fill(mask == 0, float('-inf'))\n adjusted_probs = self._degeneration_penalty(scores, input_ids, alpha_t, self.penalty)\n return adjusted_probs\n\nif torch.cuda.get_device_properties(0).major >= 8:\n torch.backends.cuda.matmul.allow_tf32 = True\n torch.backends.cudnn.allow_tf32 = True\n print('Fast inference setting for Ampere GPUs is enabled \ud83d\udd25\ud83d\udd25\ud83d\udd25.')\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--model_name', type=str, default=\"meta-llama/Llama-2-7b-chat-hf\")\n parser.add_argument('--dataset_prefix', type=str, default='./data')\n parser.add_argument('--dataset', type=str, default='wikitext')\n parser.add_argument('--save_path_prefix', type=str, default='Llama-2-7b-chat-hf')\n parser.add_argument('--cuda', type=int, default=0)\n parser.add_argument('--q', required=True, type=float, default=8)\n parser.add_argument('--penalty', type=float, default=1.2)\n parser.add_argument('--save_file', default='results', required=True, type=str)\n parser.add_argument('--batch_size', type=int, default=32)\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n if torch.cuda.is_available():\n print('Cuda is available.')\n cuda_available = torch.cuda.is_available()\n device = torch.device(f'cuda:{args.cuda}' if cuda_available else 'cpu')\n assert args.dataset in ['book', 'wikinews', 'wikitext'], \"Dataset must be one of 'book', 'wikinews', or 'wikitext'\"\n full_data_path = f'{args.dataset_prefix}/{args.dataset}_contrastive_gpt2-xl_256.jsonl'\n print(f'Full data path is {full_data_path}')\n save_path_prefix = f'{args.save_path_prefix}/{args.dataset}/'\n print(f\"Save path prefix is {save_path_prefix}\")\n if not os.path.exists(save_path_prefix):\n os.makedirs(save_path_prefix, exist_ok=True)\n save_name = f'{args.dataset}_{args.save_file}_q_{args.q}_penalty_{args.penalty}.json'\n save_path = os.path.join(save_path_prefix, save_name)\n print(f'Result saving path is {save_path}')\n print('Loading model... \ud83d\udd28\ud83d\udd28\ud83d\udd28')\n tokenizer = AutoTokenizer.from_pretrained(args.model_name, fast=True)\n tokenizer.pad_token_id = tokenizer.eos_token_id\n model = AutoModelForCausalLM.from_pretrained(args.model_name, torch_dtype=torch.bfloat16, device_map=\"cpu\")\n model = torch.compile(model)\n model.to(device)\n dynamic_warper = ACSLogitsWarper(\n pad_token_id=tokenizer.pad_token_id,\n q=args.q,\n penalty=args.penalty\n )\n logits_processor = LogitsProcessorList([dynamic_warper])\n prefix_text_list, prefix_token_id_list, reference_text_list = load_data(full_data_path, tokenizer, mode=args.dataset)\n print('Performing inference \ud83d\ude80\ud83d\ude80\ud83d\ude80...')\n data_num = len(prefix_text_list)\n if args.TestCode:\n data_num = 64\n result_list = []\n batch_size = args.batch_size\n max_len = max(len(tokenizer.encode(text)) for text in prefix_text_list)\n with torch.inference_mode():\n for index in trange(0, data_num, batch_size, desc='Inferring... \u231b\u231b\u231b'):\n torch.cuda.synchronize()\n batch_prefix_text = prefix_text_list[index:index+batch_size]\n batch_reference_text = reference_text_list[index:index+batch_size]\n model_inputs = tokenizer(batch_prefix_text, padding='max_length', padding_side=\"left\", max_length=max_len, truncation=False, return_tensors=\"pt\").to(device)\n generated_ids = model.generate(**model_inputs, logits_processor=logits_processor, max_new_tokens=256, pad_token_id=tokenizer.eos_token_id, do_sample = False)\n batch_generation_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)\n current_batch_size = min(batch_size, data_num - index)\n for i in range(current_batch_size):\n one_res_dict = {\n 'prefix_text': batch_prefix_text[i],\n 'reference_text': batch_reference_text[i],\n 'generated_result': {\n '0': batch_generation_text[i][len(batch_prefix_text[i]):]\n }\n }\n result_list.append(one_res_dict)\n torch.cuda.empty_cache()\n torch.cuda.synchronize()\n print('Inference completed! \ud83c\udf89\ud83c\udf89\ud83c\udf89')" } ] }, { "paper_id": 18, "paper_details": { "title": "MiniCheck: Efficient Fact-Checking of LLMs on Grounding Documents", "url": "https://arxiv.org/abs/2404.10774" }, "repo_original_url": "https://github.com/Liyan06/MiniCheck", "project_path": "Benchmark/18-MiniCheck/MiniCheck-main", "enviorment_name": "minicheck", "file_organization": "\nMiniCheck-main/\n minicheck/\n __init__.py\n inference.py\n minicheck.py\n utils.py\n synthetic_data_gen/\n C2D_gen.py\n D2C_gen.py\n D2C-doc-example.txt\n prompt_utils.py\n README.md\n .gitignore\n benchmark_evaluation_demo.ipynb\n LICENSE\n pyproject.toml\n README.md\n requirements.txt\n", "latex_code_path": "Benchmark/18-MiniCheck/arXiv-2404.10774v2", "task_details": [ { "task_id": 0, "indent": 2, "script": "\npython synthetic_data_gen/C2D_gen.py \n", "latex_code": "\n\\paragraph{Step 1: Claim decomposition} Given a claim $c$, we first decompose it into a set of atomic facts $\\mathbf{a}$ with GPT-3.5:\n$\\mathrm{\\texttt{Decomp}}(c) = \\{a_1, \\ldots, a_l\\}.$\n", "completion_path": "./synthetic_data_gen/C2D_gen.py", "namespace": "synthetic_data_gen.C2D_gen.C2D_pipeline.decompose_sent_to_facts", "type": "method", "signature_position": [ 34, 34 ], "body_position": [ 35, 45 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Implement Decomp(c) operation from LaTeX using prompt engineering\n# Maps to \"we first decompose it into a set of atomic facts with GPT-4o-mini\"\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nprompt_for_decompose_adapted = PROMPT_FOR_DECOMPOSE.replace(\"[SENTENCE]\", CLAIM)\nretry = True\nwhile retry:\n try:\n response = get_GPT_output(prompt_for_decompose_adapted, model)\n retry = False \n except Exception as e:\n retry = True\n time.sleep(10)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Post-processing of LLM output format (not specified in LaTeX)\n# Converts bullet-point response to clean fact list\n# Return the list of atomic facts\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nATOMIC_FACTS = [item[2:] if '- ' == item[:2] else item for item in response.split(\"\\n\")]\n\nreturn ATOMIC_FACTS\n# [End Snippet 2]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - Converts bullet-point response to clean fact list.\n - Retry mechanism for API failures.\n - the prompt for decomposition is defined in PROMPT_FOR_DECOMPOSE in synthetic_data_gen/prompt_utils.py. \n\n - Mismatched Details:\n - The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX.\n", "Missing_details": [ "\n- Converts bullet-point response to clean fact list.\n", "\n- Retry mechanism for API failures.\n", "\n- the prompt for decomposition is defined in PROMPT_FOR_DECOMPOSE in synthetic_data_gen/prompt_utils.py.\n" ], "Mismatched_details": [ "\n- The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - CLAIM (str): The input claim that needs to be decomposed into atomic facts.\n - model (str, optional): The identifier of the GPT model to use for decomposition, defaulting to \"gpt-3.5-turbo-0125\".\n", "Arguments_list": [ { "name": "CLAIM", "string": "\n- CLAIM (str): The input claim that needs to be decomposed into atomic facts.\n", "dependency": null }, { "name": "model", "string": "\n- model (str, optional): The identifier of the GPT model to use for decomposition, defaulting to \"gpt-3.5-turbo-0125\".\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n - Intra File Dependencies: \n - None\n \n - Cross File Dependencies: \n - prompt_utils.get_GPT_output\n", "intra_file": [], "cross_file": [ "prompt_utils.get_GPT_output" ] }, "external_APIs": { "string": "\nExternal APIs: \n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - ATOMIC_FACTS (list[str]): A list containing the atomic facts derived from the input claim.\n", "Return_list": [ { "name": "ATOMIC_FACTS", "string": "\n- ATOMIC_FACTS (list[str]): A list containing the atomic facts derived from the input claim.\n", "dependency": null } ] }, "ori_python_file": "from prompt_utils import *\nimport json\nimport argparse\nimport pandas as pd\nimport logging\nfrom prompt_utils import get_GPT_output, generate_deduction_pair, entailment_check_for_sent_pair, generate_document, entailment_check_for_document, merge_facts_to_sent, get_combinations_of_facts, entailment_check_for_claim\ndef construct_removed_sent_dict_wrapper(ATOMIC_FACTS, SENT_PAIRS):\n atom_sent_map = {}\n for atom, sent_pair in zip(ATOMIC_FACTS, SENT_PAIRS):\n atom_sent_map[atom] = sent_pair\n sent_dict_for_passage_gen, atomic_dict_for_fact_check = construct_removed_sent_dict(atom_sent_map)\n return sent_dict_for_passage_gen, atomic_dict_for_fact_check\n\nclass C2D_pipeline:\n\n def __init__(self):\n self.logging = logging.getLogger()\n self.total_cost = 0\n\n def construct_data(self, CLAIM):\n ATOMIC_FACTS = self.decompose_sent_to_facts(CLAIM)\n SENT_PAIRS, SENT_PAIRS_LABELS = self.sent_pairs_generation(ATOMIC_FACTS)\n ORG_PASSAGE, ORG_PASSAGE_LABEL = self.org_passage_generation(SENT_PAIRS)\n AUGMENTED_ATOMIC_FACTS = self.augment_atomic_facts(CLAIM, ATOMIC_FACTS)\n sent_dict_for_passage_gen, atomic_dict_for_fact_check = construct_removed_sent_dict_wrapper(ATOMIC_FACTS, SENT_PAIRS)\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL = self.get_atomic_fact_label_after_sent_removal(atomic_dict_for_fact_check)\n AUGMENTED_PASSAGES = self.passage_augmentation(SENT_PAIRS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL, sent_dict_for_passage_gen)\n df = pd.DataFrame(columns=['claim', 'sent_pair', 'sent_pair_label', 'org_passage', 'org_passage_label', 'augmented_passage', 'augmented_sent', 'fact_check_label'])\n df.loc[len(df)] = [CLAIM, SENT_PAIRS, SENT_PAIRS_LABELS, ORG_PASSAGE, ORG_PASSAGE_LABEL, AUGMENTED_PASSAGES, AUGMENTED_ATOMIC_FACTS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL]\n new_df = pd.DataFrame(columns=['claim', 'doc', 'label'])\n claim_doc_label_df = self.construct_claim_doc_label_triples(df, new_df)\n return claim_doc_label_df\n \n def decompose_sent_to_facts(self, CLAIM, model=\"gpt-4o-mini\"):\n prompt_for_decompose_adapted = PROMPT_FOR_DECOMPOSE.replace(\"[SENTENCE]\", CLAIM)\n retry = True\n while retry:\n try:\n response = get_GPT_output(prompt_for_decompose_adapted, model)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n ATOMIC_FACTS = [item[2:] if '- ' == item[:2] else item for item in response.split(\"\\n\")]\n return ATOMIC_FACTS\n \n def sent_pairs_generation(self, ATOMIC_FACTS):\n SENT_PAIRS = []\n SENT_PAIRS_LABELS = []\n for atomic_fact in ATOMIC_FACTS:\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n sent_pair = generate_deduction_pair(atomic_fact)\n sent_pair_label = entailment_check_for_sent_pair(atomic_fact, sent_pair, n=3)\n if 'yes' in sent_pair_label.lower():\n is_not_entailed = False\n else:\n counter -= 1\n SENT_PAIRS.append(sent_pair)\n SENT_PAIRS_LABELS.append(sent_pair_label)\n return SENT_PAIRS, SENT_PAIRS_LABELS\n \n def org_passage_generation(self, SENT_PAIRS):\n sents_from_sent_pairs = []\n for sent_pair in SENT_PAIRS:\n sents_from_sent_pairs.extend(sent_pair)\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n ORG_PASSAGE = generate_document(sents_from_sent_pairs, return_cost=True, is_json=False)\n num_passed_fact = 0\n sents_in_pair_group = [sents_from_sent_pairs[i:i+2] for i in range(0, len(sents_from_sent_pairs), 2)]\n for sents_in_pair in sents_in_pair_group:\n sent = \" \".join(sents_in_pair)\n ORG_PASSAGE_LABEL = entailment_check_for_document(sent, ORG_PASSAGE, n=3)\n if 'yes' not in ORG_PASSAGE_LABEL.lower():\n is_not_entailed = True\n counter -= 1\n break\n else:\n num_passed_fact += 1\n if num_passed_fact == len(sents_in_pair_group):\n is_not_entailed = False\n return ORG_PASSAGE, ORG_PASSAGE_LABEL\n \n def augment_atomic_facts(self, CLAIM, ATOMIC_FACTS):\n AUGMENTED_ATOMIC_FACTS = {}\n merge_idx_sents_dict = get_combinations_of_facts(ATOMIC_FACTS)\n for idx, facts in merge_idx_sents_dict.items():\n if len(facts) == 1:\n AUGMENTED_ATOMIC_FACTS[idx] = facts[0]\n elif len(facts) == len(ATOMIC_FACTS):\n AUGMENTED_ATOMIC_FACTS[idx] = CLAIM\n else:\n response = merge_facts_to_sent(facts)\n AUGMENTED_ATOMIC_FACTS[idx] = response\n return AUGMENTED_ATOMIC_FACTS\n\n def get_atomic_fact_label_after_sent_removal(self, atomic_dict_for_fact_check):\n step_cost = 0\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL = {}\n for key, (source, fact) in atomic_dict_for_fact_check.items():\n source_sent = \" \".join(source).strip()\n response, cost = entailment_check_for_claim(fact, source_sent, n=3)\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL[key] = 'yes' in response.lower()\n step_cost += cost\n self.total_cost += step_cost\n return ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL\n\n def passage_augmentation(self, SENT_PAIRS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL, sent_dict_for_passage_gen):\n AUGMENTED_PASSAGES = {}\n for name, label in ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL.items():\n if label == False:\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n document = generate_document(sent_dict_for_passage_gen[name], return_cost=True, is_json=False)\n atomic_fact_idx = int(name.split('-')[2]) - 1\n sent_idx = int(name.split('-')[4]) - 1\n remaining_sents_from_atomic_fact = [sent for i, sent in enumerate(SENT_PAIRS[atomic_fact_idx]) if i != sent_idx]\n remaining_sent_pairs_reformatted = [\" \".join(sent) for i, sent in enumerate(SENT_PAIRS) if i != atomic_fact_idx]\n sents_to_check = remaining_sents_from_atomic_fact + remaining_sent_pairs_reformatted\n num_passed_fact = 0\n for sent in sents_to_check:\n label = entailment_check_for_document(sent, document, n=3)\n if 'yes' not in label.lower():\n is_not_entailed = True\n counter -= 1\n break\n else:\n num_passed_fact += 1\n if num_passed_fact == len(sents_to_check):\n is_not_entailed = False\n if is_not_entailed:\n AUGMENTED_PASSAGES[name] = 'invalid_doc'\n else:\n AUGMENTED_PASSAGES[name] = document\n else:\n AUGMENTED_PASSAGES[name] = 'invalid_doc'\n return AUGMENTED_PASSAGES\n\n def construct_claim_doc_label_triples(self, df, new_df):\n mask1 = df.sent_pair_label.apply(lambda x: all([label == 'Yes' for label in x]))\n mask2 = df.org_passage_label.apply(lambda x: x == 'Yes')\n df_valid = df[mask1 & mask2].reset_index(drop=True)\n for row, data in df_valid.iterrows():\n claim = data.claim\n fact_check_labels = data.fact_check_label\n augmented_sents = data.augmented_sent\n augmented_passages = data.augmented_passage\n org_passage = data.org_passage\n for augmented_sent in augmented_sents.values():\n new_df.loc[len(new_df)] = [augmented_sent, org_passage, 1]\n for remove_id, passage in augmented_passages.items():\n atomic_fact_idx = remove_id.split('-')[2]\n if passage != 'invalid_doc' and fact_check_labels[remove_id] != True:\n fact_is_supported = fact_check_labels[remove_id]\n if not fact_is_supported:\n supported_claims = [value for key, value in augmented_sents.items() if atomic_fact_idx not in key]\n unsupported_claims = [value for key, value in augmented_sents.items() if atomic_fact_idx in key]\n for supported_claim in supported_claims:\n new_df.loc[len(new_df)] = [supported_claim, passage, 1]\n for unsupported_claim in unsupported_claims:\n new_df.loc[len(new_df)] = [unsupported_claim, passage, 0]\n df_invalid = df[~(mask1 & mask2)].reset_index(drop=True)\n for row, data in df_invalid.iterrows():\n unsupported_claim = data.claim\n passage = data.org_passage\n new_df.loc[len(new_df)] = [unsupported_claim, passage, 0]\n return new_df\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--doc_path', type=str, default='synthetic_data_gen/claim.txt', help='path to the document that will be used to construct the training data.')\n parser.add_argument('--no_log', action='store_true', help='Disable logging')\n parser.add_argument(\"--test_path\", type=str)\n parser.add_argument(\"--TestCode\", action='store_true')\n args = parser.parse_args()\n if args.no_log:\n logging.basicConfig(level=logging.CRITICAL)\n else:\n logging.basicConfig(\n level=logging.INFO,\n format='%(message)s',\n handlers=[logging.StreamHandler()]\n )\n httpx_logger = logging.getLogger(\"httpx\")\n httpx_logger.setLevel(logging.WARNING)\n c2d_pipeline = C2D_pipeline()\n claim = open(args.doc_path, 'r').read()\n claim_doc_label_df = c2d_pipeline.construct_data(claim)" }, { "task_id": 1, "indent": 2, "script": "\npython synthetic_data_gen/C2D_gen.py \n", "latex_code": "\n\\paragraph{Step 2: Atomic fact expansion} For the claim $c$, we ask GPT-4 to generate a pair of sentences for each of its atomic facts with a 4-shot prompt:\n$$\\mathrm{\\texttt{SentPair}}(a_i) = (s_{i,1}, s_{i,2}), \\forall i \\in \\{1, \\ldots, l\\}.$$\nThe generated sentence pairs are designed such that the atomic fact is supported if and only if the information from both sentences is combined.\n", "completion_path": "./synthetic_data_gen/C2D_gen.py", "namespace": "synthetic_data_gen.C2D_gen.C2D_pipeline.sent_pairs_generation", "type": "method", "signature_position": [ 47, 47 ], "body_position": [ 48, 62 ], "ReferenceCode_With_Comments": "\nSENT_PAIRS = []\nSENT_PAIRS_LABELS = []\nfor atomic_fact in ATOMIC_FACTS:\n is_not_entailed = True\n counter = 5\n \n # ---------------------------------------------------------------------------\n # Snippet 1: Implements SentPair(a_i) operation from LaTeX using retry logic\n # Maps to \"generate a pair of sentences for each atomic fact with 4-shot prompt\"\n # Retry mechanism (counter=5) is implementation detail not in paper\n # ---------------------------------------------------------------------------\n # [Begin Snippet 1]\n while is_not_entailed and counter > 0:\n sent_pair = generate_deduction_pair(atomic_fact)\n # [End Snippet 1]\n\n # -----------------------------------------------------------------------\n # Snippet 2: Quality control through entailment checking - verifies the\n # core requirement that \"atomic fact is supported iff both sentences combined\"\n # n=3 indicates majority voting over 3 LLM judgments\n # -----------------------------------------------------------------------\n # [Begin Snippet 2]\n sent_pair_label = entailment_check_for_sent_pair(atomic_fact, sent_pair, n=3)\n if 'yes' in sent_pair_label.lower():\n is_not_entailed = False\n else:\n counter -= 1\n # [End Snippet 2]\n \n SENT_PAIRS.append(sent_pair)\n SENT_PAIRS_LABELS.append(sent_pair_label)\n\nreturn SENT_PAIRS, SENT_PAIRS_LABELS\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - Retry mechanism (5 attempts) for failed entailment checks.\n\n Mismatched Details:\n - The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX. \n", "Missing_details": [ "\n- Retry mechanism (5 attempts) for failed entailment checks.\n" ], "Mismatched_details": [ "\n- The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - ATOMIC_FACTS (list of str): A list containing atomic facts derived from the main claim. Each atomic fact represents a fundamental piece of information that needs to be expanded into sentence pairs for further processing.\n", "Arguments_list": [ { "name": "ATOMIC_FACTS", "string": "\n- ATOMIC_FACTS (list of str): A list containing atomic facts derived from the main claim. Each atomic fact represents a fundamental piece of information that needs to be expanded into sentence pairs for further processing.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n - Intra File Dependencies: \n - None\n\n - Cross File Dependencies: \n - prompt_utils.generate_deduction_pair\n - prompt_utils.entailment_check_for_sent_pair\n", "intra_file": [], "cross_file": [ "prompt_utils.generate_deduction_pair", "prompt_utils.entailment_check_for_sent_pair" ] }, "external_APIs": { "string": "\nExternal APIs: None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - SENT_PAIRS (list of tuples): A list where each element is a tuple containing a pair of sentences (s_{i,1}, s_{i,2}) generated for the corresponding atomic fact.\n - SENT_PAIRS_LABELS (list of str): A list of labels indicating whether each generated sentence pair supports the corresponding atomic fact. Labels are typically 'yes' or 'no'.\n", "Return_list": [ { "name": "SENT_PAIRS", "string": "\n- SENT_PAIRS (list of tuples): A list where each element is a tuple containing a pair of sentences (s_{i,1}, s_{i,2}) generated for the corresponding atomic fact.\n", "dependency": null }, { "name": "SENT_PAIRS_LABELS", "string": "\n- SENT_PAIRS_LABELS (list of str): A list of labels indicating whether each generated sentence pair supports the corresponding atomic fact. Labels are typically 'yes' or 'no'.\n", "dependency": null } ] }, "ori_python_file": "from prompt_utils import *\nimport json\nimport argparse\nimport pandas as pd\nimport logging\nfrom prompt_utils import get_GPT_output, generate_deduction_pair, entailment_check_for_sent_pair, generate_document, entailment_check_for_document, merge_facts_to_sent, get_combinations_of_facts, entailment_check_for_claim\ndef construct_removed_sent_dict_wrapper(ATOMIC_FACTS, SENT_PAIRS):\n atom_sent_map = {}\n for atom, sent_pair in zip(ATOMIC_FACTS, SENT_PAIRS):\n atom_sent_map[atom] = sent_pair\n sent_dict_for_passage_gen, atomic_dict_for_fact_check = construct_removed_sent_dict(atom_sent_map)\n return sent_dict_for_passage_gen, atomic_dict_for_fact_check\n\nclass C2D_pipeline:\n\n def __init__(self):\n self.logging = logging.getLogger()\n self.total_cost = 0\n\n def construct_data(self, CLAIM):\n ATOMIC_FACTS = self.decompose_sent_to_facts(CLAIM)\n SENT_PAIRS, SENT_PAIRS_LABELS = self.sent_pairs_generation(ATOMIC_FACTS)\n ORG_PASSAGE, ORG_PASSAGE_LABEL = self.org_passage_generation(SENT_PAIRS)\n AUGMENTED_ATOMIC_FACTS = self.augment_atomic_facts(CLAIM, ATOMIC_FACTS)\n sent_dict_for_passage_gen, atomic_dict_for_fact_check = construct_removed_sent_dict_wrapper(ATOMIC_FACTS, SENT_PAIRS)\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL = self.get_atomic_fact_label_after_sent_removal(atomic_dict_for_fact_check)\n AUGMENTED_PASSAGES = self.passage_augmentation(SENT_PAIRS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL, sent_dict_for_passage_gen)\n df = pd.DataFrame(columns=['claim', 'sent_pair', 'sent_pair_label', 'org_passage', 'org_passage_label', 'augmented_passage', 'augmented_sent', 'fact_check_label'])\n df.loc[len(df)] = [CLAIM, SENT_PAIRS, SENT_PAIRS_LABELS, ORG_PASSAGE, ORG_PASSAGE_LABEL, AUGMENTED_PASSAGES, AUGMENTED_ATOMIC_FACTS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL]\n new_df = pd.DataFrame(columns=['claim', 'doc', 'label'])\n claim_doc_label_df = self.construct_claim_doc_label_triples(df, new_df)\n return claim_doc_label_df\n \n def decompose_sent_to_facts(self, CLAIM, model=\"gpt-4o-mini\"):\n prompt_for_decompose_adapted = PROMPT_FOR_DECOMPOSE.replace(\"[SENTENCE]\", CLAIM)\n retry = True\n while retry:\n try:\n response = get_GPT_output(prompt_for_decompose_adapted, model)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n ATOMIC_FACTS = [item[2:] if '- ' == item[:2] else item for item in response.split(\"\\n\")]\n return ATOMIC_FACTS\n \n def sent_pairs_generation(self, ATOMIC_FACTS):\n SENT_PAIRS = []\n SENT_PAIRS_LABELS = []\n for atomic_fact in ATOMIC_FACTS:\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n sent_pair = generate_deduction_pair(atomic_fact)\n sent_pair_label = entailment_check_for_sent_pair(atomic_fact, sent_pair, n=3)\n if 'yes' in sent_pair_label.lower():\n is_not_entailed = False\n else:\n counter -= 1\n SENT_PAIRS.append(sent_pair)\n SENT_PAIRS_LABELS.append(sent_pair_label)\n return SENT_PAIRS, SENT_PAIRS_LABELS\n \n def org_passage_generation(self, SENT_PAIRS):\n sents_from_sent_pairs = []\n for sent_pair in SENT_PAIRS:\n sents_from_sent_pairs.extend(sent_pair)\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n ORG_PASSAGE = generate_document(sents_from_sent_pairs, return_cost=True, is_json=False)\n num_passed_fact = 0\n sents_in_pair_group = [sents_from_sent_pairs[i:i+2] for i in range(0, len(sents_from_sent_pairs), 2)]\n for sents_in_pair in sents_in_pair_group:\n sent = \" \".join(sents_in_pair)\n ORG_PASSAGE_LABEL = entailment_check_for_document(sent, ORG_PASSAGE, n=3)\n if 'yes' not in ORG_PASSAGE_LABEL.lower():\n is_not_entailed = True\n counter -= 1\n break\n else:\n num_passed_fact += 1\n if num_passed_fact == len(sents_in_pair_group):\n is_not_entailed = False\n return ORG_PASSAGE, ORG_PASSAGE_LABEL\n \n def augment_atomic_facts(self, CLAIM, ATOMIC_FACTS):\n AUGMENTED_ATOMIC_FACTS = {}\n merge_idx_sents_dict = get_combinations_of_facts(ATOMIC_FACTS)\n for idx, facts in merge_idx_sents_dict.items():\n if len(facts) == 1:\n AUGMENTED_ATOMIC_FACTS[idx] = facts[0]\n elif len(facts) == len(ATOMIC_FACTS):\n AUGMENTED_ATOMIC_FACTS[idx] = CLAIM\n else:\n response = merge_facts_to_sent(facts)\n AUGMENTED_ATOMIC_FACTS[idx] = response\n return AUGMENTED_ATOMIC_FACTS\n\n def get_atomic_fact_label_after_sent_removal(self, atomic_dict_for_fact_check):\n step_cost = 0\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL = {}\n for key, (source, fact) in atomic_dict_for_fact_check.items():\n source_sent = \" \".join(source).strip()\n response, cost = entailment_check_for_claim(fact, source_sent, n=3)\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL[key] = 'yes' in response.lower()\n step_cost += cost\n self.total_cost += step_cost\n return ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL\n\n def passage_augmentation(self, SENT_PAIRS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL, sent_dict_for_passage_gen):\n AUGMENTED_PASSAGES = {}\n for name, label in ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL.items():\n if label == False:\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n document = generate_document(sent_dict_for_passage_gen[name], return_cost=True, is_json=False)\n atomic_fact_idx = int(name.split('-')[2]) - 1\n sent_idx = int(name.split('-')[4]) - 1\n remaining_sents_from_atomic_fact = [sent for i, sent in enumerate(SENT_PAIRS[atomic_fact_idx]) if i != sent_idx]\n remaining_sent_pairs_reformatted = [\" \".join(sent) for i, sent in enumerate(SENT_PAIRS) if i != atomic_fact_idx]\n sents_to_check = remaining_sents_from_atomic_fact + remaining_sent_pairs_reformatted\n num_passed_fact = 0\n for sent in sents_to_check:\n label = entailment_check_for_document(sent, document, n=3)\n if 'yes' not in label.lower():\n is_not_entailed = True\n counter -= 1\n break\n else:\n num_passed_fact += 1\n if num_passed_fact == len(sents_to_check):\n is_not_entailed = False\n if is_not_entailed:\n AUGMENTED_PASSAGES[name] = 'invalid_doc'\n else:\n AUGMENTED_PASSAGES[name] = document\n else:\n AUGMENTED_PASSAGES[name] = 'invalid_doc'\n return AUGMENTED_PASSAGES\n\n def construct_claim_doc_label_triples(self, df, new_df):\n mask1 = df.sent_pair_label.apply(lambda x: all([label == 'Yes' for label in x]))\n mask2 = df.org_passage_label.apply(lambda x: x == 'Yes')\n df_valid = df[mask1 & mask2].reset_index(drop=True)\n for row, data in df_valid.iterrows():\n claim = data.claim\n fact_check_labels = data.fact_check_label\n augmented_sents = data.augmented_sent\n augmented_passages = data.augmented_passage\n org_passage = data.org_passage\n for augmented_sent in augmented_sents.values():\n new_df.loc[len(new_df)] = [augmented_sent, org_passage, 1]\n for remove_id, passage in augmented_passages.items():\n atomic_fact_idx = remove_id.split('-')[2]\n if passage != 'invalid_doc' and fact_check_labels[remove_id] != True:\n fact_is_supported = fact_check_labels[remove_id]\n if not fact_is_supported:\n supported_claims = [value for key, value in augmented_sents.items() if atomic_fact_idx not in key]\n unsupported_claims = [value for key, value in augmented_sents.items() if atomic_fact_idx in key]\n for supported_claim in supported_claims:\n new_df.loc[len(new_df)] = [supported_claim, passage, 1]\n for unsupported_claim in unsupported_claims:\n new_df.loc[len(new_df)] = [unsupported_claim, passage, 0]\n df_invalid = df[~(mask1 & mask2)].reset_index(drop=True)\n for row, data in df_invalid.iterrows():\n unsupported_claim = data.claim\n passage = data.org_passage\n new_df.loc[len(new_df)] = [unsupported_claim, passage, 0]\n return new_df\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--doc_path', type=str, default='synthetic_data_gen/claim.txt', help='path to the document that will be used to construct the training data.')\n parser.add_argument('--no_log', action='store_true', help='Disable logging')\n parser.add_argument(\"--test_path\", type=str)\n parser.add_argument(\"--TestCode\", action='store_true')\n args = parser.parse_args()\n if args.no_log:\n logging.basicConfig(level=logging.CRITICAL)\n else:\n logging.basicConfig(\n level=logging.INFO,\n format='%(message)s',\n handlers=[logging.StreamHandler()]\n )\n httpx_logger = logging.getLogger(\"httpx\")\n httpx_logger.setLevel(logging.WARNING)\n c2d_pipeline = C2D_pipeline()\n claim = open(args.doc_path, 'r').read()\n claim_doc_label_df = c2d_pipeline.construct_data(claim)" }, { "task_id": 2, "indent": 2, "script": "\npython synthetic_data_gen/C2D_gen.py \n", "latex_code": "\n\\paragraph{Step 3: Supporting document generation} After expanding atomic facts $\\mathbf{a}$ into sentences $\\mathbf{s} = \\{s_{1,1}, s_{1,2}, \\ldots, s_{l,1}, s_{l,2}\\}$, we ask GPT-4 to generate a document $D$ that mentions all sentences from the generated sentence pairs in its own words $D = \\mathrm{\\texttt{PassageGen}}(\\mathbf{s})$\nwith a zero-shot prompt.\\footnote{We ask GPT-4 to not state deduced facts or conclusions based on the provided sentences, and we find that GPT-4 can follow this instruction well.} \n\n\nBy following these steps, we create a triplet $(D, c, y=1)$. This procedure increases the difficulty of the task by ensuring that multiple-sentence reasoning is required to correctly classify a claim.\n", "completion_path": "./synthetic_data_gen/C2D_gen.py", "namespace": "synthetic_data_gen.C2D_gen.C2D_pipeline.org_passage_generation", "type": "method", "signature_position": [ 64, 64 ], "body_position": [ 65, 85 ], "ReferenceCode_With_Comments": "\nsents_from_sent_pairs = []\nfor sent_pair in SENT_PAIRS: \n sents_from_sent_pairs.extend(sent_pair)\n\nis_not_entailed = True\ncounter = 5\n\nwhile is_not_entailed and counter > 0:\n # ---------------------------------------------------------------------------\n # Snippet 1: Implements PassageGen(s) from LaTeX using GPT-4 zero-shot prompt\n # Maps to \"generate document D that mentions all sentences in its own words\"\n # ---------------------------------------------------------------------------\n # [Begin Snippet 1]\n ORG_PASSAGE = generate_document(sents_from_sent_pairs, return_cost=True, is_json=False)\n # [End Snippet 1]\n\n num_passed_fact = 0\n\n sents_in_pair_group = [sents_from_sent_pairs[i:i+2] for i in range(0, len(sents_from_sent_pairs), 2)]\n\n for sents_in_pair in sents_in_pair_group:\n sent = \" \".join(sents_in_pair)\n\n # -----------------------------------------------------------------------\n # Snippet 2: Validates document supports atomic fact through sentence pair combination\n # Implements paper's core requirement that \"atomic fact is supported iff both sentences combined\"\n # -----------------------------------------------------------------------\n # [Begin Snippet 2]\n ORG_PASSAGE_LABEL = entailment_check_for_document(sent, ORG_PASSAGE, n=3)\n \n if 'yes' not in ORG_PASSAGE_LABEL.lower():\n is_not_entailed = True\n counter -= 1\n break\n else:\n num_passed_fact += 1\n # [End Snippet 2]\n\n # ---------------------------------------------------------------------------\n # Snippet 3: Final validation that document supports ALL atomic facts\n # Ensures multi-sentence reasoning requirement from paper's Step 3\n # ---------------------------------------------------------------------------\n # [Begin Snippet 3]\n if num_passed_fact == len(sents_in_pair_group):\n is_not_entailed = False\n # [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Return the final generated passage along with its entailment label.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nreturn ORG_PASSAGE, ORG_PASSAGE_LABEL \n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - Retry mechanism with counter=5 for document regeneration.\n \n - Mismatched Details:\n - The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX.\n", "Missing_details": [ "\n- Retry mechanism with counter=5 for document regeneration.\n" ], "Mismatched_details": [ "\n- The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - SENT_PAIRS (list[tuple], each containing two strings): A list where each element is a tuple consisting of two related sentences. These sentence pairs represent the atomic facts that need to be expanded and incorporated into the generated document.\n", "Arguments_list": [ { "name": "SENT_PAIRS", "string": "\n- SENT_PAIRS (list[tuple], each containing two strings): A list where each element is a tuple consisting of two related sentences. These sentence pairs represent the atomic facts that need to be expanded and incorporated into the generated document.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n - Intra File Dependencies: \n - None\n \n - Cross File Dependencies: \n - prompt_utils.generate_document\n - prompt_utils.entailment_check_for_document\n", "intra_file": [], "cross_file": [ "prompt_utils.generate_document", "prompt_utils.entailment_check_for_document" ] }, "external_APIs": { "string": "\nExternal APIs: \n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - ORG_PASSAGE (str): The generated document that cohesively includes all the provided sentence pairs, formulated to support complex reasoning tasks.\n - ORG_PASSAGE_LABEL (str): A label indicating the entailment status of the generated passage with respect to the input sentence pairs. This label is used to verify the adequacy of the passage in encompassing all necessary facts.\n", "Return_list": [ { "name": "ORG_PASSAGE", "string": "\n- ORG_PASSAGE (str): The generated document that cohesively includes all the provided sentence pairs, formulated to support complex reasoning tasks.\n", "dependency": null }, { "name": "ORG_PASSAGE_LABEL", "string": "\n- ORG_PASSAGE_LABEL (str): A label indicating the entailment status of the generated passage with respect to the input sentence pairs. This label is used to verify the adequacy of the passage in encompassing all necessary facts.\n", "dependency": null } ] }, "ori_python_file": "from prompt_utils import *\nimport json\nimport argparse\nimport pandas as pd\nimport logging\nfrom prompt_utils import get_GPT_output, generate_deduction_pair, entailment_check_for_sent_pair, generate_document, entailment_check_for_document, merge_facts_to_sent, get_combinations_of_facts, entailment_check_for_claim\ndef construct_removed_sent_dict_wrapper(ATOMIC_FACTS, SENT_PAIRS):\n atom_sent_map = {}\n for atom, sent_pair in zip(ATOMIC_FACTS, SENT_PAIRS):\n atom_sent_map[atom] = sent_pair\n sent_dict_for_passage_gen, atomic_dict_for_fact_check = construct_removed_sent_dict(atom_sent_map)\n return sent_dict_for_passage_gen, atomic_dict_for_fact_check\n\nclass C2D_pipeline:\n\n def __init__(self):\n self.logging = logging.getLogger()\n self.total_cost = 0\n\n def construct_data(self, CLAIM):\n ATOMIC_FACTS = self.decompose_sent_to_facts(CLAIM)\n SENT_PAIRS, SENT_PAIRS_LABELS = self.sent_pairs_generation(ATOMIC_FACTS)\n ORG_PASSAGE, ORG_PASSAGE_LABEL = self.org_passage_generation(SENT_PAIRS)\n AUGMENTED_ATOMIC_FACTS = self.augment_atomic_facts(CLAIM, ATOMIC_FACTS)\n sent_dict_for_passage_gen, atomic_dict_for_fact_check = construct_removed_sent_dict_wrapper(ATOMIC_FACTS, SENT_PAIRS)\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL = self.get_atomic_fact_label_after_sent_removal(atomic_dict_for_fact_check)\n AUGMENTED_PASSAGES = self.passage_augmentation(SENT_PAIRS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL, sent_dict_for_passage_gen)\n df = pd.DataFrame(columns=['claim', 'sent_pair', 'sent_pair_label', 'org_passage', 'org_passage_label', 'augmented_passage', 'augmented_sent', 'fact_check_label'])\n df.loc[len(df)] = [CLAIM, SENT_PAIRS, SENT_PAIRS_LABELS, ORG_PASSAGE, ORG_PASSAGE_LABEL, AUGMENTED_PASSAGES, AUGMENTED_ATOMIC_FACTS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL]\n new_df = pd.DataFrame(columns=['claim', 'doc', 'label'])\n claim_doc_label_df = self.construct_claim_doc_label_triples(df, new_df)\n return claim_doc_label_df\n \n def decompose_sent_to_facts(self, CLAIM, model=\"gpt-4o-mini\"):\n prompt_for_decompose_adapted = PROMPT_FOR_DECOMPOSE.replace(\"[SENTENCE]\", CLAIM)\n retry = True\n while retry:\n try:\n response = get_GPT_output(prompt_for_decompose_adapted, model)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n ATOMIC_FACTS = [item[2:] if '- ' == item[:2] else item for item in response.split(\"\\n\")]\n return ATOMIC_FACTS\n \n def sent_pairs_generation(self, ATOMIC_FACTS):\n SENT_PAIRS = []\n SENT_PAIRS_LABELS = []\n for atomic_fact in ATOMIC_FACTS:\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n sent_pair = generate_deduction_pair(atomic_fact)\n sent_pair_label = entailment_check_for_sent_pair(atomic_fact, sent_pair, n=3)\n if 'yes' in sent_pair_label.lower():\n is_not_entailed = False\n else:\n counter -= 1\n SENT_PAIRS.append(sent_pair)\n SENT_PAIRS_LABELS.append(sent_pair_label)\n return SENT_PAIRS, SENT_PAIRS_LABELS\n \n def org_passage_generation(self, SENT_PAIRS):\n sents_from_sent_pairs = []\n for sent_pair in SENT_PAIRS:\n sents_from_sent_pairs.extend(sent_pair)\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n ORG_PASSAGE = generate_document(sents_from_sent_pairs, return_cost=True, is_json=False)\n num_passed_fact = 0\n sents_in_pair_group = [sents_from_sent_pairs[i:i+2] for i in range(0, len(sents_from_sent_pairs), 2)]\n for sents_in_pair in sents_in_pair_group:\n sent = \" \".join(sents_in_pair)\n ORG_PASSAGE_LABEL = entailment_check_for_document(sent, ORG_PASSAGE, n=3)\n if 'yes' not in ORG_PASSAGE_LABEL.lower():\n is_not_entailed = True\n counter -= 1\n break\n else:\n num_passed_fact += 1\n if num_passed_fact == len(sents_in_pair_group):\n is_not_entailed = False\n return ORG_PASSAGE, ORG_PASSAGE_LABEL\n \n def augment_atomic_facts(self, CLAIM, ATOMIC_FACTS):\n AUGMENTED_ATOMIC_FACTS = {}\n merge_idx_sents_dict = get_combinations_of_facts(ATOMIC_FACTS)\n for idx, facts in merge_idx_sents_dict.items():\n if len(facts) == 1:\n AUGMENTED_ATOMIC_FACTS[idx] = facts[0]\n elif len(facts) == len(ATOMIC_FACTS):\n AUGMENTED_ATOMIC_FACTS[idx] = CLAIM\n else:\n response = merge_facts_to_sent(facts)\n AUGMENTED_ATOMIC_FACTS[idx] = response\n return AUGMENTED_ATOMIC_FACTS\n\n def get_atomic_fact_label_after_sent_removal(self, atomic_dict_for_fact_check):\n step_cost = 0\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL = {}\n for key, (source, fact) in atomic_dict_for_fact_check.items():\n source_sent = \" \".join(source).strip()\n response, cost = entailment_check_for_claim(fact, source_sent, n=3)\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL[key] = 'yes' in response.lower()\n step_cost += cost\n self.total_cost += step_cost\n return ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL\n\n def passage_augmentation(self, SENT_PAIRS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL, sent_dict_for_passage_gen):\n AUGMENTED_PASSAGES = {}\n for name, label in ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL.items():\n if label == False:\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n document = generate_document(sent_dict_for_passage_gen[name], return_cost=True, is_json=False)\n atomic_fact_idx = int(name.split('-')[2]) - 1\n sent_idx = int(name.split('-')[4]) - 1\n remaining_sents_from_atomic_fact = [sent for i, sent in enumerate(SENT_PAIRS[atomic_fact_idx]) if i != sent_idx]\n remaining_sent_pairs_reformatted = [\" \".join(sent) for i, sent in enumerate(SENT_PAIRS) if i != atomic_fact_idx]\n sents_to_check = remaining_sents_from_atomic_fact + remaining_sent_pairs_reformatted\n num_passed_fact = 0\n for sent in sents_to_check:\n label = entailment_check_for_document(sent, document, n=3)\n if 'yes' not in label.lower():\n is_not_entailed = True\n counter -= 1\n break\n else:\n num_passed_fact += 1\n if num_passed_fact == len(sents_to_check):\n is_not_entailed = False\n if is_not_entailed:\n AUGMENTED_PASSAGES[name] = 'invalid_doc'\n else:\n AUGMENTED_PASSAGES[name] = document\n else:\n AUGMENTED_PASSAGES[name] = 'invalid_doc'\n return AUGMENTED_PASSAGES\n\n def construct_claim_doc_label_triples(self, df, new_df):\n mask1 = df.sent_pair_label.apply(lambda x: all([label == 'Yes' for label in x]))\n mask2 = df.org_passage_label.apply(lambda x: x == 'Yes')\n df_valid = df[mask1 & mask2].reset_index(drop=True)\n for row, data in df_valid.iterrows():\n claim = data.claim\n fact_check_labels = data.fact_check_label\n augmented_sents = data.augmented_sent\n augmented_passages = data.augmented_passage\n org_passage = data.org_passage\n for augmented_sent in augmented_sents.values():\n new_df.loc[len(new_df)] = [augmented_sent, org_passage, 1]\n for remove_id, passage in augmented_passages.items():\n atomic_fact_idx = remove_id.split('-')[2]\n if passage != 'invalid_doc' and fact_check_labels[remove_id] != True:\n fact_is_supported = fact_check_labels[remove_id]\n if not fact_is_supported:\n supported_claims = [value for key, value in augmented_sents.items() if atomic_fact_idx not in key]\n unsupported_claims = [value for key, value in augmented_sents.items() if atomic_fact_idx in key]\n for supported_claim in supported_claims:\n new_df.loc[len(new_df)] = [supported_claim, passage, 1]\n for unsupported_claim in unsupported_claims:\n new_df.loc[len(new_df)] = [unsupported_claim, passage, 0]\n df_invalid = df[~(mask1 & mask2)].reset_index(drop=True)\n for row, data in df_invalid.iterrows():\n unsupported_claim = data.claim\n passage = data.org_passage\n new_df.loc[len(new_df)] = [unsupported_claim, passage, 0]\n return new_df\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--doc_path', type=str, default='synthetic_data_gen/claim.txt', help='path to the document that will be used to construct the training data.')\n parser.add_argument('--no_log', action='store_true', help='Disable logging')\n parser.add_argument(\"--test_path\", type=str)\n parser.add_argument(\"--TestCode\", action='store_true')\n args = parser.parse_args()\n if args.no_log:\n logging.basicConfig(level=logging.CRITICAL)\n else:\n logging.basicConfig(\n level=logging.INFO,\n format='%(message)s',\n handlers=[logging.StreamHandler()]\n )\n httpx_logger = logging.getLogger(\"httpx\")\n httpx_logger.setLevel(logging.WARNING)\n c2d_pipeline = C2D_pipeline()\n claim = open(args.doc_path, 'r').read()\n claim_doc_label_df = c2d_pipeline.construct_data(claim)" }, { "task_id": 3, "indent": 2, "script": "\npython synthetic_data_gen/C2D_gen.py \n", "latex_code": "\n\\paragraph{Step 4: Nonsupporting document generation} By construction, an atomic fact $a_i$ in the claim $c$ is supported by the sentence pair $(s_{i,1}, s_{i,2})$ mentioned in the generated document $D$. Therefore, by omitting one of the sentences from the pair in a newly generated document $D'$, it is likely that $a_i$, and consequently $c$, is no longer supported by $D'$ (except in cases of redundancy in the sentences $\\mathbf{s}$). More formally, we can construct a document $D'_{a_{i\\setminus j}}$ that \\emph{probably} cannot support fact $a_i$ in $c$ (and hence $c$) by removing sentence $s_{i, j}$ from its sentence pair:\n$$D'_{a_{i\\setminus j}} = \\mathrm{\\texttt{PassageGen}}(\\mathbf{s} \\setminus {s_{i, j}}),$$\nfor all $i \\in \\{1, \\ldots, l\\}$ and $j \\in \\{1, 2\\}$ (Figure~\\ref{fig:data-gen-fig}; top right). To collect documents that do not support the claim $c$, we retain $D'_{a_{i\\setminus j}}$ if $a_i$ cannot be supported by the information combined from the remaining sentence from its sentence pair and other atomic facts ($s_{i, 3-j} \\cup \\{\\mathbf{a} \\setminus {a_i}\\}$) via an entailment check by GPT-4. Note that this entailment check is again more accurate than directly checking $a_i$ against $D'_{a_{i\\setminus j}}$ due to the shorter context.\n", "completion_path": "./synthetic_data_gen/C2D_gen.py", "namespace": "synthetic_data_gen.C2D_gen.C2D_pipeline.passage_augmentation", "type": "method", "signature_position": [ 111, 111 ], "body_position": [ 112, 141 ], "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The LaTeX description does not explicitly describe the iterative regeneration process where a newly formed document is repeatedly tested to ensure that the fact is indeednot supported. In the reference code, a loop attempts to regenerate the document several times until the removal of a sentence truly yields an unsupported fact or until theprocess fails 5 times.\n - The LaTeX description suggests that the entailment check is performed using the remaining sentence from the pair combined with information from other atomic facts to verify if the atomic fact is unsupported, implying a composite set of sentences is evaluated. However, the reference implementation extends this by checking each sentence in this set individually against the generated document, requiring all to fail the entailment test for the document to be accepted as nonsupporting. This detailed per-sentence verification contrasts with the LaTeX\u2019s broader implication of a single, collective entailment check, leading to a stricter criterion in the implementation.\n - There is no mention in the LaTeX description of a detailed sentence indexing mechanism to precisely identify which sentence from a pair corresponds to a specific atomic fact. The workflow should involve parsing a structured identifier that encodes both the atomic fact and the sentence to be removed, ensuring the correct sentence is targeted for omission rather than relying on a sequential or arbitrary selection.\n \n - Mismatched Details:\n - The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX.\n", "Missing_details": [ "\n- The LaTeX description does not explicitly describe the iterative regeneration process where a newly formed document is repeatedly tested to ensure that the fact is indeednot supported. In the reference code, a loop attempts to regenerate the document several times until the removal of a sentence truly yields an unsupported fact or until theprocess fails 5 times.\n", "\n- The LaTeX description suggests that the entailment check is performed using the remaining sentence from the pair combined with information from other atomic facts to verify if the atomic fact is unsupported, implying a composite set of sentences is evaluated. However, the reference implementation extends this by checking each sentence in this set individually against the generated document, requiring all to fail the entailment test for the document to be accepted as nonsupporting. This detailed per-sentence verification contrasts with the LaTeX\u2019s broader implication of a single, collective entailment check, leading to a stricter criterion in the implementation.\n", " \n- There is no mention in the LaTeX description of a detailed sentence indexing mechanism to precisely identify which sentence from a pair corresponds to a specific atomic fact. The workflow should involve parsing a structured identifier that encodes both the atomic fact and the sentence to be removed, ensuring the correct sentence is targeted for omission rather than relying on a sequential or arbitrary selection.\n" ], "Mismatched_details": [ "\n- The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX.\n" ] }, "ReferenceCode_With_Comments": "\nAUGMENTED_PASSAGES = {}\nfor name, label in ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL.items():\n if label == False:\n\n is_not_entailed = True\n counter = 5\n\n while is_not_entailed and counter > 0:\n \n # ---------------------------------------------------------------------------\n # Snippet 1: Generate a modified document by removing the specified sentence.\n # This implements the PassageGen(s \\setminus {s_{i, j}}) operation described in the LaTeX,\n # where a sentence is removed from the sentence pair to simulate a nonsupporting document.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 1]\n document = generate_document(sent_dict_for_passage_gen[name], return_cost=True, is_json=False)\n # [End Snippet 1]\n\n # ---------------------------------------------------------------------------\n # Snippet 2: Extract the indices of the atomic fact and the specific sentence to be removed.\n # This corresponds to determining which sentence s_{i, j} is omitted, aligning with the LaTeX notation.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 2]\n atomic_fact_idx = int(name.split('-')[2]) - 1\n sent_idx = int(name.split('-')[4]) - 1\n # [End Snippet 2]\n\n # ---------------------------------------------------------------------------\n # Snippet 3: Construct the set of remaining sentences for entailment checking.\n # Here, we combine the sentence not removed from the atomic fact pair with the sentences\n # from the other atomic facts, reflecting the LaTeX's s_{i, 3-j} \u222a {other atomic facts}.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 3]\n remaining_sents_from_atomic_fact = [sent for i, sent in enumerate(SENT_PAIRS[atomic_fact_idx]) if i != sent_idx]\n remaining_sent_pairs_reformatted = [\" \".join(sent) for i, sent in enumerate(SENT_PAIRS) if i != atomic_fact_idx]\n sents_to_check = remaining_sents_from_atomic_fact + remaining_sent_pairs_reformatted\n # [End Snippet 3]\n\n # ---------------------------------------------------------------------------\n # Snippet 4: Perform entailment checks for each sentence in the combined set.\n # This verifies that the modified document indeed fails to support the atomic fact,\n # as per the intended effect of sentence removal described in the LaTeX.\n # If any sentence fails the entailment check, the document is regenerated.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 4]\n num_passed_fact = 0\n for sent in sents_to_check:\n label = entailment_check_for_document(sent, document, n=3)\n if 'yes' not in label.lower():\n is_not_entailed = True\n counter -= 1\n self.logging.info(f\"Regenerate augmented passages. Remaining attempts: {counter}\")\n break\n else:\n num_passed_fact += 1\n if num_passed_fact == len(sents_to_check):\n is_not_entailed = False\n # [End Snippet 4]\n\n if is_not_entailed:\n AUGMENTED_PASSAGES[name] = 'invalid_doc'\n else:\n AUGMENTED_PASSAGES[name] = document\n\n else:\n AUGMENTED_PASSAGES[name] = 'invalid_doc'\n\nreturn AUGMENTED_PASSAGES\n", "Arguments": { "string": "\nInput Variables:\n - SENT_PAIRS (list of tuples, shape=[num_facts, 2], each tuple contains two sentences): \n List containing pairs of sentences that support each atomic fact in the claim.\n - ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL (dict, keys=str, values=bool): \n Dictionary mapping each atomic fact identifier to a boolean label indicating whether \n the removal of a specific sentence leads to the fact being unsupported.\n - sent_dict_for_passage_gen (dict, keys=str, values=list): \n Dictionary mapping each atomic fact identifier to a list of sentences used for \n generating passages.\n", "Arguments_list": [ { "name": "SENT_PAIRS", "string": "\n- SENT_PAIRS (list of tuples, shape=[num_facts, 2], each tuple contains two sentences):\n List containing pairs of sentences that support each atomic fact in the claim.\n", "dependency": null }, { "name": "ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL", "string": "\n- ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL (dict, keys=str, values=bool):\n Dictionary mapping each atomic fact identifier to a boolean label indicating whether \n the removal of a specific sentence leads to the fact being unsupported.\n", "dependency": null }, { "name": "sent_dict_for_passage_gen", "string": "\n- sent_dict_for_passage_gen (dict, keys=str, values=list):\n Dictionary mapping each atomic fact identifier to a list of sentences used for \n generating passages.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n - Intra File Dependencies: \n - None\n \n - Cross File Dependencies: \n - prompt_utils.generate_document\n - prompt_utils.entailment_check_for_document\n", "intra_file": [], "cross_file": [ "prompt_utils.generate_document", "prompt_utils.entailment_check_for_document" ] }, "external_APIs": { "string": "\nExternal APIs: \n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - AUGMENTED_PASSAGES (dict, keys=str, values=str): \n Dictionary mapping each atomic fact identifier to its corresponding augmented \n passage. If the passage is invalid (i.e., does not support the fact), it is marked \n as 'invalid_doc'.\n", "Return_list": [ { "name": "AUGMENTED_PASSAGES", "string": "\n- AUGMENTED_PASSAGES (dict, keys=str, values=str):\n Dictionary mapping each atomic fact identifier to its corresponding augmented \n passage. If the passage is invalid (i.e., does not support the fact), it is marked \n as 'invalid_doc'.\n", "dependency": null } ] }, "ori_python_file": "from prompt_utils import *\nimport json\nimport argparse\nimport pandas as pd\nimport logging\nfrom prompt_utils import get_GPT_output, generate_deduction_pair, entailment_check_for_sent_pair, generate_document, entailment_check_for_document, merge_facts_to_sent, get_combinations_of_facts, entailment_check_for_claim\ndef construct_removed_sent_dict_wrapper(ATOMIC_FACTS, SENT_PAIRS):\n atom_sent_map = {}\n for atom, sent_pair in zip(ATOMIC_FACTS, SENT_PAIRS):\n atom_sent_map[atom] = sent_pair\n sent_dict_for_passage_gen, atomic_dict_for_fact_check = construct_removed_sent_dict(atom_sent_map)\n return sent_dict_for_passage_gen, atomic_dict_for_fact_check\n\nclass C2D_pipeline:\n\n def __init__(self):\n self.logging = logging.getLogger()\n self.total_cost = 0\n\n def construct_data(self, CLAIM):\n ATOMIC_FACTS = self.decompose_sent_to_facts(CLAIM)\n SENT_PAIRS, SENT_PAIRS_LABELS = self.sent_pairs_generation(ATOMIC_FACTS)\n ORG_PASSAGE, ORG_PASSAGE_LABEL = self.org_passage_generation(SENT_PAIRS)\n AUGMENTED_ATOMIC_FACTS = self.augment_atomic_facts(CLAIM, ATOMIC_FACTS)\n sent_dict_for_passage_gen, atomic_dict_for_fact_check = construct_removed_sent_dict_wrapper(ATOMIC_FACTS, SENT_PAIRS)\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL = self.get_atomic_fact_label_after_sent_removal(atomic_dict_for_fact_check)\n AUGMENTED_PASSAGES = self.passage_augmentation(SENT_PAIRS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL, sent_dict_for_passage_gen)\n df = pd.DataFrame(columns=['claim', 'sent_pair', 'sent_pair_label', 'org_passage', 'org_passage_label', 'augmented_passage', 'augmented_sent', 'fact_check_label'])\n df.loc[len(df)] = [CLAIM, SENT_PAIRS, SENT_PAIRS_LABELS, ORG_PASSAGE, ORG_PASSAGE_LABEL, AUGMENTED_PASSAGES, AUGMENTED_ATOMIC_FACTS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL]\n new_df = pd.DataFrame(columns=['claim', 'doc', 'label'])\n claim_doc_label_df = self.construct_claim_doc_label_triples(df, new_df)\n return claim_doc_label_df\n \n def decompose_sent_to_facts(self, CLAIM, model=\"gpt-4o-mini\"):\n prompt_for_decompose_adapted = PROMPT_FOR_DECOMPOSE.replace(\"[SENTENCE]\", CLAIM)\n retry = True\n while retry:\n try:\n response = get_GPT_output(prompt_for_decompose_adapted, model)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n ATOMIC_FACTS = [item[2:] if '- ' == item[:2] else item for item in response.split(\"\\n\")]\n return ATOMIC_FACTS\n \n def sent_pairs_generation(self, ATOMIC_FACTS):\n SENT_PAIRS = []\n SENT_PAIRS_LABELS = []\n for atomic_fact in ATOMIC_FACTS:\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n sent_pair = generate_deduction_pair(atomic_fact)\n sent_pair_label = entailment_check_for_sent_pair(atomic_fact, sent_pair, n=3)\n if 'yes' in sent_pair_label.lower():\n is_not_entailed = False\n else:\n counter -= 1\n SENT_PAIRS.append(sent_pair)\n SENT_PAIRS_LABELS.append(sent_pair_label)\n return SENT_PAIRS, SENT_PAIRS_LABELS\n \n def org_passage_generation(self, SENT_PAIRS):\n sents_from_sent_pairs = []\n for sent_pair in SENT_PAIRS:\n sents_from_sent_pairs.extend(sent_pair)\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n ORG_PASSAGE = generate_document(sents_from_sent_pairs, return_cost=True, is_json=False)\n num_passed_fact = 0\n sents_in_pair_group = [sents_from_sent_pairs[i:i+2] for i in range(0, len(sents_from_sent_pairs), 2)]\n for sents_in_pair in sents_in_pair_group:\n sent = \" \".join(sents_in_pair)\n ORG_PASSAGE_LABEL = entailment_check_for_document(sent, ORG_PASSAGE, n=3)\n if 'yes' not in ORG_PASSAGE_LABEL.lower():\n is_not_entailed = True\n counter -= 1\n break\n else:\n num_passed_fact += 1\n if num_passed_fact == len(sents_in_pair_group):\n is_not_entailed = False\n return ORG_PASSAGE, ORG_PASSAGE_LABEL\n \n def augment_atomic_facts(self, CLAIM, ATOMIC_FACTS):\n AUGMENTED_ATOMIC_FACTS = {}\n merge_idx_sents_dict = get_combinations_of_facts(ATOMIC_FACTS)\n for idx, facts in merge_idx_sents_dict.items():\n if len(facts) == 1:\n AUGMENTED_ATOMIC_FACTS[idx] = facts[0]\n elif len(facts) == len(ATOMIC_FACTS):\n AUGMENTED_ATOMIC_FACTS[idx] = CLAIM\n else:\n response = merge_facts_to_sent(facts)\n AUGMENTED_ATOMIC_FACTS[idx] = response\n return AUGMENTED_ATOMIC_FACTS\n\n def get_atomic_fact_label_after_sent_removal(self, atomic_dict_for_fact_check):\n step_cost = 0\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL = {}\n for key, (source, fact) in atomic_dict_for_fact_check.items():\n source_sent = \" \".join(source).strip()\n response, cost = entailment_check_for_claim(fact, source_sent, n=3)\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL[key] = 'yes' in response.lower()\n step_cost += cost\n self.total_cost += step_cost\n return ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL\n\n def passage_augmentation(self, SENT_PAIRS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL, sent_dict_for_passage_gen):\n AUGMENTED_PASSAGES = {}\n for name, label in ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL.items():\n if label == False:\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n document = generate_document(sent_dict_for_passage_gen[name], return_cost=True, is_json=False)\n atomic_fact_idx = int(name.split('-')[2]) - 1\n sent_idx = int(name.split('-')[4]) - 1\n remaining_sents_from_atomic_fact = [sent for i, sent in enumerate(SENT_PAIRS[atomic_fact_idx]) if i != sent_idx]\n remaining_sent_pairs_reformatted = [\" \".join(sent) for i, sent in enumerate(SENT_PAIRS) if i != atomic_fact_idx]\n sents_to_check = remaining_sents_from_atomic_fact + remaining_sent_pairs_reformatted\n num_passed_fact = 0\n for sent in sents_to_check:\n label = entailment_check_for_document(sent, document, n=3)\n if 'yes' not in label.lower():\n is_not_entailed = True\n counter -= 1\n break\n else:\n num_passed_fact += 1\n if num_passed_fact == len(sents_to_check):\n is_not_entailed = False\n if is_not_entailed:\n AUGMENTED_PASSAGES[name] = 'invalid_doc'\n else:\n AUGMENTED_PASSAGES[name] = document\n else:\n AUGMENTED_PASSAGES[name] = 'invalid_doc'\n return AUGMENTED_PASSAGES\n\n def construct_claim_doc_label_triples(self, df, new_df):\n mask1 = df.sent_pair_label.apply(lambda x: all([label == 'Yes' for label in x]))\n mask2 = df.org_passage_label.apply(lambda x: x == 'Yes')\n df_valid = df[mask1 & mask2].reset_index(drop=True)\n for row, data in df_valid.iterrows():\n claim = data.claim\n fact_check_labels = data.fact_check_label\n augmented_sents = data.augmented_sent\n augmented_passages = data.augmented_passage\n org_passage = data.org_passage\n for augmented_sent in augmented_sents.values():\n new_df.loc[len(new_df)] = [augmented_sent, org_passage, 1]\n for remove_id, passage in augmented_passages.items():\n atomic_fact_idx = remove_id.split('-')[2]\n if passage != 'invalid_doc' and fact_check_labels[remove_id] != True:\n fact_is_supported = fact_check_labels[remove_id]\n if not fact_is_supported:\n supported_claims = [value for key, value in augmented_sents.items() if atomic_fact_idx not in key]\n unsupported_claims = [value for key, value in augmented_sents.items() if atomic_fact_idx in key]\n for supported_claim in supported_claims:\n new_df.loc[len(new_df)] = [supported_claim, passage, 1]\n for unsupported_claim in unsupported_claims:\n new_df.loc[len(new_df)] = [unsupported_claim, passage, 0]\n df_invalid = df[~(mask1 & mask2)].reset_index(drop=True)\n for row, data in df_invalid.iterrows():\n unsupported_claim = data.claim\n passage = data.org_passage\n new_df.loc[len(new_df)] = [unsupported_claim, passage, 0]\n return new_df\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--doc_path', type=str, default='synthetic_data_gen/claim.txt', help='path to the document that will be used to construct the training data.')\n parser.add_argument('--no_log', action='store_true', help='Disable logging')\n parser.add_argument(\"--test_path\", type=str)\n parser.add_argument(\"--TestCode\", action='store_true')\n args = parser.parse_args()\n if args.no_log:\n logging.basicConfig(level=logging.CRITICAL)\n else:\n logging.basicConfig(\n level=logging.INFO,\n format='%(message)s',\n handlers=[logging.StreamHandler()]\n )\n httpx_logger = logging.getLogger(\"httpx\")\n httpx_logger.setLevel(logging.WARNING)\n c2d_pipeline = C2D_pipeline()\n claim = open(args.doc_path, 'r').read()\n claim_doc_label_df = c2d_pipeline.construct_data(claim)" }, { "task_id": 4, "indent": 2, "script": "\npython synthetic_data_gen/C2D_gen.py \n", "latex_code": "\n\\paragraph{Step 5: Pairing subclaims and generated documents} We have collected tuples $(D, c, 1)$ and $(D'_{a_{i\\setminus j}}, c, 0)$ for some $i$ and $j$. We can further augment this data to produce more examples. We first generate a power set $\\mathrm{\\texttt{Power}}(\\mathbf{a})$, that consists of all possible subsets of atomic facts $\\mathbf{a}$ in $c$, but excludes the empty set.\n", "completion_path": "./synthetic_data_gen/C2D_gen.py", "namespace": "synthetic_data_gen.C2D_gen.C2D_pipeline.augment_atomic_facts", "type": "method", "signature_position": [ 87, 87 ], "body_position": [ 88, 98 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Generate all non-empty subsets (power set) of atomic facts.\n# This implements the LaTeX operation of generating the power set of atomic facts (excluding the empty set).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nAUGMENTED_ATOMIC_FACTS = {} \nmerge_idx_sents_dict = get_combinations_of_facts(ATOMIC_FACTS)\n# [End Snippet 1]\n\nfor idx, facts in merge_idx_sents_dict.items():\n \n # ---------------------------------------------------------------------------\n # Snippet 2: For subsets with a single atomic fact, retain the fact as is.\n # This directly maps to using individual atomic facts for subclaims without modification.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 2]\n if len(facts) == 1:\n AUGMENTED_ATOMIC_FACTS[idx] = facts[0]\n # [End Snippet 2]\n \n # ---------------------------------------------------------------------------\n # Snippet 3: For the subset that includes all atomic facts, use the original claim.\n # This ensures that the full claim is represented exactly when no decomposition is applied.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 3]\n elif len(facts) == len(ATOMIC_FACTS):\n AUGMENTED_ATOMIC_FACTS[idx] = CLAIM\n # [End Snippet 3]\n else:\n # ---------------------------------------------------------------------------\n # Snippet 4: For subsets containing multiple atomic facts (but not all), merge them into a single sentence.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 4]\n response = merge_facts_to_sent(facts)\n AUGMENTED_ATOMIC_FACTS[idx] = response\n # [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Return the dictionary of augmented atomic facts (subclaims) for further pairing with documents.\n# This completes the subclaim generation as described in the LaTeX.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nreturn AUGMENTED_ATOMIC_FACTS\n# [End Snippet 5]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - None\n \n Mismatched Details:\n - The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX.\n", "Missing_details": [], "Mismatched_details": [ "\n- The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - CLAIM (str): The original claim statement that may be decomposed into atomic facts or used as is for augmentation.\n - ATOMIC_FACTS (list of str): A list of atomic facts derived from the original claim, which will be used to generate various subsets for augmentation.\n", "Arguments_list": [ { "name": "CLAIM", "string": "\n- CLAIM (str): The original claim statement that may be decomposed into atomic facts or used as is for augmentation.\n", "dependency": null }, { "name": "ATOMIC_FACTS", "string": "\n- ATOMIC_FACTS (list of str): A list of atomic facts derived from the original claim, which will be used to generate various subsets for augmentation.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n - Intra File Dependencies: \n - None\n \n - Cross File Dependencies: \n - prompt_utils.get_combinations_of_facts\n - prompt_utils.merge_facts_to_sent\n", "intra_file": [], "cross_file": [ "prompt_utils.get_combinations_of_facts", "prompt_utils.merge_facts_to_sent" ] }, "external_APIs": { "string": "\nExternal APIs: \n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - AUGMENTED_ATOMIC_FACTS (dict): A dictionary mapping each subset index (str, like '1', '2' and '1-2') to its corresponding augmented atomic fact or claim. This includes individual atomic facts,the original claim, and merged sentences from multiple atomic facts.\n", "Return_list": [ { "name": "AUGMENTED_ATOMIC_FACTS", "string": "\n- AUGMENTED_ATOMIC_FACTS (dict): A dictionary mapping each subset index (str, like '1', '2' and '1-2') to its corresponding augmented atomic fact or claim. This includes individual atomic facts,the original claim, and merged sentences from multiple atomic facts.\n", "dependency": null } ] }, "ori_python_file": "from prompt_utils import *\nimport json\nimport argparse\nimport pandas as pd\nimport logging\nfrom prompt_utils import get_GPT_output, generate_deduction_pair, entailment_check_for_sent_pair, generate_document, entailment_check_for_document, merge_facts_to_sent, get_combinations_of_facts, entailment_check_for_claim\ndef construct_removed_sent_dict_wrapper(ATOMIC_FACTS, SENT_PAIRS):\n atom_sent_map = {}\n for atom, sent_pair in zip(ATOMIC_FACTS, SENT_PAIRS):\n atom_sent_map[atom] = sent_pair\n sent_dict_for_passage_gen, atomic_dict_for_fact_check = construct_removed_sent_dict(atom_sent_map)\n return sent_dict_for_passage_gen, atomic_dict_for_fact_check\n\nclass C2D_pipeline:\n\n def __init__(self):\n self.logging = logging.getLogger()\n self.total_cost = 0\n\n def construct_data(self, CLAIM):\n ATOMIC_FACTS = self.decompose_sent_to_facts(CLAIM)\n SENT_PAIRS, SENT_PAIRS_LABELS = self.sent_pairs_generation(ATOMIC_FACTS)\n ORG_PASSAGE, ORG_PASSAGE_LABEL = self.org_passage_generation(SENT_PAIRS)\n AUGMENTED_ATOMIC_FACTS = self.augment_atomic_facts(CLAIM, ATOMIC_FACTS)\n sent_dict_for_passage_gen, atomic_dict_for_fact_check = construct_removed_sent_dict_wrapper(ATOMIC_FACTS, SENT_PAIRS)\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL = self.get_atomic_fact_label_after_sent_removal(atomic_dict_for_fact_check)\n AUGMENTED_PASSAGES = self.passage_augmentation(SENT_PAIRS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL, sent_dict_for_passage_gen)\n df = pd.DataFrame(columns=['claim', 'sent_pair', 'sent_pair_label', 'org_passage', 'org_passage_label', 'augmented_passage', 'augmented_sent', 'fact_check_label'])\n df.loc[len(df)] = [CLAIM, SENT_PAIRS, SENT_PAIRS_LABELS, ORG_PASSAGE, ORG_PASSAGE_LABEL, AUGMENTED_PASSAGES, AUGMENTED_ATOMIC_FACTS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL]\n new_df = pd.DataFrame(columns=['claim', 'doc', 'label'])\n claim_doc_label_df = self.construct_claim_doc_label_triples(df, new_df)\n return claim_doc_label_df\n \n def decompose_sent_to_facts(self, CLAIM, model=\"gpt-4o-mini\"):\n prompt_for_decompose_adapted = PROMPT_FOR_DECOMPOSE.replace(\"[SENTENCE]\", CLAIM)\n retry = True\n while retry:\n try:\n response = get_GPT_output(prompt_for_decompose_adapted, model)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n ATOMIC_FACTS = [item[2:] if '- ' == item[:2] else item for item in response.split(\"\\n\")]\n return ATOMIC_FACTS\n \n def sent_pairs_generation(self, ATOMIC_FACTS):\n SENT_PAIRS = []\n SENT_PAIRS_LABELS = []\n for atomic_fact in ATOMIC_FACTS:\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n sent_pair = generate_deduction_pair(atomic_fact)\n sent_pair_label = entailment_check_for_sent_pair(atomic_fact, sent_pair, n=3)\n if 'yes' in sent_pair_label.lower():\n is_not_entailed = False\n else:\n counter -= 1\n SENT_PAIRS.append(sent_pair)\n SENT_PAIRS_LABELS.append(sent_pair_label)\n return SENT_PAIRS, SENT_PAIRS_LABELS\n \n def org_passage_generation(self, SENT_PAIRS):\n sents_from_sent_pairs = []\n for sent_pair in SENT_PAIRS:\n sents_from_sent_pairs.extend(sent_pair)\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n ORG_PASSAGE = generate_document(sents_from_sent_pairs, return_cost=True, is_json=False)\n num_passed_fact = 0\n sents_in_pair_group = [sents_from_sent_pairs[i:i+2] for i in range(0, len(sents_from_sent_pairs), 2)]\n for sents_in_pair in sents_in_pair_group:\n sent = \" \".join(sents_in_pair)\n ORG_PASSAGE_LABEL = entailment_check_for_document(sent, ORG_PASSAGE, n=3)\n if 'yes' not in ORG_PASSAGE_LABEL.lower():\n is_not_entailed = True\n counter -= 1\n break\n else:\n num_passed_fact += 1\n if num_passed_fact == len(sents_in_pair_group):\n is_not_entailed = False\n return ORG_PASSAGE, ORG_PASSAGE_LABEL\n \n def augment_atomic_facts(self, CLAIM, ATOMIC_FACTS):\n AUGMENTED_ATOMIC_FACTS = {}\n merge_idx_sents_dict = get_combinations_of_facts(ATOMIC_FACTS)\n for idx, facts in merge_idx_sents_dict.items():\n if len(facts) == 1:\n AUGMENTED_ATOMIC_FACTS[idx] = facts[0]\n elif len(facts) == len(ATOMIC_FACTS):\n AUGMENTED_ATOMIC_FACTS[idx] = CLAIM\n else:\n response = merge_facts_to_sent(facts)\n AUGMENTED_ATOMIC_FACTS[idx] = response\n return AUGMENTED_ATOMIC_FACTS\n\n def get_atomic_fact_label_after_sent_removal(self, atomic_dict_for_fact_check):\n step_cost = 0\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL = {}\n for key, (source, fact) in atomic_dict_for_fact_check.items():\n source_sent = \" \".join(source).strip()\n response, cost = entailment_check_for_claim(fact, source_sent, n=3)\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL[key] = 'yes' in response.lower()\n step_cost += cost\n self.total_cost += step_cost\n return ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL\n\n def passage_augmentation(self, SENT_PAIRS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL, sent_dict_for_passage_gen):\n AUGMENTED_PASSAGES = {}\n for name, label in ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL.items():\n if label == False:\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n document = generate_document(sent_dict_for_passage_gen[name], return_cost=True, is_json=False)\n atomic_fact_idx = int(name.split('-')[2]) - 1\n sent_idx = int(name.split('-')[4]) - 1\n remaining_sents_from_atomic_fact = [sent for i, sent in enumerate(SENT_PAIRS[atomic_fact_idx]) if i != sent_idx]\n remaining_sent_pairs_reformatted = [\" \".join(sent) for i, sent in enumerate(SENT_PAIRS) if i != atomic_fact_idx]\n sents_to_check = remaining_sents_from_atomic_fact + remaining_sent_pairs_reformatted\n num_passed_fact = 0\n for sent in sents_to_check:\n label = entailment_check_for_document(sent, document, n=3)\n if 'yes' not in label.lower():\n is_not_entailed = True\n counter -= 1\n break\n else:\n num_passed_fact += 1\n if num_passed_fact == len(sents_to_check):\n is_not_entailed = False\n if is_not_entailed:\n AUGMENTED_PASSAGES[name] = 'invalid_doc'\n else:\n AUGMENTED_PASSAGES[name] = document\n else:\n AUGMENTED_PASSAGES[name] = 'invalid_doc'\n return AUGMENTED_PASSAGES\n\n def construct_claim_doc_label_triples(self, df, new_df):\n mask1 = df.sent_pair_label.apply(lambda x: all([label == 'Yes' for label in x]))\n mask2 = df.org_passage_label.apply(lambda x: x == 'Yes')\n df_valid = df[mask1 & mask2].reset_index(drop=True)\n for row, data in df_valid.iterrows():\n claim = data.claim\n fact_check_labels = data.fact_check_label\n augmented_sents = data.augmented_sent\n augmented_passages = data.augmented_passage\n org_passage = data.org_passage\n for augmented_sent in augmented_sents.values():\n new_df.loc[len(new_df)] = [augmented_sent, org_passage, 1]\n for remove_id, passage in augmented_passages.items():\n atomic_fact_idx = remove_id.split('-')[2]\n if passage != 'invalid_doc' and fact_check_labels[remove_id] != True:\n fact_is_supported = fact_check_labels[remove_id]\n if not fact_is_supported:\n supported_claims = [value for key, value in augmented_sents.items() if atomic_fact_idx not in key]\n unsupported_claims = [value for key, value in augmented_sents.items() if atomic_fact_idx in key]\n for supported_claim in supported_claims:\n new_df.loc[len(new_df)] = [supported_claim, passage, 1]\n for unsupported_claim in unsupported_claims:\n new_df.loc[len(new_df)] = [unsupported_claim, passage, 0]\n df_invalid = df[~(mask1 & mask2)].reset_index(drop=True)\n for row, data in df_invalid.iterrows():\n unsupported_claim = data.claim\n passage = data.org_passage\n new_df.loc[len(new_df)] = [unsupported_claim, passage, 0]\n return new_df\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--doc_path', type=str, default='synthetic_data_gen/claim.txt', help='path to the document that will be used to construct the training data.')\n parser.add_argument('--no_log', action='store_true', help='Disable logging')\n parser.add_argument(\"--test_path\", type=str)\n parser.add_argument(\"--TestCode\", action='store_true')\n args = parser.parse_args()\n if args.no_log:\n logging.basicConfig(level=logging.CRITICAL)\n else:\n logging.basicConfig(\n level=logging.INFO,\n format='%(message)s',\n handlers=[logging.StreamHandler()]\n )\n httpx_logger = logging.getLogger(\"httpx\")\n httpx_logger.setLevel(logging.WARNING)\n c2d_pipeline = C2D_pipeline()\n claim = open(args.doc_path, 'r').read()\n claim_doc_label_df = c2d_pipeline.construct_data(claim)" }, { "task_id": 5, "indent": 2, "script": "\npython synthetic_data_gen/C2D_gen.py \n", "latex_code": "\nWe then create a set of augmented subclaims $\\mathrm{Aug}(c)$ by merging atomic facts from each subset:\n$$\\mathrm{Aug}(c) = \\{\\mathrm{\\texttt{Merge}}(\\mathbf{a'}): \\forall \\mathbf{a'} \\in \\mathrm{\\texttt{Power}}(\\mathbf{a})\\}.$$\nIt follows that we obtain tuples $(D, c', 1)$ for every $c' \\in \\mathrm{Aug}(c)$. Similarly, for each $D'_{a_{i\\setminus j}}$, we generate tuples $(D'_{a_{i\\setminus j}}, \\mathrm{\\texttt{Merge}}(\\mathbf{a'}), 1)$ if $a_i \\notin {\\mathbf{a'}}$, indicating that the document still supports the subclaim absent the atomic fact $a_i$. Conversely, we have $(D'_{a_{i\\setminus j}}, \\mathrm{\\texttt{Merge}}(\\mathbf{a'}), 0)$ if $a_i \\in {\\mathbf{a'}}$, suggesting that the document does not support the subclaim due to the absence of $a_i$.\n\nBecause the same subclaim is supported by certain documents and unsupported by others depending on the presence or absence of specific atomic facts, we achieve the same benefits that training on contrast sets provides \\cite{cao-wang-2021-cliff, liu-etal-2022-brio, tang-etal-2023-less}, namely making the model more sensitive to the specifics of the decision boundary and encouraging it to consider all atomic facts within a claim during prediction.\n", "completion_path": "./synthetic_data_gen/C2D_gen.py", "namespace": "synthetic_data_gen.C2D_gen.C2D_pipeline.construct_claim_doc_label_triples", "type": "method", "signature_position": [ 143, 143 ], "body_position": [ 144, 171 ], "ReferenceCode_With_Comments": "\nmask1 = df.sent_pair_label.apply(lambda x: all([label == 'Yes' for label in x]))\nmask2 = df.org_passage_label.apply(lambda x: x == 'Yes')\ndf_valid = df[mask1 & mask2].reset_index(drop=True)\n\nfor row, data in df_valid.iterrows():\n claim = data.claim\n fact_check_labels = data.fact_check_label\n augmented_sents = data.augmented_sent\n augmented_passages = data.augmented_passage\n org_passage = data.org_passage\n\n for augmented_sent in augmented_sents.values():\n new_df.loc[len(new_df)] = [augmented_sent, org_passage, 1]\n\n for remove_id, passage in augmented_passages.items():\n atomic_fact_idx = remove_id.split('-')[2]\n\n if passage != 'invalid_doc' and fact_check_labels[remove_id] != True:\n # ---------------------------------------------------------------------------\n # Snippet 1: For passages failing the entailment check (unsupported atomic fact), partition \n # the augmented subclaims into two groups: those that do not involve the omitted atomic fact \n # (supported claims) and those that do (unsupported claims). This reflects the generation of \n # tuples (D, c', 1) and (D, c', 0) as described in the LaTeX.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 1]\n fact_is_supported = fact_check_labels[remove_id]\n if not fact_is_supported:\n supported_claims = [value for key, value in augmented_sents.items() if atomic_fact_idx not in key]\n unsupported_claims = [value for key, value in augmented_sents.items() if atomic_fact_idx in key]\n # [End Snippet 1]\n\n # ---------------------------------------------------------------------------\n # Snippet 2: Append each supported subclaim along with the augmented passage to new_df \n # with a label of 1, indicating that the document supports these subclaims.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 2]\n for supported_claim in supported_claims:\n new_df.loc[len(new_df)] = [supported_claim, passage, 1]\n # [End Snippet 2]\n\n # ---------------------------------------------------------------------------\n # Snippet 3: Append each unsupported subclaim along with the augmented passage to new_df \n # with a label of 0, indicating that the document does not support these subclaims due \n # to the absence of the crucial atomic fact.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 3]\n for unsupported_claim in unsupported_claims:\n new_df.loc[len(new_df)] = [unsupported_claim, passage, 0]\n # [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Process the invalid entries (where either the sentence pairs or original passage \n# did not pass support checks) by marking the original claim with its document as unsupported (label 0).\n# This final step ensures that unsupportive cases are included.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\ndf_invalid = df[~(mask1 & mask2)].reset_index(drop=True)\nfor row, data in df_invalid.iterrows():\n unsupported_claim = data.claim\n passage = data.org_passage\n new_df.loc[len(new_df)] = [unsupported_claim, passage, 0]\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Return the constructed DataFrame containing the claim, document, and label triples.\n# This DataFrame is used for further processing in training or evaluation, completing the augmentation pipeline.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nreturn new_df\n# [End Snippet 5]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX description does not specify an initial validation step to ensure that only claims fully supported by all their atomic facts and the original document are processed further. In practice, this involves filtering the input data to retain only those claims where every individual fact is confirmed as supported and the associated original document also supports the claim.\n - The LaTeX omits the step where invalid claims (those with unsupported atomic facts or passages) are explicitly added to the dataset with label 0. The reference code appends these entries to ensure contrastive examples\n - The LaTeX does not specify the use of an external check to determine if an atomic fact remains supported after the removal of specific sentences. Before generating triples for augmented passages, the process should verify if the removal of a sentence invalidates the corresponding atomic fact. Only if the fact is no longer supported should the algorithm proceed to create both supported and unsupported claim variations.\n\n Mismatched Details:\n - None\n", "Missing_details": [ "\n- The LaTeX description does not specify an initial validation step to ensure that only claims fully supported by all their atomic facts and the original document are processed further. In practice, this involves filtering the input data to retain only those claims where every individual fact is confirmed as supported and the associated original document also supports the claim.\n", "\n- The LaTeX omits the step where invalid claims (those with unsupported atomic facts or passages) are explicitly added to the dataset with label 0. The reference code appends these entries to ensure contrastive examples\n", "\n- The LaTeX does not specify the use of an external check to determine if an atomic fact remains supported after the removal of specific sentences. Before generating triples for augmented passages, the process should verify if the removal of a sentence invalidates the corresponding atomic fact. Only if the fact is no longer supported should the algorithm proceed to create both supported and unsupported claim variations.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - df (pandas.DataFrame):\n A DataFrame containing the original claim, sentence pairs, passage, and augmented data fields. The DataFrame is structured as follows:\n - claim (str): The original claim statement that is being evaluated.\n - sent_pair (list of tuples): Pairs of sentences that are used to support the atomic facts of the claim.\n - sent_pair_label (list of str): Labels indicating whether each sentence pair supports the corresponding atomic fact ('Yes' or 'No').\n - org_passage (str): The original passage associated with the claim before any augmentation.\n - org_passage_label (str): Label indicating if the original passage supports the claim ('Yes' or 'No').\n - augmented_passage (dict): Dictionary of augmented passages created by removing specific sentences related to atomic facts.\n - augmented_sent (dict): Dictionary of augmented atomic facts corresponding to the augmented passages.\n - fact_check_label (dict): Labels indicating whether the atomic facts are still supported after the removal of certain sentences.\n - new_df (pandas.DataFrame):\n A DataFrame containing the constructed triples with columns ['claim', 'doc', 'label'].\n - claim (str): The claim statement that is being evaluated.\n - doc (str): The document or passage associated with the claim.\n - label (int): The label indicating whether the document supports the claim (1) or not (0).\n", "Arguments_list": [ { "name": "df", "string": "\n- df (pandas.DataFrame):\n A DataFrame containing the original claim, sentence pairs, passage, and augmented data fields. The DataFrame is structured as follows:\n - claim (str): The original claim statement that is being evaluated.\n - sent_pair (list of tuples): Pairs of sentences that are used to support the atomic facts of the claim.\n - sent_pair_label (list of str): Labels indicating whether each sentence pair supports the corresponding atomic fact ('Yes' or 'No').\n - org_passage (str): The original passage associated with the claim before any augmentation.\n - org_passage_label (str): Label indicating if the original passage supports the claim ('Yes' or 'No').\n - augmented_passage (dict): Dictionary of augmented passages created by removing specific sentences related to atomic facts.\n - augmented_sent (dict): Dictionary of augmented atomic facts corresponding to the augmented passages.\n - fact_check_label (dict): Labels indicating whether the atomic facts are still supported after the removal of certain sentences.\n", "dependency": null }, { "name": "new_df", "string": "\n- new_df (pandas.DataFrame):\n A DataFrame containing the constructed triples with columns ['claim', 'doc', 'label'].\n - claim (str): The claim statement that is being evaluated.\n - doc (str): The document or passage associated with the claim.\n - label (int): The label indicating whether the document supports the claim (1) or not (0).\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n - Intra File Dependencies: \n - None\n\n - Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": " \nExternal APIs:\n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - new_df (pandas.DataFrame): A DataFrame containing the constructed triples with columns ['claim', 'doc', 'label'], where 'label' indicates support (1) or lack thereof (0).\n", "Return_list": [ { "name": "new_df", "string": "\n- new_df (pandas.DataFrame): A DataFrame containing the constructed triples with columns ['claim', 'doc', 'label'], where 'label' indicates support (1) or lack thereof (0).\n", "dependency": null } ] }, "ori_python_file": "from prompt_utils import *\nimport json\nimport argparse\nimport pandas as pd\nimport logging\nfrom prompt_utils import get_GPT_output, generate_deduction_pair, entailment_check_for_sent_pair, generate_document, entailment_check_for_document, merge_facts_to_sent, get_combinations_of_facts, entailment_check_for_claim\ndef construct_removed_sent_dict_wrapper(ATOMIC_FACTS, SENT_PAIRS):\n atom_sent_map = {}\n for atom, sent_pair in zip(ATOMIC_FACTS, SENT_PAIRS):\n atom_sent_map[atom] = sent_pair\n sent_dict_for_passage_gen, atomic_dict_for_fact_check = construct_removed_sent_dict(atom_sent_map)\n return sent_dict_for_passage_gen, atomic_dict_for_fact_check\n\nclass C2D_pipeline:\n\n def __init__(self):\n self.logging = logging.getLogger()\n self.total_cost = 0\n\n def construct_data(self, CLAIM):\n ATOMIC_FACTS = self.decompose_sent_to_facts(CLAIM)\n SENT_PAIRS, SENT_PAIRS_LABELS = self.sent_pairs_generation(ATOMIC_FACTS)\n ORG_PASSAGE, ORG_PASSAGE_LABEL = self.org_passage_generation(SENT_PAIRS)\n AUGMENTED_ATOMIC_FACTS = self.augment_atomic_facts(CLAIM, ATOMIC_FACTS)\n sent_dict_for_passage_gen, atomic_dict_for_fact_check = construct_removed_sent_dict_wrapper(ATOMIC_FACTS, SENT_PAIRS)\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL = self.get_atomic_fact_label_after_sent_removal(atomic_dict_for_fact_check)\n AUGMENTED_PASSAGES = self.passage_augmentation(SENT_PAIRS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL, sent_dict_for_passage_gen)\n df = pd.DataFrame(columns=['claim', 'sent_pair', 'sent_pair_label', 'org_passage', 'org_passage_label', 'augmented_passage', 'augmented_sent', 'fact_check_label'])\n df.loc[len(df)] = [CLAIM, SENT_PAIRS, SENT_PAIRS_LABELS, ORG_PASSAGE, ORG_PASSAGE_LABEL, AUGMENTED_PASSAGES, AUGMENTED_ATOMIC_FACTS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL]\n new_df = pd.DataFrame(columns=['claim', 'doc', 'label'])\n claim_doc_label_df = self.construct_claim_doc_label_triples(df, new_df)\n return claim_doc_label_df\n \n def decompose_sent_to_facts(self, CLAIM, model=\"gpt-4o-mini\"):\n prompt_for_decompose_adapted = PROMPT_FOR_DECOMPOSE.replace(\"[SENTENCE]\", CLAIM)\n retry = True\n while retry:\n try:\n response = get_GPT_output(prompt_for_decompose_adapted, model)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n ATOMIC_FACTS = [item[2:] if '- ' == item[:2] else item for item in response.split(\"\\n\")]\n return ATOMIC_FACTS\n \n def sent_pairs_generation(self, ATOMIC_FACTS):\n SENT_PAIRS = []\n SENT_PAIRS_LABELS = []\n for atomic_fact in ATOMIC_FACTS:\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n sent_pair = generate_deduction_pair(atomic_fact)\n sent_pair_label = entailment_check_for_sent_pair(atomic_fact, sent_pair, n=3)\n if 'yes' in sent_pair_label.lower():\n is_not_entailed = False\n else:\n counter -= 1\n SENT_PAIRS.append(sent_pair)\n SENT_PAIRS_LABELS.append(sent_pair_label)\n return SENT_PAIRS, SENT_PAIRS_LABELS\n \n def org_passage_generation(self, SENT_PAIRS):\n sents_from_sent_pairs = []\n for sent_pair in SENT_PAIRS:\n sents_from_sent_pairs.extend(sent_pair)\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n ORG_PASSAGE = generate_document(sents_from_sent_pairs, return_cost=True, is_json=False)\n num_passed_fact = 0\n sents_in_pair_group = [sents_from_sent_pairs[i:i+2] for i in range(0, len(sents_from_sent_pairs), 2)]\n for sents_in_pair in sents_in_pair_group:\n sent = \" \".join(sents_in_pair)\n ORG_PASSAGE_LABEL = entailment_check_for_document(sent, ORG_PASSAGE, n=3)\n if 'yes' not in ORG_PASSAGE_LABEL.lower():\n is_not_entailed = True\n counter -= 1\n break\n else:\n num_passed_fact += 1\n if num_passed_fact == len(sents_in_pair_group):\n is_not_entailed = False\n return ORG_PASSAGE, ORG_PASSAGE_LABEL\n \n def augment_atomic_facts(self, CLAIM, ATOMIC_FACTS):\n AUGMENTED_ATOMIC_FACTS = {}\n merge_idx_sents_dict = get_combinations_of_facts(ATOMIC_FACTS)\n for idx, facts in merge_idx_sents_dict.items():\n if len(facts) == 1:\n AUGMENTED_ATOMIC_FACTS[idx] = facts[0]\n elif len(facts) == len(ATOMIC_FACTS):\n AUGMENTED_ATOMIC_FACTS[idx] = CLAIM\n else:\n response = merge_facts_to_sent(facts)\n AUGMENTED_ATOMIC_FACTS[idx] = response\n return AUGMENTED_ATOMIC_FACTS\n\n def get_atomic_fact_label_after_sent_removal(self, atomic_dict_for_fact_check):\n step_cost = 0\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL = {}\n for key, (source, fact) in atomic_dict_for_fact_check.items():\n source_sent = \" \".join(source).strip()\n response, cost = entailment_check_for_claim(fact, source_sent, n=3)\n ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL[key] = 'yes' in response.lower()\n step_cost += cost\n self.total_cost += step_cost\n return ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL\n\n def passage_augmentation(self, SENT_PAIRS, ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL, sent_dict_for_passage_gen):\n AUGMENTED_PASSAGES = {}\n for name, label in ATOMIC_FACT_LABEL_WITH_SENT_REMOVAL.items():\n if label == False:\n is_not_entailed = True\n counter = 5\n while is_not_entailed and counter > 0:\n document = generate_document(sent_dict_for_passage_gen[name], return_cost=True, is_json=False)\n atomic_fact_idx = int(name.split('-')[2]) - 1\n sent_idx = int(name.split('-')[4]) - 1\n remaining_sents_from_atomic_fact = [sent for i, sent in enumerate(SENT_PAIRS[atomic_fact_idx]) if i != sent_idx]\n remaining_sent_pairs_reformatted = [\" \".join(sent) for i, sent in enumerate(SENT_PAIRS) if i != atomic_fact_idx]\n sents_to_check = remaining_sents_from_atomic_fact + remaining_sent_pairs_reformatted\n num_passed_fact = 0\n for sent in sents_to_check:\n label = entailment_check_for_document(sent, document, n=3)\n if 'yes' not in label.lower():\n is_not_entailed = True\n counter -= 1\n break\n else:\n num_passed_fact += 1\n if num_passed_fact == len(sents_to_check):\n is_not_entailed = False\n if is_not_entailed:\n AUGMENTED_PASSAGES[name] = 'invalid_doc'\n else:\n AUGMENTED_PASSAGES[name] = document\n else:\n AUGMENTED_PASSAGES[name] = 'invalid_doc'\n return AUGMENTED_PASSAGES\n\n def construct_claim_doc_label_triples(self, df, new_df):\n mask1 = df.sent_pair_label.apply(lambda x: all([label == 'Yes' for label in x]))\n mask2 = df.org_passage_label.apply(lambda x: x == 'Yes')\n df_valid = df[mask1 & mask2].reset_index(drop=True)\n for row, data in df_valid.iterrows():\n claim = data.claim\n fact_check_labels = data.fact_check_label\n augmented_sents = data.augmented_sent\n augmented_passages = data.augmented_passage\n org_passage = data.org_passage\n for augmented_sent in augmented_sents.values():\n new_df.loc[len(new_df)] = [augmented_sent, org_passage, 1]\n for remove_id, passage in augmented_passages.items():\n atomic_fact_idx = remove_id.split('-')[2]\n if passage != 'invalid_doc' and fact_check_labels[remove_id] != True:\n fact_is_supported = fact_check_labels[remove_id]\n if not fact_is_supported:\n supported_claims = [value for key, value in augmented_sents.items() if atomic_fact_idx not in key]\n unsupported_claims = [value for key, value in augmented_sents.items() if atomic_fact_idx in key]\n for supported_claim in supported_claims:\n new_df.loc[len(new_df)] = [supported_claim, passage, 1]\n for unsupported_claim in unsupported_claims:\n new_df.loc[len(new_df)] = [unsupported_claim, passage, 0]\n df_invalid = df[~(mask1 & mask2)].reset_index(drop=True)\n for row, data in df_invalid.iterrows():\n unsupported_claim = data.claim\n passage = data.org_passage\n new_df.loc[len(new_df)] = [unsupported_claim, passage, 0]\n return new_df\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--doc_path', type=str, default='synthetic_data_gen/claim.txt', help='path to the document that will be used to construct the training data.')\n parser.add_argument('--no_log', action='store_true', help='Disable logging')\n parser.add_argument(\"--test_path\", type=str)\n parser.add_argument(\"--TestCode\", action='store_true')\n args = parser.parse_args()\n if args.no_log:\n logging.basicConfig(level=logging.CRITICAL)\n else:\n logging.basicConfig(\n level=logging.INFO,\n format='%(message)s',\n handlers=[logging.StreamHandler()]\n )\n httpx_logger = logging.getLogger(\"httpx\")\n httpx_logger.setLevel(logging.WARNING)\n c2d_pipeline = C2D_pipeline()\n claim = open(args.doc_path, 'r').read()\n claim_doc_label_df = c2d_pipeline.construct_data(claim)" }, { "task_id": 6, "indent": 2, "script": "\npython synthetic_data_gen/D2C_gen.py \n", "latex_code": "\n\\paragraph{Step 1: Chunk-level summarization} We first divide a human written document into three chunks $\\{D_1, D_2, D_3\\}$ with approximately equal length. We then use GPT-4 to generate a summary sentence for each chunk, resulting in a set of summary sentences $\\mathbf{c} = \\{c_1, c_2, c_3\\}$. We assume these generated summary sentences are factually consistent with respect to their corresponding chunks, \\emph{i.e.} $(D_i, c_i, 1)$ for all $i$, as each chunk is short and LLMs can almost always generate factual summaries in this setting \\cite{Zhang2024}.\n", "completion_path": "./synthetic_data_gen/D2C_gen.py", "namespace": "synthetic_data_gen.D2C_gen.D2C_pipeline.get_chunk_and_claims", "type": "method", "signature_position": [ 98, 98 ], "body_position": [ 99, 115 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Sentence tokenization - Foundation for equal-length chunk division\n# Implements \"divide a human written document into three chunks\" from LaTeX\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nsentences = sent_tokenize(text)\n# [End Snippet 1]\n\ntry:\n # -----------------------------------------------------------------------\n # Snippet 2: Chunk size calculation - Ensures approximate equal length\n # Corresponds to \"three chunks with approximately equal length\" in LaTeX\n # -----------------------------------------------------------------------\n # [Begin Snippet 2]\n num_sentences = len(sentences)\n chunk_size = num_sentences // chunk_num\n # [End Snippet 2]\n\n # -----------------------------------------------------------------------\n # Snippet 3: Chunk creation - Groups sentences into specified chunk structure\n # Direct implementation of chunk division described in LaTeX\n # -----------------------------------------------------------------------\n # [Begin Snippet 3]\n chunks = [sentences[i:i+chunk_size] for i in range(0, num_sentences, chunk_size)]\n chunked_text = [' '.join(chunk) for chunk in chunks]\n # [End Snippet 3]\n\n # -----------------------------------------------------------------------\n # Snippet 4: Chunk count validation - Ensures exact chunk number compliance\n # Handles edge case not explicitly mentioned in LaTeX methodology\n # -----------------------------------------------------------------------\n # [Begin Snippet 4]\n if len(chunked_text) > chunk_num:\n assert len(chunked_text) == chunk_num + 1\n chunked_text[-2] = chunked_text[-2] + \" \" + chunked_text[-1]\n chunked_text = chunked_text[:-1]\n # [End Snippet 4]\nexcept:\n chunked_text = 'invalid'\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Claim generation - Produces summary sentences via GPT-4\n# Implements \"generate a summary sentence for each chunk\" from LaTeX\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nif chunked_text == 'invalid':\n CLAIMS = ['invalid']\nelse:\n CLAIMS = get_response_for_all_chunks(chunked_text)\n# [End Snippet 5]\n\n# ---------------------------------------------------------------------------\n# Snippet 6: Return the list of chunked texts and their corresponding generated claims.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 6]\nreturn chunked_text, CLAIMS\n# [End Snippet 6]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details: \n - None\n\n Mismatched Details: \n - The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX.\n", "Missing_details": [], "Mismatched_details": [ "\n- The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - text (str): \n The complete text document to be processed and divided into chunks for summarization.\n - chunk_num (int, default=3): \n The number of chunks to divide the text into, aiming for approximately equal-length segments.\n", "Arguments_list": [ { "name": "text", "string": "\n- text (str): \n The complete text document to be processed and divided into chunks for summarization.\n", "dependency": null }, { "name": "chunk_num", "string": "\n- chunk_num (int, default=3): \n The number of chunks to divide the text into, aiming for approximately equal-length segments.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n - Intra File Dependencies:\n - get_response_for_all_chunks\n\n - Cross File Dependencies: \n - None\n", "intra_file": [ "get_response_for_all_chunks" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - nltk.tokenize.sent_tokenize\n", "list": [ "nltk.tokenize.sent_tokenize" ] }, "Return": { "Return_String": "\nOutput Variables:\n - chunked_text (list[list[str]]): \n A list where each element is a list of sentences representing a chunk of the original text.\n - CLAIMS (list[str]): \n A list of generated claims corresponding to each chunk, obtained from an external response function.\n", "Return_list": [ { "name": "chunked_text", "string": "\n- chunked_text (list[list[str]]):\n A list where each element is a list of sentences representing a chunk of the original text.\n", "dependency": null }, { "name": "CLAIMS", "string": "\n- CLAIMS (list[str]):\n A list of generated claims corresponding to each chunk, obtained from an external response function.\n", "dependency": null } ] }, "ori_python_file": "import json, pickle\nimport pandas as pd\nimport json\nimport time\nimport logging\nfrom nltk.tokenize import sent_tokenize\nfrom itertools import permutations\nfrom prompt_utils import *\nimport numpy as np\nimport argparse\nATOMIC_FACT_GEN_PROMPT = \"\"\"Document:\n[DOCUMENT]\n\nPlease generate a summary for the document with the following requirements:\n1. The summary should be a fluent and grammatical sentence.\n2. The summary should be no more than 15 words.\n3. The summary should cover information across the document.\nSummary:\"\"\"\nfrom prompt_utils import get_GPT_output, entailment_check_for_document \ndef split_into_chunks(text, chunk_num=3):\n sentences = sent_tokenize(text)\n try:\n num_sentences = len(sentences)\n chunk_size = num_sentences // chunk_num\n chunks = [sentences[i:i+chunk_size] for i in range(0, num_sentences, chunk_size)]\n chunked_text = [' '.join(chunk) for chunk in chunks]\n if len(chunked_text) > chunk_num:\n assert len(chunked_text) == chunk_num + 1\n chunked_text[-2] = chunked_text[-2] + \" \" + chunked_text[-1]\n chunked_text = chunked_text[:-1]\n except:\n return 'invalid'\n return chunked_text\n\ndef get_response_for_all_chunks(chunks):\n responses = []\n for chunk in chunks:\n atomic_fact_gen_prompt_adapted = ATOMIC_FACT_GEN_PROMPT.replace(\"[DOCUMENT]\", chunk)\n retry = True\n while retry:\n try:\n response = get_GPT_output(atomic_fact_gen_prompt_adapted)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n responses.append(response)\n return responses\n\ndef get_permutations_of_facts(facts: list):\n assert type(facts) == list\n facts = {i+1: fact for i, fact in enumerate(facts)}\n all_permutations = []\n for r in range(1, len(facts) + 1):\n all_permutations.extend(permutations(facts, r))\n merge_idx_sents_dict = {}\n for permutation in all_permutations:\n if len(permutation) <= 2:\n permutation_str = [str(s) for s in permutation]\n fact_idx = \"-\".join(permutation_str)\n fact_to_merge = [facts[idx] for idx in permutation]\n merge_idx_sents_dict[fact_idx] = fact_to_merge\n return merge_idx_sents_dict\n\ndef leave_one_sent_out_chunk_construction(chunk, claim, atomic_facts_for_claim):\n sentences = sent_tokenize(chunk)\n neg_paragraphs_for_claim = []\n costs = 0\n for i in range(len(sentences)):\n new_paragraph = [sentence for j, sentence in enumerate(sentences) if j != i]\n new_paragraph = ' '.join(new_paragraph)\n atomic_facts_labels = []\n for atomic_fact in atomic_facts_for_claim:\n label, cost = entailment_check_for_document(claim=atomic_fact, document=new_paragraph, return_cost=True, is_json=False, n=3)\n atomic_facts_labels.append(label)\n costs += cost\n if 'No' in atomic_facts_labels:\n neg_paragraphs_for_claim.append((new_paragraph, atomic_facts_labels))\n return neg_paragraphs_for_claim, costs\n\nclass D2C_pipeline:\n def __init__(self):\n self.logging = logging.getLogger()\n self.total_cost = 0\n self.chunk_num = 3\n \n def construct_data(self, DOCUMENT):\n CHUNKS, CLAIMS = d2c_pipeline.get_chunk_and_claims(DOCUMENT)\n CHUNKS, CLAIMS = pickle.load(open(\"synthetic_data_gen/CHUNKS_CLAIMS.pkl\", \"rb\"))\n CLAIM_ATOMIC_FACT_DICT = d2c_pipeline.get_atomic_facts_for_all_claims_in_doc(CLAIMS)\n CLAIM_ATOMIC_FACT_DICT = pickle.load(open(\"synthetic_data_gen/CLAIM_ATOMIC_FACT_DICT.pkl\", \"rb\"))\n EDITED_PARAGRAPHS = d2c_pipeline.document_claim_augmentation(CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT)\n EDITED_PARAGRAPHS = pickle.load(open(\"synthetic_data_gen/EDITED_PARAGRAPHS.pkl\", \"rb\"))\n REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS = d2c_pipeline.cross_document_claim_augmentation(CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, EDITED_PARAGRAPHS)\n df = d2c_pipeline.construct_claim_doc_label_triples(CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, EDITED_PARAGRAPHS, REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS)\n return df\n \n def get_chunk_and_claims(self, text, chunk_num=3):\n sentences = sent_tokenize(text)\n try:\n num_sentences = len(sentences)\n chunk_size = num_sentences // chunk_num\n chunks = [sentences[i:i+chunk_size] for i in range(0, num_sentences, chunk_size)]\n chunked_text = [' '.join(chunk) for chunk in chunks]\n if len(chunked_text) > chunk_num:\n assert len(chunked_text) == chunk_num + 1\n chunked_text[-2] = chunked_text[-2] + \" \" + chunked_text[-1]\n chunked_text = chunked_text[:-1]\n except:\n chunked_text = 'invalid'\n if chunked_text == 'invalid':\n CLAIMS = ['invalid']\n else:\n CLAIMS = get_response_for_all_chunks(chunked_text)\n return chunked_text, CLAIMS\n \n def decompose_sent_to_facts(self, CLAIM, model=\"gpt-4o-mini\", return_cost=True, is_json=False):\n prompt_for_decompose_adapted = PROMPT_FOR_DECOMPOSE.replace(\"[SENTENCE]\", CLAIM)\n retry = True\n while retry:\n try:\n response, cost = get_GPT_output(prompt_for_decompose_adapted, model=model, return_cost=return_cost, is_json=is_json)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n ATOMIC_FACTS = [item[2:] if '- ' == item[:2] else item for item in response.split(\"\\n\")]\n return ATOMIC_FACTS\n \n def get_atomic_facts_for_all_claims_in_doc(self, CLAIMS, model=\"gpt-4o-mini\"):\n CLAIM_ATOMIC_FACT_DICT = {}\n for CLAIM in CLAIMS:\n atomic_facts = self.decompose_sent_to_facts(CLAIM)\n prompt_for_decompose_adapted = PROMPT_FOR_DECOMPOSE.replace(\"[SENTENCE]\", CLAIM)\n retry = True\n while retry:\n try:\n response = get_GPT_output(prompt_for_decompose_adapted, model=model)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n atomic_facts = [item[2:] if '- ' == item[:2] else item for item in response.split(\"\\n\")]\n CLAIM_ATOMIC_FACT_DICT[CLAIM] = atomic_facts\n return CLAIM_ATOMIC_FACT_DICT\n \n def claim_augmentations(self, CLAIMS):\n merge_idx_sents_dict = get_permutations_of_facts(CLAIMS)\n AUGMENTED_SENT_MAPPING = {}\n for idx, facts in merge_idx_sents_dict.items():\n if len(facts) == 1:\n AUGMENTED_SENT_MAPPING[idx] = facts[0]\n else:\n response = merge_facts_to_sent(facts)\n AUGMENTED_SENT_MAPPING[idx] = response\n self.logging.info(f\"Augmented Claims: {json.dumps(AUGMENTED_SENT_MAPPING, indent=4)}\")\n return AUGMENTED_SENT_MAPPING\n \n def document_claim_augmentation(self, CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, num_chunks=3):\n EDITED_PARAGRAPHS = {}\n if len(CHUNKS) == len(CLAIMS) == len(CLAIM_ATOMIC_FACT_DICT):\n for idx, (chunk, claim) in enumerate(zip(CHUNKS, CLAIMS)):\n atomic_facts = CLAIM_ATOMIC_FACT_DICT[claim]\n sentences = sent_tokenize(chunk)\n neg_paragraphs_for_claim = []\n for i in range(len(sentences)):\n new_paragraph = [sentence for j, sentence in enumerate(sentences) if j != i]\n new_paragraph = ' '.join(new_paragraph)\n atomic_facts_labels = []\n for atomic_fact in atomic_facts:\n label = entailment_check_for_document(\n claim=atomic_fact,\n document=new_paragraph,\n n=num_chunks\n )\n atomic_facts_labels.append(label)\n if 'No' in atomic_facts_labels:\n neg_paragraphs_for_claim.append((new_paragraph, atomic_facts_labels))\n EDITED_PARAGRAPHS[str(idx+1)] = neg_paragraphs_for_claim\n return EDITED_PARAGRAPHS\n \n def cross_document_claim_augmentation(self, CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, EDITED_PARAGRAPHS):\n REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS = {}\n for sent_idx, items in EDITED_PARAGRAPHS.items():\n remaining_doc_chunks_ids = [i for i, chunk in enumerate(CHUNKS) if i != int(sent_idx)-1]\n sent_idx_remain_chunks_and_labels = {}\n for edited_paragraph, atomic_fact_labels in items:\n unsupported_claim = CLAIMS[int(sent_idx)-1]\n corresponding_atomic_facts = CLAIM_ATOMIC_FACT_DICT[unsupported_claim]\n remain_chunks_and_labels = []\n for remaining_doc_chunks_id in remaining_doc_chunks_ids:\n remaining_doc_chunk = CHUNKS[remaining_doc_chunks_id]\n labels = []\n for corresponding_atomic_fact in corresponding_atomic_facts:\n label = entailment_check_for_document(\n claim=corresponding_atomic_fact,\n document=remaining_doc_chunk,\n return_cost=True,\n is_json=False,\n n=3\n )\n labels.append(label)\n remain_chunks_and_labels.append((str(remaining_doc_chunks_id + 1), labels))\n sent_idx_remain_chunks_and_labels[edited_paragraph] = remain_chunks_and_labels\n REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS[sent_idx] = sent_idx_remain_chunks_and_labels\n return REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS\n \n def construct_claim_doc_label_triples(self, CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, EDITED_PARAGRAPHS, REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS):\n new_df = pd.DataFrame(columns=['claim', 'doc', 'label'])\n for claim_idx, claim in enumerate(CLAIMS):\n new_df.loc[len(new_df)] = [claim, CHUNKS[claim_idx], 1]\n for sent_idx, items in EDITED_PARAGRAPHS.items():\n claim = CLAIMS[int(sent_idx)-1]\n corresponding_atomic_facts = CLAIM_ATOMIC_FACT_DICT[claim]\n check_claim_by_rest_para_dict = REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS[sent_idx]\n for edited_paragraph, atomic_fact_labels in items:\n for atomic_idx, atomic_fact in enumerate(corresponding_atomic_facts):\n if atomic_fact_labels[atomic_idx] == 'Yes':\n new_df.loc[len(new_df)] = [atomic_fact, edited_paragraph, 1]\n elif atomic_fact_labels[atomic_idx] == 'No':\n new_df.loc[len(new_df)] = [atomic_fact, edited_paragraph, 0]\n else:\n raise ValueError(\"The atomic fact label is not 'Yes' or 'No'\")\n if 'No' in atomic_fact_labels:\n wrong_fact = str([corresponding_atomic_facts[i] for i in np.where(np.array(atomic_fact_labels) == 'No')[0]])\n new_df.loc[len(new_df)] = [claim, edited_paragraph, 0]\n else:\n new_df.loc[len(new_df)] = [claim, edited_paragraph, 1]\n if len(check_claim_by_rest_para_dict.values()) != 0:\n for item in list(check_claim_by_rest_para_dict.values())[0]:\n para_idx = int(item[0]) - 1\n for atomic_idx, atomic_fact in enumerate(corresponding_atomic_facts):\n if item[1][atomic_idx] == 'Yes':\n new_df.loc[len(new_df)] = [atomic_fact, CHUNKS[para_idx], 1]\n elif item[1][atomic_idx] == 'No':\n new_df.loc[len(new_df)] = [atomic_fact, CHUNKS[para_idx], 0]\n else:\n raise ValueError(\"The atomic fact label is not 'Yes' or 'No\")\n if 'No' in item[1]:\n wrong_fact = str([corresponding_atomic_facts[i] for i in np.where(np.array(item[1]) == 'No')[0]])\n new_df.loc[len(new_df)] = [claim, CHUNKS[para_idx], 0]\n else:\n new_df.loc[len(new_df)] = [claim, CHUNKS[para_idx], 1]\n new_df = new_df[new_df.doc.apply(lambda x: len(x)) >= 500].reset_index(drop=True)\n self.logging.info(f\"Constructed dataframe:\\n{new_df}\")\n return new_df\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--doc_path', type=str, default='synthetic_data_gen/D2C-doc-example.txt', help='path to the document that will be used to construct the training data.')\n parser.add_argument('--no_log', action='store_true', help='Disable logging')\n parser.add_argument(\"--test_path\", type=str)\n parser.add_argument(\"--TestCode\", action='store_true')\n args = parser.parse_args()\n if args.no_log:\n logging.basicConfig(level=logging.CRITICAL)\n else:\n logging.basicConfig(\n level=logging.INFO,\n format='%(message)s',\n handlers=[logging.StreamHandler()]\n )\n httpx_logger = logging.getLogger(\"httpx\")\n httpx_logger.setLevel(logging.WARNING)\n with open(args.doc_path) as file:\n DOCUMENT = file.read()\n d2c_pipeline = D2C_pipeline()\n claim_doc_label_df = d2c_pipeline.construct_data(DOCUMENT)" }, { "task_id": 7, "indent": 2, "script": "\npython synthetic_data_gen/D2C_gen.py\n", "latex_code": "\n\\paragraph{Step 2: Claim decomposition and subclaim augmentation} Similar to the C2D method, for a summary sentence $c_i$ in $\\mathbf{c}$, we decompose it into atomic facts $\\mathbf{a_i} = \\{a_{i,1}, \\ldots, a_{i, l}\\}$.\n", "completion_path": "./synthetic_data_gen/D2C_gen.py", "namespace": "synthetic_data_gen.D2C_gen.D2C_pipeline.get_atomic_facts_for_all_claims_in_doc", "type": "method", "signature_position": [ 130, 130 ], "body_position": [ 131, 145 ], "ReferenceCode_With_Comments": "\nCLAIM_ATOMIC_FACT_DICT = {}\n\nfor CLAIM in CLAIMS:\n\n # ---------------------------------------------------------------------------\n # Snippet 1: Decompose the current claim into atomic facts using an initial helper function.\n # This represents the first step of claim decomposition, analogous to extracting a_i from c_i in the LaTeX.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 1]\n atomic_facts = self.decompose_sent_to_facts(CLAIM)\n # [End Snippet 1]\n\n # ---------------------------------------------------------------------------\n # Snippet 2: Prepare the prompt by replacing the placeholder in the decomposition template with the current claim.\n # This adapts the general decomposition prompt to the specific claim, mirroring the LaTeX's decomposition process.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 2]\n prompt_for_decompose_adapted = PROMPT_FOR_DECOMPOSE.replace(\"[SENTENCE]\", CLAIM)\n # [End Snippet 2]\n\n # ---------------------------------------------------------------------------\n # Snippet 3: Obtain the GPT model's response for claim decomposition.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 3]\n retry = True\n while retry:\n try:\n response = get_GPT_output(prompt_for_decompose_adapted, model=model)\n retry = False \n except Exception as e:\n retry = True\n time.sleep(10)\n # [End Snippet 3]\n\n # ---------------------------------------------------------------------------\n # Snippet 4: Post-process the GPT response by splitting it into lines and removing any leading \"- \" if present.\n # This step extracts clean atomic facts from the response, fulfilling the extraction requirement in the LaTeX.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 4]\n atomic_facts = [item[2:] if '- ' == item[:2] else item for item in response.split(\"\\n\")]\n # [End Snippet 4]\n\n CLAIM_ATOMIC_FACT_DICT[CLAIM] = atomic_facts\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Return the complete dictionary containing all claims and their atomic facts.\n# This return statement concludes the decomposition process, providing the data for subsequent augmentation.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nreturn CLAIM_ATOMIC_FACT_DICT\n# [End Snippet 5]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details: \n - Implement retry mechanism for handling API call failures.\n\n Mismatched Details: \n - The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX.\n", "Missing_details": [ "\n- Implement retry mechanism for handling API call failures.\n" ], "Mismatched_details": [ "\n- The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - CLAIMS (list[str]): \n A list containing summary sentences or claims from the document that need to be decomposed \n into atomic facts.\n - model (str, optional): \n The identifier for the language model to be used for generating atomic facts, \n defaulting to \"gpt-3.5-turbo-0125\".\n", "Arguments_list": [ { "name": "CLAIMS", "string": "\n- CLAIMS (list[str]):\n A list containing summary sentences or claims from the document that need to be decomposed \n into atomic facts.\n", "dependency": null }, { "name": "model", "string": "\n- model (str, optional):\n The identifier for the language model to be used for generating atomic facts, \n defaulting to \"gpt-3.5-turbo-0125\".\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n - Intra File Dependencies: \n - D2C_pipeline.decompose_sent_to_facts\n \n - Cross File Dependencies: \n - prompt_utils.get_GPT_output\n", "intra_file": [ "D2C_pipeline.decompose_sent_to_facts" ], "cross_file": [ "prompt_utils.get_GPT_output" ] }, "external_APIs": { "string": "\nExternal APIs:\n - time.sleep\n ", "list": [ "time.sleep" ] }, "Return": { "Return_String": "\nOutput Variables:\n - CLAIM_ATOMIC_FACT_DICT (dict): \n A dictionary mapping each original claim to a list of its corresponding atomic facts.\n", "Return_list": [ { "name": "CLAIM_ATOMIC_FACT_DICT", "string": "\n- CLAIM_ATOMIC_FACT_DICT (dict):\n A dictionary mapping each original claim to a list of its corresponding atomic facts.\n", "dependency": null } ] }, "ori_python_file": "import json, pickle\nimport pandas as pd\nimport json\nimport time\nimport logging\nfrom nltk.tokenize import sent_tokenize\nfrom itertools import permutations\nfrom prompt_utils import *\nimport numpy as np\nimport argparse\nATOMIC_FACT_GEN_PROMPT = \"\"\"Document:\n[DOCUMENT]\n\nPlease generate a summary for the document with the following requirements:\n1. The summary should be a fluent and grammatical sentence.\n2. The summary should be no more than 15 words.\n3. The summary should cover information across the document.\nSummary:\"\"\"\nfrom prompt_utils import get_GPT_output, entailment_check_for_document \ndef split_into_chunks(text, chunk_num=3):\n sentences = sent_tokenize(text)\n try:\n num_sentences = len(sentences)\n chunk_size = num_sentences // chunk_num\n chunks = [sentences[i:i+chunk_size] for i in range(0, num_sentences, chunk_size)]\n chunked_text = [' '.join(chunk) for chunk in chunks]\n if len(chunked_text) > chunk_num:\n assert len(chunked_text) == chunk_num + 1\n chunked_text[-2] = chunked_text[-2] + \" \" + chunked_text[-1]\n chunked_text = chunked_text[:-1]\n except:\n return 'invalid'\n return chunked_text\n\ndef get_response_for_all_chunks(chunks):\n responses = []\n for chunk in chunks:\n atomic_fact_gen_prompt_adapted = ATOMIC_FACT_GEN_PROMPT.replace(\"[DOCUMENT]\", chunk)\n retry = True\n while retry:\n try:\n response = get_GPT_output(atomic_fact_gen_prompt_adapted)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n responses.append(response)\n return responses\n\ndef get_permutations_of_facts(facts: list):\n assert type(facts) == list\n facts = {i+1: fact for i, fact in enumerate(facts)}\n all_permutations = []\n for r in range(1, len(facts) + 1):\n all_permutations.extend(permutations(facts, r))\n merge_idx_sents_dict = {}\n for permutation in all_permutations:\n if len(permutation) <= 2:\n permutation_str = [str(s) for s in permutation]\n fact_idx = \"-\".join(permutation_str)\n fact_to_merge = [facts[idx] for idx in permutation]\n merge_idx_sents_dict[fact_idx] = fact_to_merge\n return merge_idx_sents_dict\n\ndef leave_one_sent_out_chunk_construction(chunk, claim, atomic_facts_for_claim):\n sentences = sent_tokenize(chunk)\n neg_paragraphs_for_claim = []\n costs = 0\n for i in range(len(sentences)):\n new_paragraph = [sentence for j, sentence in enumerate(sentences) if j != i]\n new_paragraph = ' '.join(new_paragraph)\n atomic_facts_labels = []\n for atomic_fact in atomic_facts_for_claim:\n label, cost = entailment_check_for_document(claim=atomic_fact, document=new_paragraph, return_cost=True, is_json=False, n=3)\n atomic_facts_labels.append(label)\n costs += cost\n if 'No' in atomic_facts_labels:\n neg_paragraphs_for_claim.append((new_paragraph, atomic_facts_labels))\n return neg_paragraphs_for_claim, costs\n\nclass D2C_pipeline:\n def __init__(self):\n self.logging = logging.getLogger()\n self.total_cost = 0\n self.chunk_num = 3\n \n def construct_data(self, DOCUMENT):\n CHUNKS, CLAIMS = d2c_pipeline.get_chunk_and_claims(DOCUMENT)\n CHUNKS, CLAIMS = pickle.load(open(\"synthetic_data_gen/CHUNKS_CLAIMS.pkl\", \"rb\"))\n CLAIM_ATOMIC_FACT_DICT = d2c_pipeline.get_atomic_facts_for_all_claims_in_doc(CLAIMS)\n CLAIM_ATOMIC_FACT_DICT = pickle.load(open(\"synthetic_data_gen/CLAIM_ATOMIC_FACT_DICT.pkl\", \"rb\"))\n EDITED_PARAGRAPHS = d2c_pipeline.document_claim_augmentation(CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT)\n EDITED_PARAGRAPHS = pickle.load(open(\"synthetic_data_gen/EDITED_PARAGRAPHS.pkl\", \"rb\"))\n REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS = d2c_pipeline.cross_document_claim_augmentation(CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, EDITED_PARAGRAPHS)\n df = d2c_pipeline.construct_claim_doc_label_triples(CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, EDITED_PARAGRAPHS, REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS)\n return df\n \n def get_chunk_and_claims(self, text, chunk_num=3):\n sentences = sent_tokenize(text)\n try:\n num_sentences = len(sentences)\n chunk_size = num_sentences // chunk_num\n chunks = [sentences[i:i+chunk_size] for i in range(0, num_sentences, chunk_size)]\n chunked_text = [' '.join(chunk) for chunk in chunks]\n if len(chunked_text) > chunk_num:\n assert len(chunked_text) == chunk_num + 1\n chunked_text[-2] = chunked_text[-2] + \" \" + chunked_text[-1]\n chunked_text = chunked_text[:-1]\n except:\n chunked_text = 'invalid'\n if chunked_text == 'invalid':\n CLAIMS = ['invalid']\n else:\n CLAIMS = get_response_for_all_chunks(chunked_text)\n return chunked_text, CLAIMS\n \n def decompose_sent_to_facts(self, CLAIM, model=\"gpt-4o-mini\", return_cost=True, is_json=False):\n prompt_for_decompose_adapted = PROMPT_FOR_DECOMPOSE.replace(\"[SENTENCE]\", CLAIM)\n retry = True\n while retry:\n try:\n response, cost = get_GPT_output(prompt_for_decompose_adapted, model=model, return_cost=return_cost, is_json=is_json)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n ATOMIC_FACTS = [item[2:] if '- ' == item[:2] else item for item in response.split(\"\\n\")]\n return ATOMIC_FACTS\n \n def get_atomic_facts_for_all_claims_in_doc(self, CLAIMS, model=\"gpt-4o-mini\"):\n CLAIM_ATOMIC_FACT_DICT = {}\n for CLAIM in CLAIMS:\n atomic_facts = self.decompose_sent_to_facts(CLAIM)\n prompt_for_decompose_adapted = PROMPT_FOR_DECOMPOSE.replace(\"[SENTENCE]\", CLAIM)\n retry = True\n while retry:\n try:\n response = get_GPT_output(prompt_for_decompose_adapted, model=model)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n atomic_facts = [item[2:] if '- ' == item[:2] else item for item in response.split(\"\\n\")]\n CLAIM_ATOMIC_FACT_DICT[CLAIM] = atomic_facts\n return CLAIM_ATOMIC_FACT_DICT\n \n def claim_augmentations(self, CLAIMS):\n merge_idx_sents_dict = get_permutations_of_facts(CLAIMS)\n AUGMENTED_SENT_MAPPING = {}\n for idx, facts in merge_idx_sents_dict.items():\n if len(facts) == 1:\n AUGMENTED_SENT_MAPPING[idx] = facts[0]\n else:\n response = merge_facts_to_sent(facts)\n AUGMENTED_SENT_MAPPING[idx] = response\n self.logging.info(f\"Augmented Claims: {json.dumps(AUGMENTED_SENT_MAPPING, indent=4)}\")\n return AUGMENTED_SENT_MAPPING\n \n def document_claim_augmentation(self, CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, num_chunks=3):\n EDITED_PARAGRAPHS = {}\n if len(CHUNKS) == len(CLAIMS) == len(CLAIM_ATOMIC_FACT_DICT):\n for idx, (chunk, claim) in enumerate(zip(CHUNKS, CLAIMS)):\n atomic_facts = CLAIM_ATOMIC_FACT_DICT[claim]\n sentences = sent_tokenize(chunk)\n neg_paragraphs_for_claim = []\n for i in range(len(sentences)):\n new_paragraph = [sentence for j, sentence in enumerate(sentences) if j != i]\n new_paragraph = ' '.join(new_paragraph)\n atomic_facts_labels = []\n for atomic_fact in atomic_facts:\n label = entailment_check_for_document(\n claim=atomic_fact,\n document=new_paragraph,\n n=num_chunks\n )\n atomic_facts_labels.append(label)\n if 'No' in atomic_facts_labels:\n neg_paragraphs_for_claim.append((new_paragraph, atomic_facts_labels))\n EDITED_PARAGRAPHS[str(idx+1)] = neg_paragraphs_for_claim\n return EDITED_PARAGRAPHS\n \n def cross_document_claim_augmentation(self, CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, EDITED_PARAGRAPHS):\n REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS = {}\n for sent_idx, items in EDITED_PARAGRAPHS.items():\n remaining_doc_chunks_ids = [i for i, chunk in enumerate(CHUNKS) if i != int(sent_idx)-1]\n sent_idx_remain_chunks_and_labels = {}\n for edited_paragraph, atomic_fact_labels in items:\n unsupported_claim = CLAIMS[int(sent_idx)-1]\n corresponding_atomic_facts = CLAIM_ATOMIC_FACT_DICT[unsupported_claim]\n remain_chunks_and_labels = []\n for remaining_doc_chunks_id in remaining_doc_chunks_ids:\n remaining_doc_chunk = CHUNKS[remaining_doc_chunks_id]\n labels = []\n for corresponding_atomic_fact in corresponding_atomic_facts:\n label = entailment_check_for_document(\n claim=corresponding_atomic_fact,\n document=remaining_doc_chunk,\n return_cost=True,\n is_json=False,\n n=3\n )\n labels.append(label)\n remain_chunks_and_labels.append((str(remaining_doc_chunks_id + 1), labels))\n sent_idx_remain_chunks_and_labels[edited_paragraph] = remain_chunks_and_labels\n REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS[sent_idx] = sent_idx_remain_chunks_and_labels\n return REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS\n \n def construct_claim_doc_label_triples(self, CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, EDITED_PARAGRAPHS, REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS):\n new_df = pd.DataFrame(columns=['claim', 'doc', 'label'])\n for claim_idx, claim in enumerate(CLAIMS):\n new_df.loc[len(new_df)] = [claim, CHUNKS[claim_idx], 1]\n for sent_idx, items in EDITED_PARAGRAPHS.items():\n claim = CLAIMS[int(sent_idx)-1]\n corresponding_atomic_facts = CLAIM_ATOMIC_FACT_DICT[claim]\n check_claim_by_rest_para_dict = REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS[sent_idx]\n for edited_paragraph, atomic_fact_labels in items:\n for atomic_idx, atomic_fact in enumerate(corresponding_atomic_facts):\n if atomic_fact_labels[atomic_idx] == 'Yes':\n new_df.loc[len(new_df)] = [atomic_fact, edited_paragraph, 1]\n elif atomic_fact_labels[atomic_idx] == 'No':\n new_df.loc[len(new_df)] = [atomic_fact, edited_paragraph, 0]\n else:\n raise ValueError(\"The atomic fact label is not 'Yes' or 'No'\")\n if 'No' in atomic_fact_labels:\n wrong_fact = str([corresponding_atomic_facts[i] for i in np.where(np.array(atomic_fact_labels) == 'No')[0]])\n new_df.loc[len(new_df)] = [claim, edited_paragraph, 0]\n else:\n new_df.loc[len(new_df)] = [claim, edited_paragraph, 1]\n if len(check_claim_by_rest_para_dict.values()) != 0:\n for item in list(check_claim_by_rest_para_dict.values())[0]:\n para_idx = int(item[0]) - 1\n for atomic_idx, atomic_fact in enumerate(corresponding_atomic_facts):\n if item[1][atomic_idx] == 'Yes':\n new_df.loc[len(new_df)] = [atomic_fact, CHUNKS[para_idx], 1]\n elif item[1][atomic_idx] == 'No':\n new_df.loc[len(new_df)] = [atomic_fact, CHUNKS[para_idx], 0]\n else:\n raise ValueError(\"The atomic fact label is not 'Yes' or 'No\")\n if 'No' in item[1]:\n wrong_fact = str([corresponding_atomic_facts[i] for i in np.where(np.array(item[1]) == 'No')[0]])\n new_df.loc[len(new_df)] = [claim, CHUNKS[para_idx], 0]\n else:\n new_df.loc[len(new_df)] = [claim, CHUNKS[para_idx], 1]\n new_df = new_df[new_df.doc.apply(lambda x: len(x)) >= 500].reset_index(drop=True)\n self.logging.info(f\"Constructed dataframe:\\n{new_df}\")\n return new_df\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--doc_path', type=str, default='synthetic_data_gen/D2C-doc-example.txt', help='path to the document that will be used to construct the training data.')\n parser.add_argument('--no_log', action='store_true', help='Disable logging')\n parser.add_argument(\"--test_path\", type=str)\n parser.add_argument(\"--TestCode\", action='store_true')\n args = parser.parse_args()\n if args.no_log:\n logging.basicConfig(level=logging.CRITICAL)\n else:\n logging.basicConfig(\n level=logging.INFO,\n format='%(message)s',\n handlers=[logging.StreamHandler()]\n )\n httpx_logger = logging.getLogger(\"httpx\")\n httpx_logger.setLevel(logging.WARNING)\n with open(args.doc_path) as file:\n DOCUMENT = file.read()\n d2c_pipeline = D2C_pipeline()\n claim_doc_label_df = d2c_pipeline.construct_data(DOCUMENT)" }, { "task_id": 8, "indent": 2, "script": "\npython synthetic_data_gen/D2C_gen.py\n", "latex_code": "\n\\paragraph{Step 3: Document-claim augmentation} This step aims to do data augmentation on a $(D_i, c_i)$ pair. Given a chunk $D_i = \\mathrm{\\texttt{Concat}(\\mathbf{s})}$, which is the concatenation of $n$ sentences $\\mathbf{s} = \\{s_{i,1}, ..., s_{i,n}\\}$, we construct new documents by iteratively removing each sentence $s_{i,j}$ from $\\mathbf{s}$:\n$$D'_{i \\setminus j} = \\mathrm{\\texttt{Concat}}(\\mathbf{s}\\setminus \\{s_{i,j}\\}).$$\nWe then determine the entailment label for each atomic fact $a_{i, k}$ in $c_i$, where $k \\in \\{1, \\ldots, l\\}$:\n$$L^{-j}(a_{i, k}) = \\mathrm{Ent}(D'_{i \\setminus j}, a_{i, k}) \\in \\{0, 1\\}.$$\nSimilar to step 5 in C2D, if $L^{-j}(a_{i, k}) = 1$ for all $a_{i, k} \\in \\mathbf{a}'_i$, we create tuples $(D'_{i \\setminus j}, \\mathrm{\\texttt{Merge}}(\\mathbf{a}'_i), 1)$. Conversely, if there exists any $a_{i, k} \\in \\mathbf{a}'_i$ such that $L^{-j}(a_{i, k}) = 0$, we then create tuples $(D'_{i \\setminus j}, \\mathrm{\\texttt{Merge}}(\\mathbf{a}'_i), 0)$.\n", "completion_path": "./synthetic_data_gen/D2C_gen.py", "namespace": "synthetic_data_gen.D2C_gen.D2C_pipeline.document_claim_augmentation", "type": "method", "signature_position": [ 159, 159 ], "body_position": [ 160, 180 ], "ReferenceCode_With_Comments": "\nEDITED_PARAGRAPHS = {}\n\n# ---------------------------------------------------------------------------\n# Snippet 1: Verify that the number of document chunks, claims, and atomic fact mappings are consistent.\n# This check ensures that each claim has a corresponding chunk and atomic facts as required by the LaTeX.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nif len(CHUNKS) == len(CLAIMS) == len(CLAIM_ATOMIC_FACT_DICT):\n# [End Snippet 1]\n for idx, (chunk, claim) in enumerate(zip(CHUNKS, CLAIMS)):\n\n # ---------------------------------------------------------------------------\n # Snippet 2: Retrieve the atomic facts for the current claim.\n # This corresponds to extracting the atomic facts (a_i) for claim c_i from the provided mapping.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 2]\n atomic_facts = CLAIM_ATOMIC_FACT_DICT[claim]\n # [End Snippet 2]\n\n # ---------------------------------------------------------------------------\n # Snippet 3: Tokenize the current document chunk into sentences.\n # This is in line with splitting D_i into its constituent sentences as required for the leave-one-out approach.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 3]\n sentences = sent_tokenize(chunk)\n # [End Snippet 3]\n\n neg_paragraphs_for_claim = []\n\n for i in range(len(sentences)):\n # -----------------------------------------------------------------------\n # Snippet 4: Construct a new paragraph by excluding the sentence at index i.\n # This corresponds to forming D'_{i \\setminus j} as the concatenation of all sentences except the one removed.\n # -----------------------------------------------------------------------\n # [Begin Snippet 4]\n new_paragraph = [sentence for j, sentence in enumerate(sentences) if j != i]\n new_paragraph = ' '.join(new_paragraph)\n # [End Snippet 4]\n\n atomic_facts_labels = []\n\n # ---------------------------------------------------------------------------\n # Snippet 5: For each atomic fact in the current claim, determine if the new paragraph supports it.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 5]\n for atomic_fact in atomic_facts:\n label = entailment_check_for_document(\n claim=atomic_fact, \n document=new_paragraph, \n n=num_chunks\n )\n atomic_facts_labels.append(label)\n # [End Snippet 5]\n\n # ---------------------------------------------------------------------------\n # Snippet 6: Check if the new paragraph fails to support at least one atomic fact.\n # According to the LaTeX, if any atomic fact is not supported (i.e., label is 'No'), the paragraph should be marked as negative.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 6]\n if 'No' in atomic_facts_labels:\n neg_paragraphs_for_claim.append((new_paragraph, atomic_facts_labels))\n # [End Snippet 6]\n\n EDITED_PARAGRAPHS[str(idx+1)] = neg_paragraphs_for_claim\n\n# ---------------------------------------------------------------------------\n# Snippet 7: Return the complete dictionary of edited paragraphs for all claims.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 7]\nreturn EDITED_PARAGRAPHS\n# [End Snippet 7]\n\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details: \n - How to split the input text into sentences is not mentioned. The LaTeX description simply introduces $D_i = \\mathrm{\\texttt{Concat}(\\mathbf{s})}$, which concatenates n sentences. The details about using any tokenizer is missing. The code should use 'sent_tokenize' function.\n - The LaTeX omits a step for selectively filtering augmented document-claim pairs based on their entailment outcomes. Specifically, it does not describe the workflow where, after computing entailment labels for each atomic fact in a modified document, only those modified documents that fail to support at least one atomic fact are retained as negative examples. This process involves evaluating each modified document against all atomic facts of the claim, collecting the entailment results, and then checking if any result indicates non-support. If so, the modified document and its entailment labels are stored as a negative example; otherwise, they are discarded.\n - The LaTeX description does not specify a validation process to ensure that the number of document chunks, claims, and their associated atomic facts align before proceeding with augmentation. In practice, such a step involves checking that each document chunk has a corresponding claim and that each claim is mapped to its atomic facts. This workflow starts by comparing the total count of document chunks to the total count of claims and the total number of entries in the atomic fact mapping. If these counts match, the process continues; otherwise, it halts to avoid mismatched pairings, ensuring that subsequent steps operate on consistent data.\n\n\n Mismatched Details: \n - The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX.\n", "Missing_details": [ "\n- How to split the input text into sentences is not mentioned. The LaTeX description simply introduces $D_i = \\mathrm{\\texttt{Concat}(\\mathbf{s})}$, which concatenates n sentences. The details about using any tokenizer is missing. The code should use 'sent_tokenize' function.\n", "\n- The LaTeX omits a step for selectively filtering augmented document-claim pairs based on their entailment outcomes. Specifically, it does not describe the workflow where, after computing entailment labels for each atomic fact in a modified document, only those modified documents that fail to support at least one atomic fact are retained as negative examples. This process involves evaluating each modified document against all atomic facts of the claim, collecting the entailment results, and then checking if any result indicates non-support. If so, the modified document and its entailment labels are stored as a negative example; otherwise, they are discarded.\n", "\n- The LaTeX description does not specify a validation process to ensure that the number of document chunks, claims, and their associated atomic facts align before proceeding with augmentation. In practice, such a step involves checking that each document chunk has a corresponding claim and that each claim is mapped to its atomic facts. This workflow starts by comparing the total count of document chunks to the total count of claims and the total number of entries in the atomic fact mapping. If these counts match, the process continues; otherwise, it halts to avoid mismatched pairings, ensuring that subsequent steps operate on consistent data.\n" ], "Mismatched_details": [ "\n- The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - CHUNKS (list[str]): \n A list where each element is a document chunk composed of concatenated sentences.\n - CLAIMS (list[str]): \n A list of claims corresponding to each document chunk in CHUNKS.\n - CLAIM_ATOMIC_FACT_DICT (dict): \n A dictionary mapping each claim to its list of atomic facts. Each key is a claim (str), and the \n value is a list of atomic facts (str) associated with that claim.\n - num_chunks (int): \n The number of chunks to consider for entailment checks, defaulting to 3.\n", "Arguments_list": [ { "name": "CHUNKS", "string": "\n- CHUNKS (list[str]):\n A list where each element is a document chunk composed of concatenated sentences.\n", "dependency": null }, { "name": "CLAIMS", "string": "\n- CLAIMS (list[str]):\n A list of claims corresponding to each document chunk in CHUNKS.\n", "dependency": null }, { "name": "CLAIM_ATOMIC_FACT_DICT", "string": "\n- CLAIM_ATOMIC_FACT_DICT (dict):\n A dictionary mapping each claim to its list of atomic facts. Each key is a claim (str), and the \n value is a list of atomic facts (str) associated with that claim.\n", "dependency": null }, { "name": "num_chunks", "string": "\n- num_chunks (int):\n The number of chunks to consider for entailment checks, defaulting to 3.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n - Intra File Dependencies: \n - None\n\n - Cross File Dependencies: \n - prompt_utils.entailment_check_for_document\n", "intra_file": [], "cross_file": [ "prompt_utils.entailment_check_for_document" ] }, "external_APIs": { "string": "\nExternal APIs:\n - nltk.tokenize.sent_tokenize\n", "list": [ "nltk.tokenize.sent_tokenize" ] }, "Return": { "Return_String": "\nOutput Variables:\n - EDITED_PARAGRAPHS (dict): \n A dictionary where each key is a stringified index (starting from '1') corresponding to the \n input CHUNKS. The value for each key is a list of tuples, each containing:\n - The modified paragraph (str) with one sentence removed.\n - A list of entailment labels (str) for each atomic fact, indicating whether the fact is \n entailed ('Yes') or not ('No') by the modified paragraph.\n", "Return_list": [ { "name": "EDITED_PARAGRAPHS", "string": "\n- EDITED_PARAGRAPHS (dict):\n A dictionary where each key is a stringified index (starting from '1') corresponding to the \n input CHUNKS. The value for each key is a list of tuples, each containing:\n - The modified paragraph (str) with one sentence removed.\n - A list of entailment labels (str) for each atomic fact, indicating whether the fact is \n entailed ('Yes') or not ('No') by the modified paragraph. \n", "dependency": null } ] }, "ori_python_file": "import json, pickle\nimport pandas as pd\nimport json\nimport time\nimport logging\nfrom nltk.tokenize import sent_tokenize\nfrom itertools import permutations\nfrom prompt_utils import *\nimport numpy as np\nimport argparse\nATOMIC_FACT_GEN_PROMPT = \"\"\"Document:\n[DOCUMENT]\n\nPlease generate a summary for the document with the following requirements:\n1. The summary should be a fluent and grammatical sentence.\n2. The summary should be no more than 15 words.\n3. The summary should cover information across the document.\nSummary:\"\"\"\nfrom prompt_utils import get_GPT_output, entailment_check_for_document \ndef split_into_chunks(text, chunk_num=3):\n sentences = sent_tokenize(text)\n try:\n num_sentences = len(sentences)\n chunk_size = num_sentences // chunk_num\n chunks = [sentences[i:i+chunk_size] for i in range(0, num_sentences, chunk_size)]\n chunked_text = [' '.join(chunk) for chunk in chunks]\n if len(chunked_text) > chunk_num:\n assert len(chunked_text) == chunk_num + 1\n chunked_text[-2] = chunked_text[-2] + \" \" + chunked_text[-1]\n chunked_text = chunked_text[:-1]\n except:\n return 'invalid'\n return chunked_text\n\ndef get_response_for_all_chunks(chunks):\n responses = []\n for chunk in chunks:\n atomic_fact_gen_prompt_adapted = ATOMIC_FACT_GEN_PROMPT.replace(\"[DOCUMENT]\", chunk)\n retry = True\n while retry:\n try:\n response = get_GPT_output(atomic_fact_gen_prompt_adapted)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n responses.append(response)\n return responses\n\ndef get_permutations_of_facts(facts: list):\n assert type(facts) == list\n facts = {i+1: fact for i, fact in enumerate(facts)}\n all_permutations = []\n for r in range(1, len(facts) + 1):\n all_permutations.extend(permutations(facts, r))\n merge_idx_sents_dict = {}\n for permutation in all_permutations:\n if len(permutation) <= 2:\n permutation_str = [str(s) for s in permutation]\n fact_idx = \"-\".join(permutation_str)\n fact_to_merge = [facts[idx] for idx in permutation]\n merge_idx_sents_dict[fact_idx] = fact_to_merge\n return merge_idx_sents_dict\n\ndef leave_one_sent_out_chunk_construction(chunk, claim, atomic_facts_for_claim):\n sentences = sent_tokenize(chunk)\n neg_paragraphs_for_claim = []\n costs = 0\n for i in range(len(sentences)):\n new_paragraph = [sentence for j, sentence in enumerate(sentences) if j != i]\n new_paragraph = ' '.join(new_paragraph)\n atomic_facts_labels = []\n for atomic_fact in atomic_facts_for_claim:\n label, cost = entailment_check_for_document(claim=atomic_fact, document=new_paragraph, return_cost=True, is_json=False, n=3)\n atomic_facts_labels.append(label)\n costs += cost\n if 'No' in atomic_facts_labels:\n neg_paragraphs_for_claim.append((new_paragraph, atomic_facts_labels))\n return neg_paragraphs_for_claim, costs\n\nclass D2C_pipeline:\n def __init__(self):\n self.logging = logging.getLogger()\n self.total_cost = 0\n self.chunk_num = 3\n \n def construct_data(self, DOCUMENT):\n CHUNKS, CLAIMS = d2c_pipeline.get_chunk_and_claims(DOCUMENT)\n CHUNKS, CLAIMS = pickle.load(open(\"synthetic_data_gen/CHUNKS_CLAIMS.pkl\", \"rb\"))\n CLAIM_ATOMIC_FACT_DICT = d2c_pipeline.get_atomic_facts_for_all_claims_in_doc(CLAIMS)\n CLAIM_ATOMIC_FACT_DICT = pickle.load(open(\"synthetic_data_gen/CLAIM_ATOMIC_FACT_DICT.pkl\", \"rb\"))\n EDITED_PARAGRAPHS = d2c_pipeline.document_claim_augmentation(CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT)\n EDITED_PARAGRAPHS = pickle.load(open(\"synthetic_data_gen/EDITED_PARAGRAPHS.pkl\", \"rb\"))\n REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS = d2c_pipeline.cross_document_claim_augmentation(CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, EDITED_PARAGRAPHS)\n df = d2c_pipeline.construct_claim_doc_label_triples(CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, EDITED_PARAGRAPHS, REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS)\n return df\n \n def get_chunk_and_claims(self, text, chunk_num=3):\n sentences = sent_tokenize(text)\n try:\n num_sentences = len(sentences)\n chunk_size = num_sentences // chunk_num\n chunks = [sentences[i:i+chunk_size] for i in range(0, num_sentences, chunk_size)]\n chunked_text = [' '.join(chunk) for chunk in chunks]\n if len(chunked_text) > chunk_num:\n assert len(chunked_text) == chunk_num + 1\n chunked_text[-2] = chunked_text[-2] + \" \" + chunked_text[-1]\n chunked_text = chunked_text[:-1]\n except:\n chunked_text = 'invalid'\n if chunked_text == 'invalid':\n CLAIMS = ['invalid']\n else:\n CLAIMS = get_response_for_all_chunks(chunked_text)\n return chunked_text, CLAIMS\n \n def decompose_sent_to_facts(self, CLAIM, model=\"gpt-4o-mini\", return_cost=True, is_json=False):\n prompt_for_decompose_adapted = PROMPT_FOR_DECOMPOSE.replace(\"[SENTENCE]\", CLAIM)\n retry = True\n while retry:\n try:\n response, cost = get_GPT_output(prompt_for_decompose_adapted, model=model, return_cost=return_cost, is_json=is_json)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n ATOMIC_FACTS = [item[2:] if '- ' == item[:2] else item for item in response.split(\"\\n\")]\n return ATOMIC_FACTS\n \n def get_atomic_facts_for_all_claims_in_doc(self, CLAIMS, model=\"gpt-4o-mini\"):\n CLAIM_ATOMIC_FACT_DICT = {}\n for CLAIM in CLAIMS:\n atomic_facts = self.decompose_sent_to_facts(CLAIM)\n prompt_for_decompose_adapted = PROMPT_FOR_DECOMPOSE.replace(\"[SENTENCE]\", CLAIM)\n retry = True\n while retry:\n try:\n response = get_GPT_output(prompt_for_decompose_adapted, model=model)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n atomic_facts = [item[2:] if '- ' == item[:2] else item for item in response.split(\"\\n\")]\n CLAIM_ATOMIC_FACT_DICT[CLAIM] = atomic_facts\n return CLAIM_ATOMIC_FACT_DICT\n \n def claim_augmentations(self, CLAIMS):\n merge_idx_sents_dict = get_permutations_of_facts(CLAIMS)\n AUGMENTED_SENT_MAPPING = {}\n for idx, facts in merge_idx_sents_dict.items():\n if len(facts) == 1:\n AUGMENTED_SENT_MAPPING[idx] = facts[0]\n else:\n response = merge_facts_to_sent(facts)\n AUGMENTED_SENT_MAPPING[idx] = response\n self.logging.info(f\"Augmented Claims: {json.dumps(AUGMENTED_SENT_MAPPING, indent=4)}\")\n return AUGMENTED_SENT_MAPPING\n \n def document_claim_augmentation(self, CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, num_chunks=3):\n EDITED_PARAGRAPHS = {}\n if len(CHUNKS) == len(CLAIMS) == len(CLAIM_ATOMIC_FACT_DICT):\n for idx, (chunk, claim) in enumerate(zip(CHUNKS, CLAIMS)):\n atomic_facts = CLAIM_ATOMIC_FACT_DICT[claim]\n sentences = sent_tokenize(chunk)\n neg_paragraphs_for_claim = []\n for i in range(len(sentences)):\n new_paragraph = [sentence for j, sentence in enumerate(sentences) if j != i]\n new_paragraph = ' '.join(new_paragraph)\n atomic_facts_labels = []\n for atomic_fact in atomic_facts:\n label = entailment_check_for_document(\n claim=atomic_fact,\n document=new_paragraph,\n n=num_chunks\n )\n atomic_facts_labels.append(label)\n if 'No' in atomic_facts_labels:\n neg_paragraphs_for_claim.append((new_paragraph, atomic_facts_labels))\n EDITED_PARAGRAPHS[str(idx+1)] = neg_paragraphs_for_claim\n return EDITED_PARAGRAPHS\n \n def cross_document_claim_augmentation(self, CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, EDITED_PARAGRAPHS):\n REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS = {}\n for sent_idx, items in EDITED_PARAGRAPHS.items():\n remaining_doc_chunks_ids = [i for i, chunk in enumerate(CHUNKS) if i != int(sent_idx)-1]\n sent_idx_remain_chunks_and_labels = {}\n for edited_paragraph, atomic_fact_labels in items:\n unsupported_claim = CLAIMS[int(sent_idx)-1]\n corresponding_atomic_facts = CLAIM_ATOMIC_FACT_DICT[unsupported_claim]\n remain_chunks_and_labels = []\n for remaining_doc_chunks_id in remaining_doc_chunks_ids:\n remaining_doc_chunk = CHUNKS[remaining_doc_chunks_id]\n labels = []\n for corresponding_atomic_fact in corresponding_atomic_facts:\n label = entailment_check_for_document(\n claim=corresponding_atomic_fact,\n document=remaining_doc_chunk,\n return_cost=True,\n is_json=False,\n n=3\n )\n labels.append(label)\n remain_chunks_and_labels.append((str(remaining_doc_chunks_id + 1), labels))\n sent_idx_remain_chunks_and_labels[edited_paragraph] = remain_chunks_and_labels\n REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS[sent_idx] = sent_idx_remain_chunks_and_labels\n return REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS\n \n def construct_claim_doc_label_triples(self, CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, EDITED_PARAGRAPHS, REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS):\n new_df = pd.DataFrame(columns=['claim', 'doc', 'label'])\n for claim_idx, claim in enumerate(CLAIMS):\n new_df.loc[len(new_df)] = [claim, CHUNKS[claim_idx], 1]\n for sent_idx, items in EDITED_PARAGRAPHS.items():\n claim = CLAIMS[int(sent_idx)-1]\n corresponding_atomic_facts = CLAIM_ATOMIC_FACT_DICT[claim]\n check_claim_by_rest_para_dict = REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS[sent_idx]\n for edited_paragraph, atomic_fact_labels in items:\n for atomic_idx, atomic_fact in enumerate(corresponding_atomic_facts):\n if atomic_fact_labels[atomic_idx] == 'Yes':\n new_df.loc[len(new_df)] = [atomic_fact, edited_paragraph, 1]\n elif atomic_fact_labels[atomic_idx] == 'No':\n new_df.loc[len(new_df)] = [atomic_fact, edited_paragraph, 0]\n else:\n raise ValueError(\"The atomic fact label is not 'Yes' or 'No'\")\n if 'No' in atomic_fact_labels:\n wrong_fact = str([corresponding_atomic_facts[i] for i in np.where(np.array(atomic_fact_labels) == 'No')[0]])\n new_df.loc[len(new_df)] = [claim, edited_paragraph, 0]\n else:\n new_df.loc[len(new_df)] = [claim, edited_paragraph, 1]\n if len(check_claim_by_rest_para_dict.values()) != 0:\n for item in list(check_claim_by_rest_para_dict.values())[0]:\n para_idx = int(item[0]) - 1\n for atomic_idx, atomic_fact in enumerate(corresponding_atomic_facts):\n if item[1][atomic_idx] == 'Yes':\n new_df.loc[len(new_df)] = [atomic_fact, CHUNKS[para_idx], 1]\n elif item[1][atomic_idx] == 'No':\n new_df.loc[len(new_df)] = [atomic_fact, CHUNKS[para_idx], 0]\n else:\n raise ValueError(\"The atomic fact label is not 'Yes' or 'No\")\n if 'No' in item[1]:\n wrong_fact = str([corresponding_atomic_facts[i] for i in np.where(np.array(item[1]) == 'No')[0]])\n new_df.loc[len(new_df)] = [claim, CHUNKS[para_idx], 0]\n else:\n new_df.loc[len(new_df)] = [claim, CHUNKS[para_idx], 1]\n new_df = new_df[new_df.doc.apply(lambda x: len(x)) >= 500].reset_index(drop=True)\n self.logging.info(f\"Constructed dataframe:\\n{new_df}\")\n return new_df\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--doc_path', type=str, default='synthetic_data_gen/D2C-doc-example.txt', help='path to the document that will be used to construct the training data.')\n parser.add_argument('--no_log', action='store_true', help='Disable logging')\n parser.add_argument(\"--test_path\", type=str)\n parser.add_argument(\"--TestCode\", action='store_true')\n args = parser.parse_args()\n if args.no_log:\n logging.basicConfig(level=logging.CRITICAL)\n else:\n logging.basicConfig(\n level=logging.INFO,\n format='%(message)s',\n handlers=[logging.StreamHandler()]\n )\n httpx_logger = logging.getLogger(\"httpx\")\n httpx_logger.setLevel(logging.WARNING)\n with open(args.doc_path) as file:\n DOCUMENT = file.read()\n d2c_pipeline = D2C_pipeline()\n claim_doc_label_df = d2c_pipeline.construct_data(DOCUMENT)" }, { "task_id": 9, "indent": 2, "script": "\npython synthetic_data_gen/D2C_gen.py\n", "latex_code": "\n\\paragraph{Step 4: Cross-document-claim augmentation} The objective of this step is to perform data augmentation on a $(D_j, c_i)$ pair, where $j \\neq i$. The rationale behind this is that the important information in a document can be conveyed multiple times in various ways. Given that each chunk $D_i$ has an associated summary $c_i$, it is probable that the summary $c_i$ conveys some information that can be indirectly supported by other chunks $D_j$ within the document, even if $D_j$ are not used to generate $c_i$. Therefore, we consider chunks $D_j$, where $j \\neq i$, as more challenging chunks to either support or refute the claim $c_i$ or its atomic facts $\\mathbf{a}_i$.\n\nMore formally, we determine the entailment label for each atomic fact $a_{i, k}$ in $c_i$, using the document chunk $D_j$, where $k \\in \\{1, \\ldots, l\\}$, and $j \\neq i$:\n$$L^{D_j}(a_{i, k}) = \\mathrm{Ent}(D_j, a_{i, k}) \\in \\{0, 1\\}.$$ \nIf $L^{D_j}(a_{i, k}) = 1$ for all $a_{i, k} \\in \\mathbf{a}'_i$, we create tuples $(D_j, \\mathrm{\\texttt{Merge}}(\\mathbf{a}'_i), 1)$. Conversely, if there exists any $a_{i, k} \\in \\mathbf{a}'_i$ such that $L^{D_j}(a_{i, k}) = 0$, we then create tuples $(D_j, \\mathrm{\\texttt{Merge}}(\\mathbf{a}'_i), 0)$.\n", "completion_path": "./synthetic_data_gen/D2C_gen.py", "namespace": "synthetic_data_gen.D2C_gen.D2C_pipeline.cross_document_claim_augmentation", "type": "method", "signature_position": [ 182, 182 ], "body_position": [ 183, 206 ], "ReferenceCode_With_Comments": "\nREMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS = {}\n\n# ---------------------------------------------------------------------------\n# Snippet 1: For each each paragraph, compute the list of indices for document chunks (D_j) that are not associated with the current claim.\n# This implements the LaTeX requirement of considering chunks where j \u2260 i.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nfor sent_idx, items in EDITED_PARAGRAPHS.items():\n remaining_doc_chunks_ids = [i for i, chunk in enumerate(CHUNKS) if i != int(sent_idx)-1]\n# [End Snippet 1]\n\n sent_idx_remain_chunks_and_labels = {}\n\n # ---------------------------------------------------------------------------\n # Snippet 2: For each remaining document chunk (D_j) identified earlier, perform entailment checks\n # for every atomic fact in the current claim using the external API. The result is a list of labels \n # (each 'Yes' or 'No') corresponding to whether each atomic fact is supported by the chunk.\n # This directly implements the LaTeX formulation:\n # L^{D_j}(a_{i, k}) = Ent(D_j, a_{i, k}) \u2208 {0, 1}.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 2]\n for edited_paragraph, atomic_fact_labels in items:\n unsupported_claim = CLAIMS[int(sent_idx)-1]\n corresponding_atomic_facts = CLAIM_ATOMIC_FACT_DICT[unsupported_claim]\n remain_chunks_and_labels = []\n for remaining_doc_chunks_id in remaining_doc_chunks_ids:\n remaining_doc_chunk = CHUNKS[remaining_doc_chunks_id]\n labels = []\n for corresponding_atomic_fact in corresponding_atomic_facts:\n label = entailment_check_for_document(\n claim=corresponding_atomic_fact, \n document=remaining_doc_chunk, \n return_cost=True, \n is_json=False, \n n=3\n )\n labels.append(label)\n remain_chunks_and_labels.append((str(remaining_doc_chunks_id + 1), labels))\n\n sent_idx_remain_chunks_and_labels[edited_paragraph] = remain_chunks_and_labels\n # [End Snippet 2]\n REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS[sent_idx] = sent_idx_remain_chunks_and_labels\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Return the aggregated dictionary containing entailment labels for each \n# claim evaluated against all alternative document chunks. \n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nreturn REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS\n# [End Snippet 3]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The LaTeX description does not specify the indexing scheme used to map sentence identifiers to document chunks and claims, nor does it clarify how to determine which chunks to exclude during cross-document augmentation. The workflow for this process involves associating each claim with its corresponding document chunk using a unique identifier, then systematically excluding the chunk that shares the same identifier as the claim being evaluated. This ensures that only chunks from other documents (i.e., where the identifier differs) are used to assess support or refutation.\n - The method for determining whether a document chunk supports or refutes an atomic fact\u2014referred to as the entailment function\u2014is not described in the LaTeX code. The workflow for this step involves taking a document chunk and an atomic fact, then applying a process to evaluate if the chunk\u2019s content semantically implies the fact, resulting in a binary label (e.g., 1 for support, 0 for refutation).\n - The LaTeX description does not clearly define the role of edited paragraphs in the augmentation process, leading to inconsistent handling compared to the reference implementation. In the intended workflow, each edited paragraph represents a distinct variation or context of the claim, and for each variation, the process evaluates the full set of atomic facts against every document chunk from other documents. This produces a detailed set of labels specific to each variation, reflecting how different chunks support or refute the claim in that context.\n\n - Mismatched Details:\n - The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX.\n", "Missing_details": [ "\n- The prompt for entailment check is defined in ENTAILMENT_CHECK_PROMPT in ./synthetic_data_gen/prompt_utils.py in this repo.\n" ], "Mismatched_details": [ "\n- The function adopts gpt-4o-mini rather than gpt-3.5 as specified in the LaTeX.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - CHUNKS (list[str]): \n A list containing different chunks of the document, where each chunk corresponds \n to a specific section or paragraph.\n - CLAIMS (list[str]): \n A list of claims associated with each document chunk.\n - CLAIM_ATOMIC_FACT_DICT (dict): \n A dictionary mapping each claim to its corresponding list of atomic facts.\n - EDITED_PARAGRAPHS (dict): \n A dictionary where each key is a sentence index and each value is a list of tuples \n containing edited paragraphs and their associated atomic fact labels.\n", "Arguments_list": [ { "name": "CHUNKS", "string": "\n- CHUNKS (list[str]):\n A list containing different chunks of the document, where each chunk corresponds \n to a specific section or paragraph.\n", "dependency": null }, { "name": "CLAIMS", "string": "\n- CLAIMS (list[str]):\n A list of claims associated with each document chunk.\n", "dependency": null }, { "name": "CLAIM_ATOMIC_FACT_DICT", "string": "\n- CLAIM_ATOMIC_FACT_DICT (dict):\n A dictionary mapping each claim to its corresponding list of atomic facts.\n", "dependency": null }, { "name": "EDITED_PARAGRAPHS", "string": "\n- EDITED_PARAGRAPHS (dict):\n A dictionary where each key is a sentence index and each value is a list of tuples \n containing edited paragraphs and their associated atomic fact labels.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n - Intra File Dependencies: \n - None\n\n - Cross File Dependencies: \n - prompt_utils.entailment_check_for_document\n", "intra_file": [], "cross_file": [ "prompt_utils.entailment_check_for_document" ] }, "external_APIs": { "string": "\nExternal APIs:\n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS (dict): \n A nested dictionary mapping each sentence index to edited paragraphs and their corresponding remaining document chunks along with entailment labels for atomic facts.\n Outer Dictionary (Key: sent_idx):\n Keys: The keys of the outer dictionary are strings representing sentence indices (e.g., \"1\", \"2\", \"3\"). These indices likely correspond to the original sentences or claims being analyzed. The index starts from 1.\n Values: The value associated with each sent_idx is another dictionary (the inner dictionary, described below):\n Inner Dictionary (Key: edited_paragraph):\n Keys: The keys of the inner dictionary are the edited paragraphs.\n Values: The value associated with each edited_paragraph is a list of tuples.\n List of Tuples:\n Each tuple contains two elements:\n The ID of remaining chunk (chunks other than the one corresponding to sent_idx), start from 1.\n A list of labels. These labels represent the entailment results (\"Yes\" or \"No\") of checking each atomic fact of claim (corresponding to sent_idx) against the \"remaining chunk\" .\n", "Return_list": [ { "name": "REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS", "string": "\n- REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS (dict): \n A nested dictionary mapping each sentence index to edited paragraphs and their corresponding remaining document chunks along with entailment labels for atomic facts.\n Outer Dictionary (Key: sent_idx):\n Keys: The keys of the outer dictionary are strings representing sentence indices (e.g., \"1\", \"2\", \"3\"). These indices likely correspond to the original sentences or claims being analyzed. The index starts from 1.\n Values: The value associated with each sent_idx is another dictionary (the inner dictionary, described below):\n Inner Dictionary (Key: edited_paragraph):\n Keys: The keys of the inner dictionary are the edited paragraphs.\n Values: The value associated with each edited_paragraph is a list of tuples.\n List of Tuples:\n Each tuple contains two elements:\n The ID of remaining chunk (chunks other than the one corresponding to sent_idx), start from 1.\n A list of labels. These labels represent the entailment results (\"Yes\" or \"No\") of checking each atomic fact of claim (corresponding to sent_idx) against the \"remaining chunk\" .\n", "dependency": null } ] }, "ori_python_file": "import json, pickle\nimport pandas as pd\nimport json\nimport time\nimport logging\nfrom nltk.tokenize import sent_tokenize\nfrom itertools import permutations\nfrom prompt_utils import *\nimport numpy as np\nimport argparse\nATOMIC_FACT_GEN_PROMPT = \"\"\"Document:\n[DOCUMENT]\n\nPlease generate a summary for the document with the following requirements:\n1. The summary should be a fluent and grammatical sentence.\n2. The summary should be no more than 15 words.\n3. The summary should cover information across the document.\nSummary:\"\"\"\nfrom prompt_utils import get_GPT_output, entailment_check_for_document \ndef split_into_chunks(text, chunk_num=3):\n sentences = sent_tokenize(text)\n try:\n num_sentences = len(sentences)\n chunk_size = num_sentences // chunk_num\n chunks = [sentences[i:i+chunk_size] for i in range(0, num_sentences, chunk_size)]\n chunked_text = [' '.join(chunk) for chunk in chunks]\n if len(chunked_text) > chunk_num:\n assert len(chunked_text) == chunk_num + 1\n chunked_text[-2] = chunked_text[-2] + \" \" + chunked_text[-1]\n chunked_text = chunked_text[:-1]\n except:\n return 'invalid'\n return chunked_text\n\ndef get_response_for_all_chunks(chunks):\n responses = []\n for chunk in chunks:\n atomic_fact_gen_prompt_adapted = ATOMIC_FACT_GEN_PROMPT.replace(\"[DOCUMENT]\", chunk)\n retry = True\n while retry:\n try:\n response = get_GPT_output(atomic_fact_gen_prompt_adapted)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n responses.append(response)\n return responses\n\ndef get_permutations_of_facts(facts: list):\n assert type(facts) == list\n facts = {i+1: fact for i, fact in enumerate(facts)}\n all_permutations = []\n for r in range(1, len(facts) + 1):\n all_permutations.extend(permutations(facts, r))\n merge_idx_sents_dict = {}\n for permutation in all_permutations:\n if len(permutation) <= 2:\n permutation_str = [str(s) for s in permutation]\n fact_idx = \"-\".join(permutation_str)\n fact_to_merge = [facts[idx] for idx in permutation]\n merge_idx_sents_dict[fact_idx] = fact_to_merge\n return merge_idx_sents_dict\n\ndef leave_one_sent_out_chunk_construction(chunk, claim, atomic_facts_for_claim):\n sentences = sent_tokenize(chunk)\n neg_paragraphs_for_claim = []\n costs = 0\n for i in range(len(sentences)):\n new_paragraph = [sentence for j, sentence in enumerate(sentences) if j != i]\n new_paragraph = ' '.join(new_paragraph)\n atomic_facts_labels = []\n for atomic_fact in atomic_facts_for_claim:\n label, cost = entailment_check_for_document(claim=atomic_fact, document=new_paragraph, return_cost=True, is_json=False, n=3)\n atomic_facts_labels.append(label)\n costs += cost\n if 'No' in atomic_facts_labels:\n neg_paragraphs_for_claim.append((new_paragraph, atomic_facts_labels))\n return neg_paragraphs_for_claim, costs\n\nclass D2C_pipeline:\n def __init__(self):\n self.logging = logging.getLogger()\n self.total_cost = 0\n self.chunk_num = 3\n \n def construct_data(self, DOCUMENT):\n CHUNKS, CLAIMS = d2c_pipeline.get_chunk_and_claims(DOCUMENT)\n CHUNKS, CLAIMS = pickle.load(open(\"synthetic_data_gen/CHUNKS_CLAIMS.pkl\", \"rb\"))\n CLAIM_ATOMIC_FACT_DICT = d2c_pipeline.get_atomic_facts_for_all_claims_in_doc(CLAIMS)\n CLAIM_ATOMIC_FACT_DICT = pickle.load(open(\"synthetic_data_gen/CLAIM_ATOMIC_FACT_DICT.pkl\", \"rb\"))\n EDITED_PARAGRAPHS = d2c_pipeline.document_claim_augmentation(CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT)\n EDITED_PARAGRAPHS = pickle.load(open(\"synthetic_data_gen/EDITED_PARAGRAPHS.pkl\", \"rb\"))\n REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS = d2c_pipeline.cross_document_claim_augmentation(CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, EDITED_PARAGRAPHS)\n df = d2c_pipeline.construct_claim_doc_label_triples(CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, EDITED_PARAGRAPHS, REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS)\n return df\n \n def get_chunk_and_claims(self, text, chunk_num=3):\n sentences = sent_tokenize(text)\n try:\n num_sentences = len(sentences)\n chunk_size = num_sentences // chunk_num\n chunks = [sentences[i:i+chunk_size] for i in range(0, num_sentences, chunk_size)]\n chunked_text = [' '.join(chunk) for chunk in chunks]\n if len(chunked_text) > chunk_num:\n assert len(chunked_text) == chunk_num + 1\n chunked_text[-2] = chunked_text[-2] + \" \" + chunked_text[-1]\n chunked_text = chunked_text[:-1]\n except:\n chunked_text = 'invalid'\n if chunked_text == 'invalid':\n CLAIMS = ['invalid']\n else:\n CLAIMS = get_response_for_all_chunks(chunked_text)\n return chunked_text, CLAIMS\n \n def decompose_sent_to_facts(self, CLAIM, model=\"gpt-4o-mini\", return_cost=True, is_json=False):\n prompt_for_decompose_adapted = PROMPT_FOR_DECOMPOSE.replace(\"[SENTENCE]\", CLAIM)\n retry = True\n while retry:\n try:\n response, cost = get_GPT_output(prompt_for_decompose_adapted, model=model, return_cost=return_cost, is_json=is_json)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n ATOMIC_FACTS = [item[2:] if '- ' == item[:2] else item for item in response.split(\"\\n\")]\n return ATOMIC_FACTS\n \n def get_atomic_facts_for_all_claims_in_doc(self, CLAIMS, model=\"gpt-4o-mini\"):\n CLAIM_ATOMIC_FACT_DICT = {}\n for CLAIM in CLAIMS:\n atomic_facts = self.decompose_sent_to_facts(CLAIM)\n prompt_for_decompose_adapted = PROMPT_FOR_DECOMPOSE.replace(\"[SENTENCE]\", CLAIM)\n retry = True\n while retry:\n try:\n response = get_GPT_output(prompt_for_decompose_adapted, model=model)\n retry = False\n except Exception as e:\n retry = True\n time.sleep(10)\n atomic_facts = [item[2:] if '- ' == item[:2] else item for item in response.split(\"\\n\")]\n CLAIM_ATOMIC_FACT_DICT[CLAIM] = atomic_facts\n return CLAIM_ATOMIC_FACT_DICT\n \n def claim_augmentations(self, CLAIMS):\n merge_idx_sents_dict = get_permutations_of_facts(CLAIMS)\n AUGMENTED_SENT_MAPPING = {}\n for idx, facts in merge_idx_sents_dict.items():\n if len(facts) == 1:\n AUGMENTED_SENT_MAPPING[idx] = facts[0]\n else:\n response = merge_facts_to_sent(facts)\n AUGMENTED_SENT_MAPPING[idx] = response\n self.logging.info(f\"Augmented Claims: {json.dumps(AUGMENTED_SENT_MAPPING, indent=4)}\")\n return AUGMENTED_SENT_MAPPING\n \n def document_claim_augmentation(self, CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, num_chunks=3):\n EDITED_PARAGRAPHS = {}\n if len(CHUNKS) == len(CLAIMS) == len(CLAIM_ATOMIC_FACT_DICT):\n for idx, (chunk, claim) in enumerate(zip(CHUNKS, CLAIMS)):\n atomic_facts = CLAIM_ATOMIC_FACT_DICT[claim]\n sentences = sent_tokenize(chunk)\n neg_paragraphs_for_claim = []\n for i in range(len(sentences)):\n new_paragraph = [sentence for j, sentence in enumerate(sentences) if j != i]\n new_paragraph = ' '.join(new_paragraph)\n atomic_facts_labels = []\n for atomic_fact in atomic_facts:\n label = entailment_check_for_document(\n claim=atomic_fact,\n document=new_paragraph,\n n=num_chunks\n )\n atomic_facts_labels.append(label)\n if 'No' in atomic_facts_labels:\n neg_paragraphs_for_claim.append((new_paragraph, atomic_facts_labels))\n EDITED_PARAGRAPHS[str(idx+1)] = neg_paragraphs_for_claim\n return EDITED_PARAGRAPHS\n \n def cross_document_claim_augmentation(self, CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, EDITED_PARAGRAPHS):\n REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS = {}\n for sent_idx, items in EDITED_PARAGRAPHS.items():\n remaining_doc_chunks_ids = [i for i, chunk in enumerate(CHUNKS) if i != int(sent_idx)-1]\n sent_idx_remain_chunks_and_labels = {}\n for edited_paragraph, atomic_fact_labels in items:\n unsupported_claim = CLAIMS[int(sent_idx)-1]\n corresponding_atomic_facts = CLAIM_ATOMIC_FACT_DICT[unsupported_claim]\n remain_chunks_and_labels = []\n for remaining_doc_chunks_id in remaining_doc_chunks_ids:\n remaining_doc_chunk = CHUNKS[remaining_doc_chunks_id]\n labels = []\n for corresponding_atomic_fact in corresponding_atomic_facts:\n label = entailment_check_for_document(\n claim=corresponding_atomic_fact,\n document=remaining_doc_chunk,\n return_cost=True,\n is_json=False,\n n=3\n )\n labels.append(label)\n remain_chunks_and_labels.append((str(remaining_doc_chunks_id + 1), labels))\n sent_idx_remain_chunks_and_labels[edited_paragraph] = remain_chunks_and_labels\n REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS[sent_idx] = sent_idx_remain_chunks_and_labels\n return REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS\n \n def construct_claim_doc_label_triples(self, CHUNKS, CLAIMS, CLAIM_ATOMIC_FACT_DICT, EDITED_PARAGRAPHS, REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS):\n new_df = pd.DataFrame(columns=['claim', 'doc', 'label'])\n for claim_idx, claim in enumerate(CLAIMS):\n new_df.loc[len(new_df)] = [claim, CHUNKS[claim_idx], 1]\n for sent_idx, items in EDITED_PARAGRAPHS.items():\n claim = CLAIMS[int(sent_idx)-1]\n corresponding_atomic_facts = CLAIM_ATOMIC_FACT_DICT[claim]\n check_claim_by_rest_para_dict = REMAIN_CHUNKS_LABELS_FOR_ATOMIC_FACTS[sent_idx]\n for edited_paragraph, atomic_fact_labels in items:\n for atomic_idx, atomic_fact in enumerate(corresponding_atomic_facts):\n if atomic_fact_labels[atomic_idx] == 'Yes':\n new_df.loc[len(new_df)] = [atomic_fact, edited_paragraph, 1]\n elif atomic_fact_labels[atomic_idx] == 'No':\n new_df.loc[len(new_df)] = [atomic_fact, edited_paragraph, 0]\n else:\n raise ValueError(\"The atomic fact label is not 'Yes' or 'No'\")\n if 'No' in atomic_fact_labels:\n wrong_fact = str([corresponding_atomic_facts[i] for i in np.where(np.array(atomic_fact_labels) == 'No')[0]])\n new_df.loc[len(new_df)] = [claim, edited_paragraph, 0]\n else:\n new_df.loc[len(new_df)] = [claim, edited_paragraph, 1]\n if len(check_claim_by_rest_para_dict.values()) != 0:\n for item in list(check_claim_by_rest_para_dict.values())[0]:\n para_idx = int(item[0]) - 1\n for atomic_idx, atomic_fact in enumerate(corresponding_atomic_facts):\n if item[1][atomic_idx] == 'Yes':\n new_df.loc[len(new_df)] = [atomic_fact, CHUNKS[para_idx], 1]\n elif item[1][atomic_idx] == 'No':\n new_df.loc[len(new_df)] = [atomic_fact, CHUNKS[para_idx], 0]\n else:\n raise ValueError(\"The atomic fact label is not 'Yes' or 'No\")\n if 'No' in item[1]:\n wrong_fact = str([corresponding_atomic_facts[i] for i in np.where(np.array(item[1]) == 'No')[0]])\n new_df.loc[len(new_df)] = [claim, CHUNKS[para_idx], 0]\n else:\n new_df.loc[len(new_df)] = [claim, CHUNKS[para_idx], 1]\n new_df = new_df[new_df.doc.apply(lambda x: len(x)) >= 500].reset_index(drop=True)\n self.logging.info(f\"Constructed dataframe:\\n{new_df}\")\n return new_df\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--doc_path', type=str, default='synthetic_data_gen/D2C-doc-example.txt', help='path to the document that will be used to construct the training data.')\n parser.add_argument('--no_log', action='store_true', help='Disable logging')\n parser.add_argument(\"--test_path\", type=str)\n parser.add_argument(\"--TestCode\", action='store_true')\n args = parser.parse_args()\n if args.no_log:\n logging.basicConfig(level=logging.CRITICAL)\n else:\n logging.basicConfig(\n level=logging.INFO,\n format='%(message)s',\n handlers=[logging.StreamHandler()]\n )\n httpx_logger = logging.getLogger(\"httpx\")\n httpx_logger.setLevel(logging.WARNING)\n with open(args.doc_path) as file:\n DOCUMENT = file.read()\n d2c_pipeline = D2C_pipeline()\n claim_doc_label_df = d2c_pipeline.construct_data(DOCUMENT)" } ] }, { "paper_id": 19, "paper_details": { "title": "Nearest Neighbor Normalization Improves Multimodal Retrieval", "url": "https://arxiv.org/abs/2410.24114" }, "enviorment_name": "nnn", "repo_original_url": "https://github.com/multimodal-interpretability/nnn", "project_path": "Benchmark/19-nnn-main/nnn-main", "file_organization": "\nnnn-main/\n assets/\n nnn_teaser.png\n docs/\n conf.py\n docs/\n source/\n modules.rst\n nnn.rst\n index.rst\n make.bat\n Makefile\n source/\n modules.rst\n nnn.rst\n _static/\n custom.css\n env.sh\n examples/\n nnn_simple_example.py\n LICENSE\n nnn/\n base_ranker.py\n base_retriever.py\n dn_ranker.py\n faiss_cpu_retriever.py\n faiss_gpu_retriever.py\n __init__.py\n nnn_ranker.py\n nnn_retriever.py\n ranker.py\n retriever.py\n nnn_clip_flickr_30k.py\n pyproject.toml\n pytest.ini\n README.md\n tests/\n test_nnn.py\n", "latex_code_path": "Benchmark/19-nnn-main/arXiv-2410.24114v1", "task_details": [ { "task_id": 0, "indent": 2, "script": "\npython nnn_clip_flickr_30k.py\n", "latex_code": "\n\\section{Nearest Neighbor Normalization}\n\\label{sec:method}\n\nRetrieval models compute a match score $s(q, r)$ between a query $q$ and database retrieval candidate $r$, and return the highest-scoring candidates. In the case of contrastive multimodal models such as CLIP, this score is typically the cosine similarity between image and text embeddings \\citep{radford2021learning}. Figure \\ref{fig:matching} shows how the hubness problem \\cite{radovanovic2010hubs} manifests as a failure mode of contrastive text-to-image retrieval. Some images are simply preferred by contrastive models over other images: they have high cosine similarity with a wide array of query captions. \n\nTo correct for bias towards hubs in image-text retrieval, we propose \\nnd, an approach that estimates bias for each retrieval candidate using a database of reference queries, $\\mathcal{D}$. The bias is then applied as an additive correction to the original match score, then used for retrieval. Specifically, given a contrastive retrieval score $s(q, r) = q \\cdot r$, we define the bias $b(r)$ for a retrieval candidate $r$ as a constant multiple ($\\alpha$) of the mean of $s(q_1, r), s(q_2, r), \\dots, s(q_k, r)$, where $\\{q_1, \\dots, q_k\\} = \\mathcal{D}_{\\text{top } k}(r)$ are the $k$ queries from the reference query dataset that have the highest similarity score $s(q_i, r)$ with $r$. Namely, if we define the operator $\\text{argmax}^k$ to denote the $k$ arguments for the which a function attains its $k$ maximum values, then we have $D_{\\text{top } k}(r) = \\underset{q \\in \\mathcal{D}}{\\arg \\max^k_ s(q, r)}$, and our bias is computed as:\n\\begin{equation}\n\\label{eqn:bias}\nb(r) = \\alpha \\cdot \\frac{1}{k} \\sum_{q_j \\in D_{\\text{top }k}(r)} s(q_j, r).\\end{equation}\n\n\\nnd\\ uses the nearest $k$ query embeddings to differentiate similar objects, capturing fine-grained distinctions between retrieval candidates. \n\nEach retrieval candidate has a constant bias score, so these scores can be computed offline and cached. \nThe debiased retrieval score can then be computed by subtracting the estimated bias from the original score:\n\\begin{equation}\n\\label{eqn:debias}\ns_{\\mathcal{D}}(q,r) = s(q, r) - b(r)\n.\\end{equation}\n\n\nWhen using vector retrieval to compute match scores, bias scores are computed in sublinear time and add a constant factor to retrieval runtime; see Section~\\ref{sec:retrieval_perf} for further discussion. \n\n\\begin{figure}[t!]\n \\centering\n \\includegraphics[width=\\linewidth]{figures/nnn_fig2.png}\n \\vspace{-6mm}\n \\caption{\\textbf{Distribution of COCO captions matched to each image during image retrieval.} A base CLIP model contains many hubs that match over 100 captions, while the distribution after \\nnd\\ shows fewer hubs, on par with finetuning on COCO.}\n \\vspace{-5mm}\n \\label{fig:matching}\n\\end{figure}\n", "completion_path": "./nnn/nnn_retriever.py", "namespace": "KEnnnN.nnn_retriever.NNNRetriever.compute_alignment_means", "type": "method", "signature_position": [ 13, 15 ], "body_position": [ 16, 28 ], "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The LaTeX description specifies using the \"top-k similarity scores\" but does not address whether these scores are sorted. The reference code uses `torch.topk` with default sorted outputs (`sorted=True`)\n\n - Mismatched Details:\n - The LaTeX description defines the bias term as involving a constant multiplier (\\(\\alpha\\)) applied to the mean of the top-k similarity scores, suggesting that this scaling factor is a key component of the bias calculation. However, the reference implementation computes only the mean of the top-k scores without applying any such multiplier within the described function.\n\n", "Missing_details": [ "\n- The LaTeX description specifies using the \"top-k similarity scores\" but does not address whether these scores are sorted. The reference code uses `torch.topk` with default sorted outputs (`sorted=True`)\n" ], "Mismatched_details": [ "\n- The LaTeX description defines the bias term as involving a constant multiplier (\\(\\alpha\\)) applied to the mean of the top-k similarity scores, suggesting that this scaling factor is a key component of the bias calculation. However, the reference implementation computes only the mean of the top-k scores without applying any such multiplier within the described function.\n" ] }, "ReferenceCode_With_Comments": "\nalignment_means = []\n\nfor i in tqdm(range(0, retrieval_embeds.shape[0], batch_size)):\n \n # -----------------------------------------------------------------------\n # Snippet 1: Compute the pairwise similarity scores between the current batch\n # of retrieval embeddings and all reference embeddings using the Einstein\n # summation convention. This step implements the calculation of s(q, r) as\n # described in the match score definition.\n # -----------------------------------------------------------------------\n # [Begin Snippet 1]\n batch_reference_similarity_scores = torch.einsum(\n \"ik,jk->ij\", retrieval_embeds[i : i + batch_size, :], reference_embeds\n )\n # [End Snippet 1]\n\n # -----------------------------------------------------------------------\n # Snippet 2: Identify the top-k similarity scores for each retrieval embedding\n # within the current batch. Selecting the top-k scores is essential for\n # estimating the bias based on the most similar reference queries.\n # -----------------------------------------------------------------------\n # [Begin Snippet 2]\n top_k_reference_scores = torch.topk(\n batch_reference_similarity_scores, alternate_ks, dim=1\n )\n # [End Snippet 2]\n\n # -----------------------------------------------------------------------\n # Snippet 3: Calculate the mean of the top-k similarity scores for each retrieval\n # embedding and append the results to the alignment_means list. This averaging\n # process aligns with the bias computation formula, providing an estimate of\n # each retrieval candidate's propensity to be a hub.\n # -----------------------------------------------------------------------\n # [Begin Snippet 3]\n alignment_means.append(\n torch.mean(top_k_reference_scores.values, dim=1, keepdim=True)\n )\n # [End Snippet 3]\n\nmean_align_score = (torch.cat(alignment_means)).cpu().numpy() \n\nreturn mean_align_score\n", "Arguments": { "string": "\nInput Variables:\n - retrieval_embeds (torch.Tensor, dtype=torch.float32, shape=[num_retrievals, embed_dim]): \n Tensor containing the embeddings of the retrieval candidates for which bias scores are to be computed.\n - reference_embeds (torch.Tensor, dtype=torch.float32, shape=[num_references, embed_dim]): \n Tensor containing the embeddings of reference queries used to estimate the bias for each retrieval candidate.\n - alternate_ks (int): \n The number of top similarity scores to consider when computing the mean alignment score for each retrieval candidate.\n - batch_size (int): \n The number of retrieval embeddings to process in each batch, facilitating efficient computation and memory management.\n", "Arguments_list": [ { "name": "retrieval_embeds", "string": "\n- retrieval_embeds (torch.Tensor, dtype=torch.float32, shape=[num_retrievals, embed_dim]): \n Tensor containing the embeddings of the retrieval candidates for which bias scores are to be computed.\n", "dependency": null }, { "name": "reference_embeds", "string": "\n- reference_embeds (torch.Tensor, dtype=torch.float32, shape=[num_references, embed_dim]):\n Tensor containing the embeddings of reference queries used to estimate the bias for each retrieval candidate.\n", "dependency": null }, { "name": "alternate_ks", "string": "\n- alternate_ks (int):\n The number of top similarity scores to consider when computing the mean alignment score for each retrieval candidate.\n", "dependency": null }, { "name": "batch_size", "string": "\n- batch_size (int):\n The number of retrieval embeddings to process in each batch, facilitating efficient computation and memory management.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n - Intra File Dependencies: \n - None\n \n - Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.einsum\n - torch.topk\n - torch.mean \n - torch.cat\n", "list": [ "torch.einsum", "torch.topk", "torch.mean", "torch.cat" ] }, "Return": { "Return_String": "\nOutput Variables:\n - mean_align_score (numpy.ndarray, shape=[num_retrievals, 1]): \n Numpy array containing the mean of the top-k similarity scores for each retrieval candidate, representing the estimated bias.\n", "Return_list": [ { "name": "mean_align_score", "string": "\n- mean_align_score (numpy.ndarray, shape=[num_retrievals, 1]): \n Numpy array containing the mean of the top-k similarity scores for each retrieval candidate, representing the estimated bias.\n", "dependency": null } ] }, "ori_python_file": "from .retriever import Retriever\nimport torch\nfrom tqdm import tqdm\n\nclass NNNRetriever(Retriever):\n def __init__(self, embeds_size: int, use_gpu: bool = False, gpu_id: int = -1):\n self.embeds_size = embeds_size\n self.use_gpu = use_gpu\n self.gpu_id = gpu_id\n if self.use_gpu and self.gpu_id == -1:\n raise Exception(\"GPU flag set but no GPU device given!\")\n \n def compute_alignment_means(\n self, retrieval_embeds, reference_embeds, alternate_ks, batch_size\n ):\n alignment_means = []\n for i in tqdm(range(0, retrieval_embeds.shape[0], batch_size)):\n batch_reference_similarity_scores = torch.einsum(\n \"ik,jk->ij\", retrieval_embeds[i : i + batch_size, :], reference_embeds\n )\n top_k_reference_scores = torch.topk(\n batch_reference_similarity_scores, alternate_ks, dim=1\n )\n alignment_means.append(\n torch.mean(top_k_reference_scores.values, dim=1, keepdim=True)\n )\n mean_align_score = (torch.cat(alignment_means)).cpu().numpy()\n return mean_align_score\n \n def setup_retriever(\n self, retrieval_embeds, reference_embeds, alternate_ks, batch_size\n ):\n alignment_means = self.compute_alignment_means(\n retrieval_embeds, reference_embeds, alternate_ks, batch_size\n )\n return alignment_means\n \n def retrieve(\n self,\n retrieval_embeds,\n batch_query,\n top_k,\n alternate_weight,\n alignment_means,\n batch_size,\n ):\n distances = []\n indices = []\n distances = []\n indices = []\n for i in tqdm(range(0, batch_query.shape[0], batch_size)):\n batch_similarity_scores = (\n torch.einsum(\n \"ik,jk->ij\", batch_query[i : i + batch_size, :], retrieval_embeds\n )\n - alternate_weight * alignment_means.T\n )\n top_k_results = torch.topk(batch_similarity_scores, top_k, dim=1)\n distances.append(top_k_results.values)\n indices.append(top_k_results.indices)\n distances = torch.vstack(distances).cpu().numpy()\n indices = torch.vstack(indices).cpu().numpy()\n return distances, indices" }, { "task_id": 1, "indent": 2, "script": "\npython nnn_clip_flickr_30k.py\n", "latex_code": "\n\\section{Nearest Neighbor Normalization}\n\\label{sec:method}\n\nRetrieval models compute a match score $s(q, r)$ between a query $q$ and database retrieval candidate $r$, and return the highest-scoring candidates. In the case of contrastive multimodal models such as CLIP, this score is typically the cosine similarity between image and text embeddings \\citep{radford2021learning}. Figure \\ref{fig:matching} shows how the hubness problem \\cite{radovanovic2010hubs} manifests as a failure mode of contrastive text-to-image retrieval. Some images are simply preferred by contrastive models over other images: they have high cosine similarity with a wide array of query captions. \n\nTo correct for bias towards hubs in image-text retrieval, we propose \\nnd, an approach that estimates bias for each retrieval candidate using a database of reference queries, $\\mathcal{D}$. The bias is then applied as an additive correction to the original match score, then used for retrieval. Specifically, given a contrastive retrieval score $s(q, r) = q \\cdot r$, we define the bias $b(r)$ for a retrieval candidate $r$ as a constant multiple ($\\alpha$) of the mean of $s(q_1, r), s(q_2, r), \\dots, s(q_k, r)$, where $\\{q_1, \\dots, q_k\\} = \\mathcal{D}_{\\text{top } k}(r)$ are the $k$ queries from the reference query dataset that have the highest similarity score $s(q_i, r)$ with $r$. Namely, if we define the operator $\\text{argmax}^k$ to denote the $k$ arguments for the which a function attains its $k$ maximum values, then we have $D_{\\text{top } k}(r) = \\underset{q \\in \\mathcal{D}}{\\arg \\max^k_ s(q, r)}$, and our bias is computed as:\n\\begin{equation}\n\\label{eqn:bias}\nb(r) = \\alpha \\cdot \\frac{1}{k} \\sum_{q_j \\in D_{\\text{top }k}(r)} s(q_j, r).\\end{equation}\n\n\\nnd\\ uses the nearest $k$ query embeddings to differentiate similar objects, capturing fine-grained distinctions between retrieval candidates. \n\nEach retrieval candidate has a constant bias score, so these scores can be computed offline and cached. \nThe debiased retrieval score can then be computed by subtracting the estimated bias from the original score:\n\\begin{equation}\n\\label{eqn:debias}\ns_{\\mathcal{D}}(q,r) = s(q, r) - b(r)\n.\\end{equation}\n\n\nWhen using vector retrieval to compute match scores, bias scores are computed in sublinear time and add a constant factor to retrieval runtime; see Section~\\ref{sec:retrieval_perf} for further discussion. \n\n\\begin{figure}[t!]\n \\centering\n \\includegraphics[width=\\linewidth]{figures/nnn_fig2.png}\n \\vspace{-6mm}\n \\caption{\\textbf{Distribution of COCO captions matched to each image during image retrieval.} A base CLIP model contains many hubs that match over 100 captions, while the distribution after \\nnd\\ shows fewer hubs, on par with finetuning on COCO.}\n \\vspace{-5mm}\n \\label{fig:matching}\n\\end{figure}\n", "completion_path": "./nnn/nnn_retriever.py", "namespace": "KEnnnN.nnn_retriever.NNNRetriever.retrieve", "type": "method", "signature_position": [ 38, 46 ], "body_position": [ 47, 63 ], "ReferenceCode_With_Comments": "\ndistances = []\nindices = []\n\ndistances = []\nindices = []\n\nfor i in tqdm(range(0, batch_query.shape[0], batch_size)):\n \n # -----------------------------------------------------------------------\n # Snippet 1: Compute the pairwise similarity scores between the current batch of\n # query embeddings and all retrieval embeddings using Einstein summation.\n # Subsequently, adjust these scores by subtracting the product of alternate_weight\n # and the precomputed alignment_means to correct for bias.\n # This adjustment aligns with Equation (2) from the LaTeX, implementing the debiased\n # retrieval score computation.\n # -----------------------------------------------------------------------\n # [Begin Snippet 1]\n batch_similarity_scores = (\n torch.einsum(\n \"ik,jk->ij\", batch_query[i : i + batch_size, :], retrieval_embeds\n )\n - alternate_weight * alignment_means.T\n )\n # [End Snippet 1]\n\n # -----------------------------------------------------------------------\n # Snippet 2: Identify the top-k retrieval candidates with the highest adjusted\n # similarity scores for each query in the current batch. Selecting the top-k\n # ensures that only the most relevant retrievals are considered for each query.\n # -----------------------------------------------------------------------\n # [Begin Snippet 2]\n top_k_results = torch.topk(batch_similarity_scores, top_k, dim=1)\n # [End Snippet 2]\n\n distances.append(top_k_results.values)\n indices.append(top_k_results.indices)\n\ndistances = torch.vstack(distances).cpu().numpy()\nindices = torch.vstack(indices).cpu().numpy()\nreturn distances, indices\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - None\n \n Mismatched Details:\n - None\n", "Missing_details": [], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - retrieval_embeds (torch.Tensor, dtype=torch.float32, shape=[num_retrievals, embed_dim]):\n Tensor containing the embeddings of retrieval candidates against which queries are matched.\n - batch_query (torch.Tensor, dtype=torch.float32, shape=[batch_size, embed_dim]):\n Tensor containing the embeddings of queries for the current batch to be processed.\n - top_k (int):\n The number of top retrieval candidates to return for each query based on the adjusted similarity scores.\n - alternate_weight (float):\n Scaling factor (\u03b1) applied to the alignment_means (bias) when adjusting the similarity scores.\n - alignment_means (numpy.ndarray, shape=[num_retrievals, 1]):\n Numpy array containing the precomputed mean alignment scores (bias) for each retrieval candidate.\n - batch_size (int):\n The number of queries to process in each iteration, facilitating efficient computation and memory management.\n", "Arguments_list": [ { "name": "retrieval_embeds", "string": "\n- retrieval_embeds (torch.Tensor, dtype=torch.float32, shape=[num_retrievals, embed_dim]):\n Tensor containing the embeddings of retrieval candidates against which queries are matched.\n", "dependency": null }, { "name": "batch_query", "string": "\n- batch_query (torch.Tensor, dtype=torch.float32, shape=[batch_size, embed_dim]):\n Tensor containing the embeddings of queries for the current batch to be processed.\n", "dependency": null }, { "name": "top_k", "string": "\n- top_k (int):\n The number of top retrieval candidates to return for each query based on the adjusted similarity scores.\n", "dependency": null }, { "name": "alternate_weight", "string": "\n- alternate_weight (float):\n Scaling factor (\u03b1) applied to the alignment_means (bias) when adjusting the similarity scores.\n", "dependency": null }, { "name": "alignment_means", "string": "\n- alignment_means (numpy.ndarray, shape=[num_retrievals, 1]):\n Numpy array containing the precomputed mean alignment scores (bias) for each retrieval candidate.\n", "dependency": null }, { "name": "batch_size", "string": "\n- batch_size (int):\n The number of queries to process in each iteration, facilitating efficient computation and memory management.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra File Dependencies:\n - None\n \n - Cross File Dependencies:\n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.einsum\n - torch.topk\n - torch.vstack\n", "list": [ "torch.einsum", "torch.topk", "torch.vstack" ] }, "Return": { "Return_String": "\nOutput Variables:\n - distances (numpy.ndarray, shape=[batch_query_size, top_k]):\n Array of the top-k adjusted similarity scores for each query in the batch.\n - indices (numpy.ndarray, shape=[batch_query_size, top_k]):\n Array of indices corresponding to the top-k retrieval candidates for each query.\n", "Return_list": [ { "name": "distances", "string": "\n- distances (numpy.ndarray, shape=[batch_query_size, top_k]):\n Array of the top-k adjusted similarity scores for each query in the batch.\n", "dependency": null }, { "name": "indices", "string": "\n- indices (numpy.ndarray, shape=[batch_query_size, top_k]):\n Array of indices corresponding to the top-k retrieval candidates for each query.\n", "dependency": null } ] }, "ori_python_file": "from .retriever import Retriever\nimport torch\nfrom tqdm import tqdm\n\nclass NNNRetriever(Retriever):\n def __init__(self, embeds_size: int, use_gpu: bool = False, gpu_id: int = -1):\n self.embeds_size = embeds_size\n self.use_gpu = use_gpu\n self.gpu_id = gpu_id\n if self.use_gpu and self.gpu_id == -1:\n raise Exception(\"GPU flag set but no GPU device given!\")\n \n def compute_alignment_means(\n self, retrieval_embeds, reference_embeds, alternate_ks, batch_size\n ):\n alignment_means = []\n for i in tqdm(range(0, retrieval_embeds.shape[0], batch_size)):\n batch_reference_similarity_scores = torch.einsum(\n \"ik,jk->ij\", retrieval_embeds[i : i + batch_size, :], reference_embeds\n )\n top_k_reference_scores = torch.topk(\n batch_reference_similarity_scores, alternate_ks, dim=1\n )\n alignment_means.append(\n torch.mean(top_k_reference_scores.values, dim=1, keepdim=True)\n )\n mean_align_score = (torch.cat(alignment_means)).cpu().numpy()\n return mean_align_score\n \n def setup_retriever(\n self, retrieval_embeds, reference_embeds, alternate_ks, batch_size\n ):\n alignment_means = self.compute_alignment_means(\n retrieval_embeds, reference_embeds, alternate_ks, batch_size\n )\n return alignment_means\n \n def retrieve(\n self,\n retrieval_embeds,\n batch_query,\n top_k,\n alternate_weight,\n alignment_means,\n batch_size,\n ):\n distances = []\n indices = []\n distances = []\n indices = []\n for i in tqdm(range(0, batch_query.shape[0], batch_size)):\n batch_similarity_scores = (\n torch.einsum(\n \"ik,jk->ij\", batch_query[i : i + batch_size, :], retrieval_embeds\n )\n - alternate_weight * alignment_means.T\n )\n top_k_results = torch.topk(batch_similarity_scores, top_k, dim=1)\n distances.append(top_k_results.values)\n indices.append(top_k_results.indices)\n distances = torch.vstack(distances).cpu().numpy()\n indices = torch.vstack(indices).cpu().numpy()\n return distances, indices" } ] }, { "paper_id": 20, "paper_details": { "title": "Neuron-Level Knowledge Attribution in Large Language Models", "url": "https://arxiv.org/abs/2312.12141" }, "enviorment_name": "neuron", "repo_original_url": "https://github.com/zepingyu0512/neuron-attribution", "project_path": "Benchmark/20-neuron-attribution-main/neuron-attribution-main", "file_organization": "\nneuron-attribution-main/\n environment.yml\n modeling_gpt2.py\n modeling_llama.py\n README.md\n", "latex_code_path": "Benchmark/20-neuron-attribution-main/arXiv-2312.12141v4", "task_details": [ { "task_id": 0, "indent": 1, "script": "\npython GPT2_view_knowledge.py\n", "latex_code": "\n\\subsection{Distribution Change Caused by Neurons}\nThe final vector $h_T^L$ has important information for predicting the final token. As it is computed by a direct sum of various neuron-level vectors, the relevant information for making the final prediction must be stored in one or many neurons. The final vector $h_T^l$ can be regarded as the sum of one neuron $v$ and another vector $x=h_T^l-v$. We consider the probability change $p(w|x+v)-p(w|x)$ caused by $v$ for prediction token $w$. \nWe aim to explore which components of $v$ are significant for amplifying the probability change. This allows us to develop static methods for locating crucial neurons.\n\nAs the probability change is nonlinear, analyzing the exact contribution of neuron $v$ is challenging. For a more concise analysis, we term the score $e_w \\cdot x$ vector $x$'s bs-value (before-softmax value) on token $w$, where $e_w$ is the $wth$ row of the unembedded matrix $E_u$. A token's bs-value directly corresponds to the probability of this token. Bs-values of all vocabulary tokens on vector $x$ are:\n\\begin{equation}\n bs(x) = [bs^x_1, bs^x_2, ..., bs^x_w, ..., bs^x_B]\n\\end{equation}\nFor vector $x$, if $bs^x_w$ is the largest among all the bs-values, the probability of word $w$ will also be the highest. The probability of each token for $x$ and $x+v$ can be computed by all the bs-values:\n\\begin{equation}\np (w|x) = \\frac{exp(bs^x_w)}{exp(bs^x_1) + ... + exp(bs^x_B) }\n\\end{equation}\n\\begin{equation}\np (w|x+v) = \\frac{exp(bs^{x+v}_w)}{exp(bs^{x+v}_1) + ... + exp(bs^{x+v}_B) }\n\\end{equation}\nwhere bs-value $bs^{x+v}_w$ is equal to $bs^x_w + bs^v_w$:\n\\begin{equation}\nbs(x+v) = bs(x)+bs(v)\n\\end{equation}\n", "completion_path": "./GPT2_view_knowledge.py", "namespace": "GPT2_view_knowledge.get_bsvalues", "type": "function", "signature_position": [ 39, 39 ], "body_position": [ 40, 43 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Compute the mean of the input vector across the last dimension to obtain the \n# central tendency. This aligns with the statistical analysis described in the LaTeX, \n# facilitating the normalization process.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nE = torch.mean(vector, -1)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Normalize the input vector by subtracting the mean and scaling by final_var.\n# This normalization is then adjusted using the layer normalization weights from the model.\n# This step prepares the vector for accurate bs-value computation as outlined in the LaTeX.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nvector_ln = (vector - E.unsqueeze(-1)) / final_var * model.transformer.ln_f.weight.data\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Pass the normalized vector through the language model head to obtain the \n# bs-values. These bs-values represent the before-softmax scores for each token, which are \n# essential for calculating the probability distribution over the vocabulary.\n# Return the computed bs-values.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nvector_bsvalues = model.lm_head(vector_ln).data\n\nreturn vector_bsvalues\n# [End Snippet 3]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX description does not specify the initial step of centering the input vector by subtracting its mean before further processing. In the workflow, this step involves calculating the average value of the vector\u2019s components along its relevant dimension and then subtracting this average from each component.\n - The LaTeX code omits the explicit application of layer normalization weights as a distinct scaling operation after normalizing the vector. The workflow for this step involves taking the normalized vector, then multiplying it element-wise by a set of learned weights derived from the model\u2019s final layer normalization process. The layer normalization should use only the weight, not the full normalization (which includes the bias).\n\n Mismatched Details:\n - None\n", "Missing_details": [ "\n- The LaTeX description does not specify the initial step of centering the input vector by subtracting its mean before further processing. In the workflow, this step involves calculating the average value of the vector\u2019s components along its relevant dimension and then subtracting this average from each component.\n", "\n- The LaTeX code omits the explicit application of layer normalization weights as a distinct scaling operation after normalizing the vector. The workflow for this step involves taking the normalized vector, then multiplying it element-wise by a set of learned weights derived from the model\u2019s final layer normalization process. The layer normalization should use only the weight, not the full normalization (which includes the bias).\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - vector (torch.Tensor, dtype=torch.float32, shape=[batch_size, ..., embedding_dim]): \n Tensor containing the neuron-level vectors for which bs-values are to be computed. Each vector \n represents the aggregated information from various neurons contributing to the final token prediction.\n - model (An object of modeling_gpt2.GPT2LMHeadModel): \n The language model instance that includes the transformer layers and the language model head \n (`lm_head`) necessary for computing bs-values. It provides access to layer normalization weights \n and the final linear layer used in generating the bs-values.\n - final_var (float): \n A scaling factor used in the normalization process of the input vector. It controls the \n intensity of the normalization applied to the vector before computing the bs-values.\n", "Arguments_list": [ { "name": "vector", "string": "\n- vector (torch.Tensor, dtype=torch.float32, shape=[batch_size, ..., embedding_dim]): \n Tensor containing the neuron-level vectors for which bs-values are to be computed. Each vector \n represents the aggregated information from various neurons contributing to the final token prediction.\n", "dependency": null }, { "name": "model", "string": "\n- model (An object of modeling_gpt2.GPT2LMHeadModel):\n The language model instance that includes the transformer layers and the language model head \n (`lm_head`) necessary for computing bs-values. It provides access to layer normalization weights \n and the final linear layer used in generating the bs-values.\n", "dependency": "modeling_gpt2.GPT2LMHeadModel" }, { "name": "final_var", "string": "\n- final_var (float):\n A scaling factor used in the normalization process of the input vector. It controls the \n intensity of the normalization applied to the vector before computing the bs-values.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies: \n - Intra File Dependencies: \n - None\n\n - Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.mean\n", "list": [ "torch.mean" ] }, "Return": { "Return_String": "\nOutput Variables:\n - vector_bsvalues (torch.Tensor, dtype=torch.float32, shape=[vocab_size]): \n Tensor containing the computed bs-values for each token in the vocabulary. These values are used \n to determine the probability distribution over tokens for prediction purposes.\n", "Return_list": [ { "name": "vector_bsvalues", "string": "\n- vector_bsvalues (torch.Tensor, dtype=torch.float32, shape=[vocab_size]): \n Tensor containing the computed bs-values for each token in the vocabulary. These values are used \n to determine the probability distribution over tokens for prediction purposes.\n", "dependency": null } ] }, "ori_python_file": "import torch\nfrom collections import Counter\nfrom transformers import GPT2Tokenizer\nfrom modeling_gpt2 import GPT2LMHeadModel\nLAYER_NUM = 36\nHEAD_NUM = 20\nHEAD_DIM = 64\nHIDDEN_DIM = HEAD_NUM * HEAD_DIM\ntorch.set_default_device(\"cuda\")\n\ndef transfer_output(model_output):\n all_pos_layer_input = []\n all_pos_attn_output = []\n all_pos_residual_output = []\n all_pos_ffn_output = []\n all_pos_layer_output = []\n all_last_attn_subvalues = []\n all_pos_coefficient_scores = []\n all_attn_scores = []\n for layer_i in range(LAYER_NUM):\n cur_layer_input = model_output[layer_i][0]\n cur_attn_output = model_output[layer_i][1]\n cur_residual_output = model_output[layer_i][2]\n cur_ffn_output = model_output[layer_i][3]\n cur_layer_output = model_output[layer_i][4]\n cur_last_attn_subvalues = model_output[layer_i][5]\n cur_coefficient_scores = model_output[layer_i][6]\n cur_attn_weights = model_output[layer_i][7]\n all_pos_layer_input.append(cur_layer_input[0].tolist())\n all_pos_attn_output.append(cur_attn_output[0].tolist())\n all_pos_residual_output.append(cur_residual_output[0].tolist())\n all_pos_ffn_output.append(cur_ffn_output[0].tolist())\n all_pos_layer_output.append(cur_layer_output[0].tolist())\n all_last_attn_subvalues.append(cur_last_attn_subvalues[0].tolist())\n all_pos_coefficient_scores.append(cur_coefficient_scores[0].tolist())\n all_attn_scores.append(cur_attn_weights)\n return all_pos_layer_input, all_pos_attn_output, all_pos_residual_output, all_pos_ffn_output, all_pos_layer_output, all_last_attn_subvalues, all_pos_coefficient_scores, all_attn_scores\n\ndef get_bsvalues(vector, model, final_var):\n E = torch.mean(vector, -1)\n vector_ln = (vector - E.unsqueeze(-1)) / final_var * model.transformer.ln_f.weight.data\n vector_bsvalues = model.lm_head(vector_ln).data\n return vector_bsvalues\n\ndef get_prob(vector):\n prob = torch.nn.Softmax(-1)(vector)\n return prob\n\ndef get_fc2_params(model, layer_num):\n return model.transformer.h[layer_num].mlp.c_proj.weight.data.T\n\ndef transfer_l(l):\n new_x, new_y = [], []\n for x in l:\n new_x.append(x[0])\n new_y.append(x[1])\n return new_x, new_y\n\ndef FFN_neuron(model, all_pos_coefficient_scores, all_pos_residual_output, final_var, predict_index):\n all_ffn_subvalues = []\n for layer_i in range(LAYER_NUM):\n coefficient_scores = torch.tensor(all_pos_coefficient_scores[layer_i][-1])\n fc2_vectors = get_fc2_params(model, layer_i)\n ffn_subvalues = (coefficient_scores * fc2_vectors).T\n all_ffn_subvalues.append(ffn_subvalues)\n ffn_subvalue_list = []\n for layer_i in range(LAYER_NUM):\n cur_ffn_subvalues = all_ffn_subvalues[layer_i]\n cur_residual = torch.tensor(all_pos_residual_output[layer_i][-1])\n origin_prob_log = torch.log(get_prob(get_bsvalues(cur_residual, model, final_var))[predict_index])\n cur_ffn_subvalues_plus = cur_ffn_subvalues + cur_residual\n cur_ffn_subvalues_bsvalues = get_bsvalues(cur_ffn_subvalues_plus, model, final_var)\n cur_ffn_subvalues_probs = get_prob(cur_ffn_subvalues_bsvalues)\n cur_ffn_subvalues_probs = cur_ffn_subvalues_probs[:, predict_index]\n cur_ffn_subvalues_probs_log = torch.log(cur_ffn_subvalues_probs)\n cur_ffn_subvalues_probs_log_increase = cur_ffn_subvalues_probs_log - origin_prob_log\n for index, ffn_increase in enumerate(cur_ffn_subvalues_probs_log_increase):\n ffn_subvalue_list.append([str(layer_i)+\"_\"+str(index), ffn_increase.item()])\n ffn_subvalue_list_sort = sorted(ffn_subvalue_list, key=lambda x: x[-1])[::-1]\n return ffn_subvalue_list_sort\n\ndef find_query_layer(model, all_pos_layer_input, all_pos_attn_output, all_pos_ffn_output, ffn_subvalue_list_sort):\n all_residual_scores = [0.0]*(1+2*LAYER_NUM)\n for l_n, increase_score in ffn_subvalue_list_sort[:100]:\n ffn_layer, ffn_neuron = l_n.split(\"_\")\n ffn_layer, ffn_neuron = int(ffn_layer), int(ffn_neuron)\n ffn_neuron_key = model.transformer.h[ffn_layer].mlp.c_fc.weight.data[:, ffn_neuron]\n ffn_neuron_key_new = ffn_neuron_key * model.transformer.h[ffn_layer].ln_2.weight.data\n last_layer_residualstream = [torch.tensor(all_pos_layer_input[0][-1]).unsqueeze(0)]\n for layer_i in range(ffn_layer):\n last_layer_residualstream.append(torch.tensor(all_pos_attn_output[layer_i][-1]).unsqueeze(0))\n last_layer_residualstream.append(torch.tensor(all_pos_ffn_output[layer_i][-1]).unsqueeze(0))\n last_layer_residualstream.append(torch.tensor(all_pos_attn_output[ffn_layer][-1]).unsqueeze(0))\n last_layer_residualstream_cat = torch.cat(last_layer_residualstream, 0)\n last_layer_residualstream_innerproduct = torch.sum(last_layer_residualstream_cat*ffn_neuron_key_new, -1)\n last_layer_residualstream_innerproduct_zip = list(zip(range(len(last_layer_residualstream_innerproduct)), last_layer_residualstream_innerproduct.tolist()))\n sum_inner_product = sum([x[1] for x in last_layer_residualstream_innerproduct_zip])\n for l, inner in last_layer_residualstream_innerproduct_zip:\n all_residual_scores[l] += inner/sum_inner_product * increase_score\n return all_residual_scores\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n modelname = \"gpt2-large\"\n tokenizer = GPT2Tokenizer.from_pretrained(modelname)\n model = GPT2LMHeadModel.from_pretrained(modelname)\n model.eval()\n model.cuda()\n test_sentence = \"Tim Duncan plays the sport of\"\n indexed_tokens = tokenizer.encode(test_sentence)\n tokens = [tokenizer.decode(x) for x in indexed_tokens]\n tokens_tensor = torch.tensor([indexed_tokens])\n with torch.no_grad():\n outputs = model(tokens_tensor)\n predictions = outputs[0]\n predicted_top10 = torch.argsort(predictions[0][-1], descending=True)[:10]\n predicted_text = [tokenizer.decode(x) for x in predicted_top10]\n print(test_sentence, \"=>\", predicted_text)\n all_pos_layer_input, all_pos_attn_output, all_pos_residual_output, all_pos_ffn_output, all_pos_layer_output, all_last_attn_subvalues, all_pos_coefficient_scores, all_attn_scores = transfer_output(outputs[1])\n final_var = ((torch.var(torch.tensor(all_pos_layer_output[-1][-1]), -1, unbiased=False)+1e-5)**0.5).item()\n pos_len = len(tokens)\n print(tokens)\n predict_index = predicted_top10[0].item()\n print(predict_index, tokenizer.decode(predict_index))\n ffn_subvalue_list_sort = FFN_neuron(model, all_pos_coefficient_scores, all_pos_residual_output, final_var, predict_index)\n cur_file_attn_neuron_list = []\n for test_layer in range(LAYER_NUM):\n cur_layer_input = torch.tensor(all_pos_layer_input[test_layer])\n cur_v_heads_recompute = torch.tensor(all_last_attn_subvalues[test_layer]).permute(1, 0, 2)\n cur_attn_o_split = model.transformer.h[test_layer].attn.c_proj.weight.data.view(HEAD_NUM, HEAD_DIM, -1)\n cur_attn_o_recompute = cur_attn_o_split * cur_v_heads_recompute.unsqueeze(-1)\n cur_layer_input_last = cur_layer_input[-1]\n origin_prob = torch.log(get_prob(get_bsvalues(cur_layer_input_last, model, final_var))[predict_index])\n cur_attn_o_head_plus = cur_attn_o_recompute + cur_layer_input_last\n cur_attn_plus_probs = torch.log(get_prob(get_bsvalues(\n cur_attn_o_head_plus, model, final_var))[:, :, :, predict_index])\n cur_attn_plus_probs_increase = cur_attn_plus_probs - origin_prob\n for pos_index in range(cur_attn_plus_probs_increase.size(0)):\n for head_index in range(cur_attn_plus_probs_increase.size(1)):\n for attn_neuron_index in range(cur_attn_plus_probs_increase.size(2)):\n cur_file_attn_neuron_list.append((str(test_layer)+\"_\"+str(head_index)+\"_\"+str(\n attn_neuron_index)+\"_\"+str(pos_index),\n cur_attn_plus_probs_increase[pos_index][head_index][attn_neuron_index].item()))\n cur_file_attn_neuron_list_sort = sorted(cur_file_attn_neuron_list, key=lambda x: x[-1])[::-1]\n print(list(zip(range(len(tokens)), tokens)))\n for x in cur_file_attn_neuron_list_sort[:10]:\n layer_i, head_i, neuron_i, _ = x[0].split(\"_\")\n layer_i, head_i, neuron_i = int(layer_i), int(head_i), int(neuron_i)\n cur_neuron = model.transformer.h[layer_i].attn.c_proj.weight.data.view(HEAD_NUM, HEAD_DIM, -1)[head_i][neuron_i]\n cur_neuron_bsvalue = get_bsvalues(cur_neuron, model, final_var)\n cur_neuron_bsvalue_sort = torch.argsort(cur_neuron_bsvalue, descending=True)\n print(x[0], round(x[1], 4), \"top10: \", [tokenizer.decode(a) for a in cur_neuron_bsvalue_sort[:10]])\n print(x[0], round(x[1], 4), \"last10: \", [tokenizer.decode(a) for a in cur_neuron_bsvalue_sort[-10:]])\n attn_value_neurons = [x[0] for x in cur_file_attn_neuron_list_sort[:300]]\n attn_layer_count_value = [int(x.split(\"_\")[0]) for x in list(attn_value_neurons)]\n attn_layer_count_value = Counter(attn_layer_count_value)\n attn_layer_count_value = sorted(zip(attn_layer_count_value.keys(), attn_layer_count_value.values()))\n gpt_attn_value_x, gpt_attn_value_y = transfer_l(attn_layer_count_value)\n all_residual_scores = [0.0]*(1+2*LAYER_NUM)\n for l_n, increase_score in ffn_subvalue_list_sort[:100]:\n ffn_layer, ffn_neuron = l_n.split(\"_\")\n ffn_layer, ffn_neuron = int(ffn_layer), int(ffn_neuron)\n ffn_neuron_key = model.transformer.h[ffn_layer].mlp.c_fc.weight.data[:, ffn_neuron]\n ffn_neuron_key_new = ffn_neuron_key * model.transformer.h[ffn_layer].ln_2.weight.data\n last_layer_residualstream = [torch.tensor(all_pos_layer_input[0][-1]).unsqueeze(0)]\n for layer_i in range(ffn_layer):\n last_layer_residualstream.append(torch.tensor(all_pos_attn_output[layer_i][-1]).unsqueeze(0))\n last_layer_residualstream.append(torch.tensor(all_pos_ffn_output[layer_i][-1]).unsqueeze(0))\n last_layer_residualstream.append(torch.tensor(all_pos_attn_output[ffn_layer][-1]).unsqueeze(0))\n last_layer_residualstream_cat = torch.cat(last_layer_residualstream, 0)\n last_layer_residualstream_innerproduct = torch.sum(last_layer_residualstream_cat*ffn_neuron_key_new, -1)\n last_layer_residualstream_innerproduct_zip = list(zip(range(len(last_layer_residualstream_innerproduct)), last_layer_residualstream_innerproduct.tolist()))\n sum_inner_product = sum([x[1] for x in last_layer_residualstream_innerproduct_zip])\n for l, inner in last_layer_residualstream_innerproduct_zip:\n all_residual_scores[l] += inner/sum_inner_product * increase_score\n all_residual_scores_zip = list(zip(range(len(all_residual_scores)), all_residual_scores))\n all_residual_scores_zip_sort = sorted(all_residual_scores_zip, key=lambda x: x[-1])[::-1]\n print([(a[0]/2-0.5, round(a[1],4)) for a in all_residual_scores_zip_sort])\n all_residual_scores = find_query_layer(model, all_pos_layer_input, all_pos_attn_output, all_pos_ffn_output, ffn_subvalue_list_sort)\n curfile_ffn_score_dict = {}\n for l_h_n_p, increase_score in cur_file_attn_neuron_list_sort[:30]:\n attn_layer, attn_head, attn_neuron, attn_pos = l_h_n_p.split(\"_\")\n attn_layer, attn_head, attn_neuron, attn_pos = int(attn_layer), int(attn_head), int(attn_neuron), int(attn_pos)\n cur_attn_neuron = attn_head*HEAD_DIM+attn_neuron\n attn_neuron_key = model.transformer.h[attn_layer].attn.c_attn.weight.data[:, 2560:][:, cur_attn_neuron]\n attn_neuron_key_new = attn_neuron_key * model.transformer.h[attn_layer].ln_1.weight.data\n cur_inner_all = torch.sum(torch.tensor(all_pos_layer_input[attn_layer][attn_pos])*attn_neuron_key_new, -1)\n for layer_i in range(attn_layer):\n cur_layer_neurons = (torch.tensor(all_pos_coefficient_scores[layer_i][attn_pos])*get_fc2_params(model, layer_i)).T\n cur_layer_neurons_innerproduct = torch.sum(cur_layer_neurons * attn_neuron_key_new, -1)/cur_inner_all\n for neuron_i in range(len(cur_layer_neurons_innerproduct)):\n if str(layer_i)+\"_\"+str(neuron_i) not in curfile_ffn_score_dict:\n curfile_ffn_score_dict[str(layer_i)+\"_\"+str(neuron_i)] = 0.0\n curfile_ffn_score_dict[str(layer_i)+\"_\"+str(neuron_i)] += cur_layer_neurons_innerproduct[neuron_i].item() * increase_score\n cur_file_neurons_ffn_zip = list(zip(curfile_ffn_score_dict.keys(), curfile_ffn_score_dict.values()))\n cur_file_neurons_ffn_zip_sort = sorted(cur_file_neurons_ffn_zip, key=lambda x: x[-1])[::-1]\n for x in cur_file_neurons_ffn_zip_sort[:10]:\n print(x[0], round(x[1], 4))\n layer = int(x[0].split(\"_\")[0])\n neuron = int(x[0].split(\"_\")[1])\n cur_vector = get_fc2_params(model, layer).T[neuron]\n cur_vector_bsvalue = get_bsvalues(cur_vector, model, final_var)\n cur_vector_bsvalue_sort = torch.argsort(cur_vector_bsvalue, descending=True)\n print(\"top10: \", [tokenizer.decode(a) for a in cur_vector_bsvalue_sort[:10]])\n print(\"last10: \", [tokenizer.decode(a) for a in cur_vector_bsvalue_sort[-10:]])\n value_neurons = [x[0] for x in ffn_subvalue_list_sort[:300]]\n query_neurons = [x[0] for x in cur_file_neurons_ffn_zip_sort[:300]]\n queryvalue_neurons = set(value_neurons) & set(query_neurons)\n queryonly_neurons = set(query_neurons) - queryvalue_neurons\n layer_count_queryonly = [int(x.split(\"_\")[0]) for x in list(queryonly_neurons)]\n layer_count_queryonly = Counter(layer_count_queryonly)\n layer_count_queryonly = sorted(zip(layer_count_queryonly.keys(), layer_count_queryonly.values()))\n gpt_queryonly_x, gpt_queryonly_y = transfer_l(layer_count_queryonly)\n layer_count_queryvalue = [int(x.split(\"_\")[0]) for x in list(queryvalue_neurons)]\n layer_count_queryvalue = Counter(layer_count_queryvalue)\n layer_count_queryvalue = sorted(zip(layer_count_queryvalue.keys(), layer_count_queryvalue.values()))\n gpt_queryvalue_x, gpt_queryvalue_y = transfer_l(layer_count_queryvalue)\n curfile_ffn_score_dict = {}\n l_h_n_p = \"21_19_7_1\"\n attn_layer, attn_head, attn_neuron, attn_pos = l_h_n_p.split(\"_\")\n attn_layer, attn_head, attn_neuron, attn_pos = int(attn_layer), int(attn_head), int(attn_neuron), int(attn_pos)\n cur_attn_neuron = attn_head*HEAD_DIM+attn_neuron\n attn_neuron_key = model.transformer.h[attn_layer].attn.c_attn.weight.data[:, 2560:][:, cur_attn_neuron]\n attn_neuron_key_new = attn_neuron_key * model.transformer.h[attn_layer].ln_1.weight.data\n cur_inner_all = torch.sum(torch.tensor(all_pos_layer_input[attn_layer][attn_pos])*attn_neuron_key_new, -1)\n for layer_i in range(attn_layer):\n cur_layer_neurons = (torch.tensor(all_pos_coefficient_scores[layer_i][attn_pos])*get_fc2_params(model, layer_i)).T\n cur_layer_neurons_innerproduct = torch.sum(cur_layer_neurons * attn_neuron_key_new, -1)/cur_inner_all\n for neuron_i in range(len(cur_layer_neurons_innerproduct)):\n if str(layer_i)+\"_\"+str(neuron_i) not in curfile_ffn_score_dict:\n curfile_ffn_score_dict[str(layer_i)+\"_\"+str(neuron_i)] = 0.0\n curfile_ffn_score_dict[str(layer_i)+\"_\"+str(neuron_i)] += cur_layer_neurons_innerproduct[neuron_i].item() * increase_score\n cur_file_neurons_ffn_zip = list(zip(curfile_ffn_score_dict.keys(), curfile_ffn_score_dict.values()))\n cur_file_neurons_ffn_zip_sort = sorted(cur_file_neurons_ffn_zip, key=lambda x: x[-1])[::-1]\n for x in cur_file_neurons_ffn_zip_sort[:10]:\n print(x[0], round(x[1], 4))\n layer = int(x[0].split(\"_\")[0])\n neuron = int(x[0].split(\"_\")[1])\n cur_vector = get_fc2_params(model, layer).T[neuron]\n cur_vector_bsvalue = get_bsvalues(cur_vector, model, final_var)\n cur_vector_bsvalue_sort = torch.argsort(cur_vector_bsvalue, descending=True)\n print(\"top10: \", [tokenizer.decode(a) for a in cur_vector_bsvalue_sort[:10]])\n print(\"last10: \", [tokenizer.decode(a) for a in cur_vector_bsvalue_sort[-10:]])\n attn_layer, attn_head, attn_neuron, attn_pos = l_h_n_p.split(\"_\")\n attn_layer, attn_head, attn_neuron, attn_pos = int(attn_layer), int(attn_head), int(attn_neuron), int(attn_pos)\n test_query_neuron = \"0_1984\"\n test_query_layer, test_query_index = test_query_neuron.split(\"_\")\n test_query_layer, test_query_index = int(test_query_layer), int(test_query_index)\n cur_neuron_vector = get_fc2_params(model, test_query_layer).T[test_query_index]\n cur_neuron_vector_ln = model.transformer.h[attn_layer].ln_1(cur_neuron_vector)\n cur_neuron_v = model.transformer.h[attn_layer].attn.c_attn(\n cur_neuron_vector_ln)[2560:][attn_head*HEAD_DIM:attn_head*HEAD_DIM+HEAD_DIM]\n cur_attn_o_split = model.transformer.h[attn_layer].attn.c_proj.weight.data.view(\n HEAD_NUM, HEAD_DIM, -1)[attn_head]\n cur_neuron_vo = torch.sum(cur_neuron_v.unsqueeze(1)*cur_attn_o_split, 0)\n cur_neuron_o_bsvalues = get_bsvalues(cur_neuron_vo, model, final_var)\n cur_neuron_o_bsvalues_sort = torch.argsort(cur_neuron_o_bsvalues, descending=True)\n print(\"top: \", [tokenizer.decode(x) for x in cur_neuron_o_bsvalues_sort[:10]])\n print(\"last: \", [tokenizer.decode(x) for x in cur_neuron_o_bsvalues_sort[-10:]])" }, { "task_id": 1, "indent": 1, "script": "\npython GPT2_view_knowledge.py\n", "latex_code": "\n\\subsection{Importance Score for \"Value Neurons\"}\nBased on the analysis in Section 3.2, an intuitive importance score of a neuron $mv$ is $|m| \\times |1/rank(w)|$, where $m$ is the coefficient score and $rank(w)$ denotes the ranking of the final token when projecting $v$ into vocabulary space. Another intuitive importance score is calculating the probability $p(w|mv)$ on token $w$. If these scores are large, $v$ will contain much information of $w$. \n\nHowever, these methods have two potential problems. On one hand, they only consider the effect of $v$, overlooking the varying importance of $v$ under different $x$ conditions. On the other hand, we usually hope to analyze the importance of different modules' combination. Therefore, it is better that the importance score $Imp$ satisfies $Imp(x+v) \\approx Imp(x) + Imp(v)$.\n\nTo address these problems, we design log probability increase as importance score for both layer-level and neuron-level vectors. If $v^l$ is a vector in $lth$ attention layer, the importance score of $v^l$ is:\n\\begin{equation}\nImp(v^l) = log(p(w|v^l+h^{l-1})) - log(p(w|h^{l-1}))\n\\end{equation}\nwhere the probability of each vector is computed by multiplying the vector with $E_u$ (see Eq.2). If $v^l$ is a vector in $lth$ FFN layer, we compute the importance score by replacing $h^{l-1}$ as $h^{l-1}+A^{l}$ in Eq.13. In Eq.13, $v^l$ is not the only element controlling the importance score. Also, it is convenient for analyzing the combination of different modules.\n", "completion_path": "./GPT2_view_knowledge.py", "namespace": "GPT2_view_knowledge.FFN_neuron", "type": "function", "signature_position": [ 59, 59 ], "body_position": [ 60, 80 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: This function begins by iterating over each FFN layer. It gathers the coefficient scores (m_{i,k}^l) and\n# multiplies them by the subvalue vectors (fc2_k^l) of that layer. \n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nall_ffn_subvalues = []\nfor layer_i in range(LAYER_NUM):\n coefficient_scores = torch.tensor(all_pos_coefficient_scores[layer_i][-1])\n fc2_vectors = get_fc2_params(model, layer_i)\n ffn_subvalues = (coefficient_scores * fc2_vectors).T\n all_ffn_subvalues.append(ffn_subvalues)\n# [End Snippet 1]\n\nffn_subvalue_list = []\nfor layer_i in range(LAYER_NUM):\n # -----------------------------------------------------------------------\n # Snippet 2: The log probability of the baseline (i.e., without adding any\n # neuron vector) is captured here. This maps to log(p(w|h^{l-1}+A^l)) from the\n # LaTeX code.\n # -----------------------------------------------------------------------\n # [Begin Snippet 2]\n cur_ffn_subvalues = all_ffn_subvalues[layer_i]\n cur_residual = torch.tensor(all_pos_residual_output[layer_i][-1])\n\n origin_prob_log = torch.log(get_prob(get_bsvalues(cur_residual, model, final_var))[predict_index])\n # [End Snippet 2]\n\n # -----------------------------------------------------------------------\n # Snippet 3: Each neuron's contribution is examined by adding it to the\n # residual (h^{l-1} + A^l + v^l in Eq.13) and measuring how this change\n # affects the final probability distribution.\n # -----------------------------------------------------------------------\n # [Begin Snippet 3]\n cur_ffn_subvalues_plus = cur_ffn_subvalues + cur_residual\n cur_ffn_subvalues_bsvalues = get_bsvalues(cur_ffn_subvalues_plus, model, final_var)\n cur_ffn_subvalues_probs = get_prob(cur_ffn_subvalues_bsvalues)\n cur_ffn_subvalues_probs = cur_ffn_subvalues_probs[:, predict_index]\n cur_ffn_subvalues_probs_log = torch.log(cur_ffn_subvalues_probs)\n cur_ffn_subvalues_probs_log_increase = cur_ffn_subvalues_probs_log - origin_prob_log\n \n for index, ffn_increase in enumerate(cur_ffn_subvalues_probs_log_increase):\n ffn_subvalue_list.append([str(layer_i)+\"_\"+str(index), ffn_increase.item()])\n # [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: The resulting list of neuron contributions is sorted in descending\n# order of their importance score, reflecting the emphasis on isolating the\n# most influential \"value neurons\" as discussed in the LaTeX sub-section.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nffn_subvalue_list_sort = sorted(ffn_subvalue_list, key=lambda x: x[-1])[::-1]\nreturn ffn_subvalue_list_sort\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX description does not specify how the vectors from the FFN layer are transformed into a probability distribution over the vocabulary. In the method, after combining a neuron\u2019s contribution with the baseline input, there should be a step where this combined vector is projected into the vocabulary space to compute the probability of the target token. This involves multiplying the vector by a matrix that maps it to token logits, followed by a normalization process (e.g., softmax) to obtain probabilities.\n - There is no mention in the LaTeX description of how the weights or parameters of the FFN\u2019s second linear transformation are incorporated into the neuron\u2019s contribution. The method requires calculating each neuron\u2019s subvalue by scaling its coefficient score with the corresponding weight vector from the FFN\u2019s output layer.\n - The LaTeX does not describe the process of iterating over all neurons within a layer to evaluate their individual contributions to the target token\u2019s probability. The workflow should involve taking each neuron\u2019s contribution, adding it to the baseline state, computing the resulting probability, and then determining the difference from the baseline probability.\n\n Mismatched Details:\n - The LaTeX suggests that the probability \\( p(w|v^l + h^{l-1}) \\) (or \\( h^{l-1} + A^l \\) for FFN) is computed directly after adding the neuron\u2019s vector, implying a single-step combination. However, the actual method requires a two-step process: first, combining the neuron\u2019s contribution with the baseline, and then projecting this combined vector into the vocabulary space to compute probabilities.\n - The LaTeX description states that for FFN layers, the importance score is computed by replacing the baseline \\( h^{l-1} \\) with \\( h^{l-1} + A^l \\) in the log probability difference formula. However, it does not clarify whether \\( A^l \\) (the attention output) is already included in the baseline vector used for probability computation. In practice, the baseline must consistently include the attention contribution before adding the FFN neuron\u2019s vector to ensure the importance score isolates the neuron\u2019s effect.\n\n", "Missing_details": [ "\n- The LaTeX description does not specify how the vectors from the FFN layer are transformed into a probability distribution over the vocabulary. In the method, after combining a neuron\u2019s contribution with the baseline input, there should be a step where this combined vector is projected into the vocabulary space to compute the probability of the target token. This involves multiplying the vector by a matrix that maps it to token logits, followed by a normalization process (e.g., softmax) to obtain probabilities.\n", "\n- There is no mention in the LaTeX description of how the weights or parameters of the FFN\u2019s second linear transformation are incorporated into the neuron\u2019s contribution. The method requires calculating each neuron\u2019s subvalue by scaling its coefficient score with the corresponding weight vector from the FFN\u2019s output layer.\n", " \n- The LaTeX does not describe the process of iterating over all neurons within a layer to evaluate their individual contributions to the target token\u2019s probability. The workflow should involve taking each neuron\u2019s contribution, adding it to the baseline state, computing the resulting probability, and then determining the difference from the baseline probability.\n" ], "Mismatched_details": [ "\n- The LaTeX suggests that the probability \\( p(w|v^l + h^{l-1}) \\) (or \\( h^{l-1} + A^l \\) for FFN) is computed directly after adding the neuron\u2019s vector, implying a single-step combination. However, the actual method requires a two-step process: first, combining the neuron\u2019s contribution with the baseline, and then projecting this combined vector into the vocabulary space to compute probabilities.\n", "\n- The LaTeX description states that for FFN layers, the importance score is computed by replacing the baseline \\( h^{l-1} \\) with \\( h^{l-1} + A^l \\) in the log probability difference formula. However, it does not clarify whether \\( A^l \\) (the attention output) is already included in the baseline vector used for probability computation. In practice, the baseline must consistently include the attention contribution before adding the FFN neuron\u2019s vector to ensure the importance score isolates the neuron\u2019s effect.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - model (An object of modeling_gpt2.GPT2LMHeadModel):\n The transformer model instance from which we extract FFN parameters. \n This aligns with the concept of computing importance scores on FFN neurons described in Eq.5-6 of the LaTeX.\n - all_pos_coefficient_scores (list[list[list[float]]], [num_layers, seq_len, num_neurons]):\n A structure containing the coefficient scores for each FFN neuron at various positions and layers for all input tokens.\n - all_pos_residual_output (list[list[list[float]]], [num_layers, seq_len, num_neurons]):\n The residual outputs at different layers for all input tokens.\n - final_var (float):\n A helper variable representing final states or parameters needed for probability computation.\n - predict_index (int):\n Specifies which token's probability is being analyzed. \n", "Arguments_list": [ { "name": "model", "string": "\n- model (An object of modeling_gpt2.GPT2LMHeadModel):\n The transformer model instance from which we extract FFN parameters. \n This aligns with the concept of computing importance scores on FFN neurons described in Eq.5-6 of the LaTeX.\n", "dependency": "modeling_gpt2.GPT2LMHeadModel" }, { "name": "all_pos_coefficient_scores", "string": "\n- all_pos_coefficient_scores (list[list[list[float]]], [num_layers, seq_len, num_neurons]):\n A structure containing the coefficient scores for each FFN neuron at various positions and layers for all input tokens.\n", "dependency": null }, { "name": "all_pos_residual_output", "string": "\n- all_pos_residual_output (list[list[list[float]]], [num_layers, seq_len, num_neurons]):\n The residual outputs at different layers for all input tokens.\n", "dependency": null }, { "name": "final_var", "string": "\n- final_var (float):\n A helper variable representing final states or parameters needed for probability computation.\n", "dependency": null }, { "name": "predict_index", "string": " \n- predict_index (int):\n Specifies which token's probability is being analyzed.\n", "dependency": null } ] }, "dependency": { "string": "\nRepository Dependencies:\n - Intra-File Dependencies:\n - get_fc2_params\n - get_bsvalues\n - get_prob\n \n - Cross-File Dependencies:\n - None\n", "intra_file": [ "get_fc2_params", "get_bsvalues", "get_prob" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.tensor\n - torch.log\n", "list": [ "torch.tensor", "torch.log" ] }, "Return": { "Return_String": "\nOutput Variables:\n - ffn_subvalue_list_sort (list[tuple]): The full list is sorted in descending order of contribution scores. Neurons at the top of the list have a larger positive impact on increasing the log probability of the predicted token, thus highlighting them as potentially more important \u201cvalue neurons.\u201d\n Each tuple consists of two entries:\n - A string identifier (\"layerindex_neuronindex\"), indicating the layer number and the neuron index within that layer.\n - A floating-point value representing how much the respective neuron contributed (via its subvalue) to increasing the log probability of the predicted token.\n", "Return_list": [ { "name": "ffn_subvalue_list_sort", "string": "\n- ffn_subvalue_list_sort (list[tuple]): The full list is sorted in descending order of contribution scores. Neurons at the top of the list have a larger positive impact on increasing the log probability of the predicted token, thus highlighting them as potentially more important \u201cvalue neurons.\u201d\n Each tuple consists of two entries:\n - A string identifier (\"layerindex_neuronindex\"), indicating the layer number and the neuron index within that layer.\n - A floating-point value representing how much the respective neuron contributed (via its subvalue) to increasing the log probability of the predicted token.\n", "dependency": null } ] }, "ori_python_file": "import torch\nfrom collections import Counter\nfrom transformers import GPT2Tokenizer\nfrom modeling_gpt2 import GPT2LMHeadModel\nLAYER_NUM = 36\nHEAD_NUM = 20\nHEAD_DIM = 64\nHIDDEN_DIM = HEAD_NUM * HEAD_DIM\ntorch.set_default_device(\"cuda\")\n\ndef transfer_output(model_output):\n all_pos_layer_input = []\n all_pos_attn_output = []\n all_pos_residual_output = []\n all_pos_ffn_output = []\n all_pos_layer_output = []\n all_last_attn_subvalues = []\n all_pos_coefficient_scores = []\n all_attn_scores = []\n for layer_i in range(LAYER_NUM):\n cur_layer_input = model_output[layer_i][0]\n cur_attn_output = model_output[layer_i][1]\n cur_residual_output = model_output[layer_i][2]\n cur_ffn_output = model_output[layer_i][3]\n cur_layer_output = model_output[layer_i][4]\n cur_last_attn_subvalues = model_output[layer_i][5]\n cur_coefficient_scores = model_output[layer_i][6]\n cur_attn_weights = model_output[layer_i][7]\n all_pos_layer_input.append(cur_layer_input[0].tolist())\n all_pos_attn_output.append(cur_attn_output[0].tolist())\n all_pos_residual_output.append(cur_residual_output[0].tolist())\n all_pos_ffn_output.append(cur_ffn_output[0].tolist())\n all_pos_layer_output.append(cur_layer_output[0].tolist())\n all_last_attn_subvalues.append(cur_last_attn_subvalues[0].tolist())\n all_pos_coefficient_scores.append(cur_coefficient_scores[0].tolist())\n all_attn_scores.append(cur_attn_weights)\n return all_pos_layer_input, all_pos_attn_output, all_pos_residual_output, all_pos_ffn_output, all_pos_layer_output, all_last_attn_subvalues, all_pos_coefficient_scores, all_attn_scores\n\ndef get_bsvalues(vector, model, final_var):\n E = torch.mean(vector, -1)\n vector_ln = (vector - E.unsqueeze(-1)) / final_var * model.transformer.ln_f.weight.data\n vector_bsvalues = model.lm_head(vector_ln).data\n return vector_bsvalues\n\ndef get_prob(vector):\n prob = torch.nn.Softmax(-1)(vector)\n return prob\n\ndef get_fc2_params(model, layer_num):\n return model.transformer.h[layer_num].mlp.c_proj.weight.data.T\n\ndef transfer_l(l):\n new_x, new_y = [], []\n for x in l:\n new_x.append(x[0])\n new_y.append(x[1])\n return new_x, new_y\n\ndef FFN_neuron(model, all_pos_coefficient_scores, all_pos_residual_output, final_var, predict_index):\n all_ffn_subvalues = []\n for layer_i in range(LAYER_NUM):\n coefficient_scores = torch.tensor(all_pos_coefficient_scores[layer_i][-1])\n fc2_vectors = get_fc2_params(model, layer_i)\n ffn_subvalues = (coefficient_scores * fc2_vectors).T\n all_ffn_subvalues.append(ffn_subvalues)\n ffn_subvalue_list = []\n for layer_i in range(LAYER_NUM):\n cur_ffn_subvalues = all_ffn_subvalues[layer_i]\n cur_residual = torch.tensor(all_pos_residual_output[layer_i][-1])\n origin_prob_log = torch.log(get_prob(get_bsvalues(cur_residual, model, final_var))[predict_index])\n cur_ffn_subvalues_plus = cur_ffn_subvalues + cur_residual\n cur_ffn_subvalues_bsvalues = get_bsvalues(cur_ffn_subvalues_plus, model, final_var)\n cur_ffn_subvalues_probs = get_prob(cur_ffn_subvalues_bsvalues)\n cur_ffn_subvalues_probs = cur_ffn_subvalues_probs[:, predict_index]\n cur_ffn_subvalues_probs_log = torch.log(cur_ffn_subvalues_probs)\n cur_ffn_subvalues_probs_log_increase = cur_ffn_subvalues_probs_log - origin_prob_log\n for index, ffn_increase in enumerate(cur_ffn_subvalues_probs_log_increase):\n ffn_subvalue_list.append([str(layer_i)+\"_\"+str(index), ffn_increase.item()])\n ffn_subvalue_list_sort = sorted(ffn_subvalue_list, key=lambda x: x[-1])[::-1]\n return ffn_subvalue_list_sort\n\ndef find_query_layer(model, all_pos_layer_input, all_pos_attn_output, all_pos_ffn_output, ffn_subvalue_list_sort):\n all_residual_scores = [0.0]*(1+2*LAYER_NUM)\n for l_n, increase_score in ffn_subvalue_list_sort[:100]:\n ffn_layer, ffn_neuron = l_n.split(\"_\")\n ffn_layer, ffn_neuron = int(ffn_layer), int(ffn_neuron)\n ffn_neuron_key = model.transformer.h[ffn_layer].mlp.c_fc.weight.data[:, ffn_neuron]\n ffn_neuron_key_new = ffn_neuron_key * model.transformer.h[ffn_layer].ln_2.weight.data\n last_layer_residualstream = [torch.tensor(all_pos_layer_input[0][-1]).unsqueeze(0)]\n for layer_i in range(ffn_layer):\n last_layer_residualstream.append(torch.tensor(all_pos_attn_output[layer_i][-1]).unsqueeze(0))\n last_layer_residualstream.append(torch.tensor(all_pos_ffn_output[layer_i][-1]).unsqueeze(0))\n last_layer_residualstream.append(torch.tensor(all_pos_attn_output[ffn_layer][-1]).unsqueeze(0))\n last_layer_residualstream_cat = torch.cat(last_layer_residualstream, 0)\n last_layer_residualstream_innerproduct = torch.sum(last_layer_residualstream_cat*ffn_neuron_key_new, -1)\n last_layer_residualstream_innerproduct_zip = list(zip(range(len(last_layer_residualstream_innerproduct)), last_layer_residualstream_innerproduct.tolist()))\n sum_inner_product = sum([x[1] for x in last_layer_residualstream_innerproduct_zip])\n for l, inner in last_layer_residualstream_innerproduct_zip:\n all_residual_scores[l] += inner/sum_inner_product * increase_score\n return all_residual_scores\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n modelname = \"gpt2-large\"\n tokenizer = GPT2Tokenizer.from_pretrained(modelname)\n model = GPT2LMHeadModel.from_pretrained(modelname)\n model.eval()\n model.cuda()\n test_sentence = \"Tim Duncan plays the sport of\"\n indexed_tokens = tokenizer.encode(test_sentence)\n tokens = [tokenizer.decode(x) for x in indexed_tokens]\n tokens_tensor = torch.tensor([indexed_tokens])\n with torch.no_grad():\n outputs = model(tokens_tensor)\n predictions = outputs[0]\n predicted_top10 = torch.argsort(predictions[0][-1], descending=True)[:10]\n predicted_text = [tokenizer.decode(x) for x in predicted_top10]\n print(test_sentence, \"=>\", predicted_text)\n all_pos_layer_input, all_pos_attn_output, all_pos_residual_output, all_pos_ffn_output, all_pos_layer_output, all_last_attn_subvalues, all_pos_coefficient_scores, all_attn_scores = transfer_output(outputs[1])\n final_var = ((torch.var(torch.tensor(all_pos_layer_output[-1][-1]), -1, unbiased=False)+1e-5)**0.5).item()\n pos_len = len(tokens)\n print(tokens)\n predict_index = predicted_top10[0].item()\n print(predict_index, tokenizer.decode(predict_index))\n ffn_subvalue_list_sort = FFN_neuron(model, all_pos_coefficient_scores, all_pos_residual_output, final_var, predict_index)\n cur_file_attn_neuron_list = []\n for test_layer in range(LAYER_NUM):\n cur_layer_input = torch.tensor(all_pos_layer_input[test_layer])\n cur_v_heads_recompute = torch.tensor(all_last_attn_subvalues[test_layer]).permute(1, 0, 2)\n cur_attn_o_split = model.transformer.h[test_layer].attn.c_proj.weight.data.view(HEAD_NUM, HEAD_DIM, -1)\n cur_attn_o_recompute = cur_attn_o_split * cur_v_heads_recompute.unsqueeze(-1)\n cur_layer_input_last = cur_layer_input[-1]\n origin_prob = torch.log(get_prob(get_bsvalues(cur_layer_input_last, model, final_var))[predict_index])\n cur_attn_o_head_plus = cur_attn_o_recompute + cur_layer_input_last\n cur_attn_plus_probs = torch.log(get_prob(get_bsvalues(\n cur_attn_o_head_plus, model, final_var))[:, :, :, predict_index])\n cur_attn_plus_probs_increase = cur_attn_plus_probs - origin_prob\n for pos_index in range(cur_attn_plus_probs_increase.size(0)):\n for head_index in range(cur_attn_plus_probs_increase.size(1)):\n for attn_neuron_index in range(cur_attn_plus_probs_increase.size(2)):\n cur_file_attn_neuron_list.append((str(test_layer)+\"_\"+str(head_index)+\"_\"+str(\n attn_neuron_index)+\"_\"+str(pos_index),\n cur_attn_plus_probs_increase[pos_index][head_index][attn_neuron_index].item()))\n cur_file_attn_neuron_list_sort = sorted(cur_file_attn_neuron_list, key=lambda x: x[-1])[::-1]\n print(list(zip(range(len(tokens)), tokens)))\n for x in cur_file_attn_neuron_list_sort[:10]:\n layer_i, head_i, neuron_i, _ = x[0].split(\"_\")\n layer_i, head_i, neuron_i = int(layer_i), int(head_i), int(neuron_i)\n cur_neuron = model.transformer.h[layer_i].attn.c_proj.weight.data.view(HEAD_NUM, HEAD_DIM, -1)[head_i][neuron_i]\n cur_neuron_bsvalue = get_bsvalues(cur_neuron, model, final_var)\n cur_neuron_bsvalue_sort = torch.argsort(cur_neuron_bsvalue, descending=True)\n print(x[0], round(x[1], 4), \"top10: \", [tokenizer.decode(a) for a in cur_neuron_bsvalue_sort[:10]])\n print(x[0], round(x[1], 4), \"last10: \", [tokenizer.decode(a) for a in cur_neuron_bsvalue_sort[-10:]])\n attn_value_neurons = [x[0] for x in cur_file_attn_neuron_list_sort[:300]]\n attn_layer_count_value = [int(x.split(\"_\")[0]) for x in list(attn_value_neurons)]\n attn_layer_count_value = Counter(attn_layer_count_value)\n attn_layer_count_value = sorted(zip(attn_layer_count_value.keys(), attn_layer_count_value.values()))\n gpt_attn_value_x, gpt_attn_value_y = transfer_l(attn_layer_count_value)\n all_residual_scores = [0.0]*(1+2*LAYER_NUM)\n for l_n, increase_score in ffn_subvalue_list_sort[:100]:\n ffn_layer, ffn_neuron = l_n.split(\"_\")\n ffn_layer, ffn_neuron = int(ffn_layer), int(ffn_neuron)\n ffn_neuron_key = model.transformer.h[ffn_layer].mlp.c_fc.weight.data[:, ffn_neuron]\n ffn_neuron_key_new = ffn_neuron_key * model.transformer.h[ffn_layer].ln_2.weight.data\n last_layer_residualstream = [torch.tensor(all_pos_layer_input[0][-1]).unsqueeze(0)]\n for layer_i in range(ffn_layer):\n last_layer_residualstream.append(torch.tensor(all_pos_attn_output[layer_i][-1]).unsqueeze(0))\n last_layer_residualstream.append(torch.tensor(all_pos_ffn_output[layer_i][-1]).unsqueeze(0))\n last_layer_residualstream.append(torch.tensor(all_pos_attn_output[ffn_layer][-1]).unsqueeze(0))\n last_layer_residualstream_cat = torch.cat(last_layer_residualstream, 0)\n last_layer_residualstream_innerproduct = torch.sum(last_layer_residualstream_cat*ffn_neuron_key_new, -1)\n last_layer_residualstream_innerproduct_zip = list(zip(range(len(last_layer_residualstream_innerproduct)), last_layer_residualstream_innerproduct.tolist()))\n sum_inner_product = sum([x[1] for x in last_layer_residualstream_innerproduct_zip])\n for l, inner in last_layer_residualstream_innerproduct_zip:\n all_residual_scores[l] += inner/sum_inner_product * increase_score\n all_residual_scores_zip = list(zip(range(len(all_residual_scores)), all_residual_scores))\n all_residual_scores_zip_sort = sorted(all_residual_scores_zip, key=lambda x: x[-1])[::-1]\n print([(a[0]/2-0.5, round(a[1],4)) for a in all_residual_scores_zip_sort])\n all_residual_scores = find_query_layer(model, all_pos_layer_input, all_pos_attn_output, all_pos_ffn_output, ffn_subvalue_list_sort)\n curfile_ffn_score_dict = {}\n for l_h_n_p, increase_score in cur_file_attn_neuron_list_sort[:30]:\n attn_layer, attn_head, attn_neuron, attn_pos = l_h_n_p.split(\"_\")\n attn_layer, attn_head, attn_neuron, attn_pos = int(attn_layer), int(attn_head), int(attn_neuron), int(attn_pos)\n cur_attn_neuron = attn_head*HEAD_DIM+attn_neuron\n attn_neuron_key = model.transformer.h[attn_layer].attn.c_attn.weight.data[:, 2560:][:, cur_attn_neuron]\n attn_neuron_key_new = attn_neuron_key * model.transformer.h[attn_layer].ln_1.weight.data\n cur_inner_all = torch.sum(torch.tensor(all_pos_layer_input[attn_layer][attn_pos])*attn_neuron_key_new, -1)\n for layer_i in range(attn_layer):\n cur_layer_neurons = (torch.tensor(all_pos_coefficient_scores[layer_i][attn_pos])*get_fc2_params(model, layer_i)).T\n cur_layer_neurons_innerproduct = torch.sum(cur_layer_neurons * attn_neuron_key_new, -1)/cur_inner_all\n for neuron_i in range(len(cur_layer_neurons_innerproduct)):\n if str(layer_i)+\"_\"+str(neuron_i) not in curfile_ffn_score_dict:\n curfile_ffn_score_dict[str(layer_i)+\"_\"+str(neuron_i)] = 0.0\n curfile_ffn_score_dict[str(layer_i)+\"_\"+str(neuron_i)] += cur_layer_neurons_innerproduct[neuron_i].item() * increase_score\n cur_file_neurons_ffn_zip = list(zip(curfile_ffn_score_dict.keys(), curfile_ffn_score_dict.values()))\n cur_file_neurons_ffn_zip_sort = sorted(cur_file_neurons_ffn_zip, key=lambda x: x[-1])[::-1]\n for x in cur_file_neurons_ffn_zip_sort[:10]:\n print(x[0], round(x[1], 4))\n layer = int(x[0].split(\"_\")[0])\n neuron = int(x[0].split(\"_\")[1])\n cur_vector = get_fc2_params(model, layer).T[neuron]\n cur_vector_bsvalue = get_bsvalues(cur_vector, model, final_var)\n cur_vector_bsvalue_sort = torch.argsort(cur_vector_bsvalue, descending=True)\n print(\"top10: \", [tokenizer.decode(a) for a in cur_vector_bsvalue_sort[:10]])\n print(\"last10: \", [tokenizer.decode(a) for a in cur_vector_bsvalue_sort[-10:]])\n value_neurons = [x[0] for x in ffn_subvalue_list_sort[:300]]\n query_neurons = [x[0] for x in cur_file_neurons_ffn_zip_sort[:300]]\n queryvalue_neurons = set(value_neurons) & set(query_neurons)\n queryonly_neurons = set(query_neurons) - queryvalue_neurons\n layer_count_queryonly = [int(x.split(\"_\")[0]) for x in list(queryonly_neurons)]\n layer_count_queryonly = Counter(layer_count_queryonly)\n layer_count_queryonly = sorted(zip(layer_count_queryonly.keys(), layer_count_queryonly.values()))\n gpt_queryonly_x, gpt_queryonly_y = transfer_l(layer_count_queryonly)\n layer_count_queryvalue = [int(x.split(\"_\")[0]) for x in list(queryvalue_neurons)]\n layer_count_queryvalue = Counter(layer_count_queryvalue)\n layer_count_queryvalue = sorted(zip(layer_count_queryvalue.keys(), layer_count_queryvalue.values()))\n gpt_queryvalue_x, gpt_queryvalue_y = transfer_l(layer_count_queryvalue)\n curfile_ffn_score_dict = {}\n l_h_n_p = \"21_19_7_1\"\n attn_layer, attn_head, attn_neuron, attn_pos = l_h_n_p.split(\"_\")\n attn_layer, attn_head, attn_neuron, attn_pos = int(attn_layer), int(attn_head), int(attn_neuron), int(attn_pos)\n cur_attn_neuron = attn_head*HEAD_DIM+attn_neuron\n attn_neuron_key = model.transformer.h[attn_layer].attn.c_attn.weight.data[:, 2560:][:, cur_attn_neuron]\n attn_neuron_key_new = attn_neuron_key * model.transformer.h[attn_layer].ln_1.weight.data\n cur_inner_all = torch.sum(torch.tensor(all_pos_layer_input[attn_layer][attn_pos])*attn_neuron_key_new, -1)\n for layer_i in range(attn_layer):\n cur_layer_neurons = (torch.tensor(all_pos_coefficient_scores[layer_i][attn_pos])*get_fc2_params(model, layer_i)).T\n cur_layer_neurons_innerproduct = torch.sum(cur_layer_neurons * attn_neuron_key_new, -1)/cur_inner_all\n for neuron_i in range(len(cur_layer_neurons_innerproduct)):\n if str(layer_i)+\"_\"+str(neuron_i) not in curfile_ffn_score_dict:\n curfile_ffn_score_dict[str(layer_i)+\"_\"+str(neuron_i)] = 0.0\n curfile_ffn_score_dict[str(layer_i)+\"_\"+str(neuron_i)] += cur_layer_neurons_innerproduct[neuron_i].item() * increase_score\n cur_file_neurons_ffn_zip = list(zip(curfile_ffn_score_dict.keys(), curfile_ffn_score_dict.values()))\n cur_file_neurons_ffn_zip_sort = sorted(cur_file_neurons_ffn_zip, key=lambda x: x[-1])[::-1]\n for x in cur_file_neurons_ffn_zip_sort[:10]:\n print(x[0], round(x[1], 4))\n layer = int(x[0].split(\"_\")[0])\n neuron = int(x[0].split(\"_\")[1])\n cur_vector = get_fc2_params(model, layer).T[neuron]\n cur_vector_bsvalue = get_bsvalues(cur_vector, model, final_var)\n cur_vector_bsvalue_sort = torch.argsort(cur_vector_bsvalue, descending=True)\n print(\"top10: \", [tokenizer.decode(a) for a in cur_vector_bsvalue_sort[:10]])\n print(\"last10: \", [tokenizer.decode(a) for a in cur_vector_bsvalue_sort[-10:]])\n attn_layer, attn_head, attn_neuron, attn_pos = l_h_n_p.split(\"_\")\n attn_layer, attn_head, attn_neuron, attn_pos = int(attn_layer), int(attn_head), int(attn_neuron), int(attn_pos)\n test_query_neuron = \"0_1984\"\n test_query_layer, test_query_index = test_query_neuron.split(\"_\")\n test_query_layer, test_query_index = int(test_query_layer), int(test_query_index)\n cur_neuron_vector = get_fc2_params(model, test_query_layer).T[test_query_index]\n cur_neuron_vector_ln = model.transformer.h[attn_layer].ln_1(cur_neuron_vector)\n cur_neuron_v = model.transformer.h[attn_layer].attn.c_attn(\n cur_neuron_vector_ln)[2560:][attn_head*HEAD_DIM:attn_head*HEAD_DIM+HEAD_DIM]\n cur_attn_o_split = model.transformer.h[attn_layer].attn.c_proj.weight.data.view(\n HEAD_NUM, HEAD_DIM, -1)[attn_head]\n cur_neuron_vo = torch.sum(cur_neuron_v.unsqueeze(1)*cur_attn_o_split, 0)\n cur_neuron_o_bsvalues = get_bsvalues(cur_neuron_vo, model, final_var)\n cur_neuron_o_bsvalues_sort = torch.argsort(cur_neuron_o_bsvalues, descending=True)\n print(\"top: \", [tokenizer.decode(x) for x in cur_neuron_o_bsvalues_sort[:10]])\n print(\"last: \", [tokenizer.decode(x) for x in cur_neuron_o_bsvalues_sort[-10:]])" }, { "task_id": 2, "indent": 1, "script": "\npython GPT2_view_knowledge.py\n", "latex_code": "\n\\subsection{Importance Score for \"Query Neurons\"}\nAs discussed in Section 3.3, the proposed attribution methods can effectively identify the \"value neurons\" containing crucial information for the final prediction. However, in addition to these \"value neurons\", there exist \"query neurons\" that aid in activating these neurons, even if they may not directly contain information about $w$. In this section, we propose a static method to identify these \"query neurons\" based on Eq.1, Eq.5, and Eq.6. Since the $fc2$ vectors do not change, the coefficient scores are the only varying element in different cases. For each \"value neuron\", we can compute the inner product between its subkey (see Eq.6) and each neuron/subvector within the residual output (see Eq.1). Despite the presence of a nonlinear function $\\sigma$ for computing the coefficient score, it usually does not affect the relative value between different neurons/subvectors. Therefore, if a \"query\" neuron/subvector exhibits a larger inner product with the subkey compared to another one, it is more helpful for activating the \"value neuron\".\n", "completion_path": "./GPT2_view_knowledge.py", "namespace": "GPT2_view_knowledge.find_query_layer", "type": "function", "signature_position": [ 82, 82 ], "body_position": [ 83, 100 ], "ReferenceCode_With_Comments": "\nall_residual_scores = [0.0]*(1+2*LAYER_NUM)\n\nfor l_n, increase_score in ffn_subvalue_list_sort[:100]:\n\n\n ffn_layer, ffn_neuron = l_n.split(\"_\")\n ffn_layer, ffn_neuron = int(ffn_layer), int(ffn_neuron)\n\n # -----------------------------------------------------------------------\n # Snippet 1: Retrieve and adjust the FFN neuron's key vector by incorporating layer\n # normalization weights, aligning with the computation of subkeys for inner product\n # calculations as described in the methodology.\n # -----------------------------------------------------------------------\n # [Begin Snippet 1]\n ffn_neuron_key = model.transformer.h[ffn_layer].mlp.c_fc.weight.data[:, ffn_neuron]\n ffn_neuron_key_new = ffn_neuron_key * model.transformer.h[ffn_layer].ln_2.weight.data\n # [End Snippet 1]\n\n # -----------------------------------------------------------------------\n # Snippet 2: Construct the residual stream by aggregating inputs and outputs up to the\n # current FFN layer, preparing the data for inner product computations with the subkey.\n # This setup mirrors the residual output aggregation mentioned in Eq.1.\n # -----------------------------------------------------------------------\n # [Begin Snippet 2]\n last_layer_residualstream = [torch.tensor(all_pos_layer_input[0][-1]).unsqueeze(0)]\n for layer_i in range(ffn_layer):\n last_layer_residualstream.append(torch.tensor(all_pos_attn_output[layer_i][-1]).unsqueeze(0))\n last_layer_residualstream.append(torch.tensor(all_pos_ffn_output[layer_i][-1]).unsqueeze(0))\n last_layer_residualstream.append(torch.tensor(all_pos_attn_output[ffn_layer][-1]).unsqueeze(0))\n # [End Snippet 2]\n\n # -----------------------------------------------------------------------\n # Snippet 3: Calculate the sum of all inner product values to normalize individual scores,\n # ensuring that the contribution of each residual stream is proportionally scaled.\n # This normalization step aligns with the relative scoring mechanism described.\n # -----------------------------------------------------------------------\n # [Begin Snippet 3]\n last_layer_residualstream_cat = torch.cat(last_layer_residualstream, 0)\n last_layer_residualstream_innerproduct = torch.sum(last_layer_residualstream_cat*ffn_neuron_key_new, -1)\n last_layer_residualstream_innerproduct_zip = list(zip(range(len(last_layer_residualstream_innerproduct)), last_layer_residualstream_innerproduct.tolist()))\n sum_inner_product = sum([x[1] for x in last_layer_residualstream_innerproduct_zip])\n # [End Snippet 3]\n\n # -----------------------------------------------------------------------\n # Snippet 4: Update the residual scores by adding the normalized inner product multiplied\n # by the increase score for each residual stream segment, effectively aggregating\n # the importance contributions as outlined in the scoring methodology.\n # -----------------------------------------------------------------------\n # [Begin Snippet 4]\n for l, inner in last_layer_residualstream_innerproduct_zip:\n all_residual_scores[l] += inner/sum_inner_product * increase_score\n # [End Snippet 4]\n\nreturn all_residual_scores\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - There is no mention in the LaTeX description of constructing a cumulative residual stream up to a specific layer for each value neuron under consideration. The workflow for this step involves starting with the initial input to the model, then iteratively adding the outputs of attention and feed-forward computations from all preceding layers, and finally including the attention output of the current layer. This aggregated stream is essential for evaluating the combined influence of all prior computations on the activation of the value neuron.\n - The LaTeX description omits the step of normalizing the computed interaction scores between residual streams and value neuron vectors before aggregating them into final importance scores. The workflow here involves calculating the total sum of interaction values across all residual components, then dividing each individual interaction by this sum to obtain a relative contribution. These normalized values are subsequently scaled by an importance factor and accumulated into a fixed-size score list, ensuring the scores reflect proportional influence rather than raw magnitudes.\n - The process of limiting the analysis to a subset of the most significant value neurons based on a predefined criterion (e.g., top 100 by some metric) is not described in the LaTeX code. The workflow entails sorting a list of value neurons by their associated importance values, selecting only the top entries, and then proceeding with the scoring process for these selected neurons exclusively. This filtering step is crucial for focusing the analysis on the most impactful neurons.\n\n Mismatched Details:\n - None\n", "Missing_details": [ "\n- There is no mention in the LaTeX description of constructing a cumulative residual stream up to a specific layer for each value neuron under consideration. The workflow for this step involves starting with the initial input to the model, then iteratively adding the outputs of attention and feed-forward computations from all preceding layers, and finally including the attention output of the current layer. This aggregated stream is essential for evaluating the combined influence of all prior computations on the activation of the value neuron.\n", "\n- The LaTeX description omits the step of normalizing the computed interaction scores between residual streams and value neuron vectors before aggregating them into final importance scores. The workflow here involves calculating the total sum of interaction values across all residual components, then dividing each individual interaction by this sum to obtain a relative contribution. These normalized values are subsequently scaled by an importance factor and accumulated into a fixed-size score list, ensuring the scores reflect proportional influence rather than raw magnitudes.\n", "\n- The process of limiting the analysis to a subset of the most significant value neurons based on a predefined criterion (e.g., top 100 by some metric) is not described in the LaTeX code. The workflow entails sorting a list of value neurons by their associated importance values, selecting only the top entries, and then proceeding with the scoring process for these selected neurons exclusively. This filtering step is crucial for focusing the analysis on the most impactful neurons.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - model (An object of modeling_gpt2.GPT2LMHeadModel): \n The neural network model containing transformer layers and associated parameters.\n - all_pos_layer_input (list[list[list[float]]], [num_layers, seq_len, num_neurons]): \n Collection of input tensors for each layer, representing the positional inputs.\n - all_pos_attn_output (list[list[list[float]]], [num_layers, seq_len, num_neurons]): \n Collection of attention output tensors for each layer.\n - all_pos_ffn_output (list[list[list[float]]], [num_layers, seq_len, num_neurons]): \n Collection of feed-forward network (FFN) output tensors for each layer.\n - all_pos_residual_output (list[list[list[float]]], [num_layers, seq_len, num_neurons]):\n The residual outputs at different layers for all input tokens.\n", "Arguments_list": [ { "name": "model", "string": "\n- model (An object of modeling_gpt2.GPT2LMHeadModel):\n The neural network model containing transformer layers and associated parameters.\n", "dependency": "modeling_gpt2.GPT2LMHeadModel" }, { "name": "all_pos_layer_input", "string": "\n- all_pos_layer_input (list[list[list[float]]], [num_layers, seq_len, num_neurons]):\n Collection of input tensors for each layer, representing the positional inputs.\n", "dependency": null }, { "name": "all_pos_attn_output", "string": "\n- all_pos_attn_output (list[list[list[float]]], [num_layers, seq_len, num_neurons]):\n Collection of attention output tensors for each layer.\n", "dependency": null }, { "name": "all_pos_ffn_output", "string": "\n- all_pos_ffn_output (list[list[list[float]]], [num_layers, seq_len, num_neurons]):\n Collection of feed-forward network (FFN) output tensors for each layer.\n", "dependency": null }, { "name": "all_pos_residual_output", "string": "\n- all_pos_residual_output (list[list[list[float]]], [num_layers, seq_len, num_neurons]):\n The residual outputs at different layers for all input tokens.\n", "dependency": null } ] }, "dependency": { "string": "\nRepository Dependencies: \n - Intra File Dependencies: \n - None\n\n - Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.tensor\n - torch.sum\n - torch.cat\n", "list": [ "torch.tensor", "torch.sum", "torch.cat" ] }, "Return": { "Return_String": "\nOutput Variables:\n - all_residual_scores (list[floats]): \n A list containing the aggregated importance scores for each residual stream across layers.\n These scores indicate the significance of each residual stream in activating the corresponding\n value neurons.\n", "Return_list": [ { "name": "all_residual_scores", "string": "\n- all_residual_scores (list[floats]):\n A list containing the aggregated importance scores for each residual stream across layers.\n These scores indicate the significance of each residual stream in activating the corresponding\n value neurons.\n", "dependency": null } ] }, "ori_python_file": "import torch\nfrom collections import Counter\nfrom transformers import GPT2Tokenizer\nfrom modeling_gpt2 import GPT2LMHeadModel\nLAYER_NUM = 36\nHEAD_NUM = 20\nHEAD_DIM = 64\nHIDDEN_DIM = HEAD_NUM * HEAD_DIM\ntorch.set_default_device(\"cuda\")\n\ndef transfer_output(model_output):\n all_pos_layer_input = []\n all_pos_attn_output = []\n all_pos_residual_output = []\n all_pos_ffn_output = []\n all_pos_layer_output = []\n all_last_attn_subvalues = []\n all_pos_coefficient_scores = []\n all_attn_scores = []\n for layer_i in range(LAYER_NUM):\n cur_layer_input = model_output[layer_i][0]\n cur_attn_output = model_output[layer_i][1]\n cur_residual_output = model_output[layer_i][2]\n cur_ffn_output = model_output[layer_i][3]\n cur_layer_output = model_output[layer_i][4]\n cur_last_attn_subvalues = model_output[layer_i][5]\n cur_coefficient_scores = model_output[layer_i][6]\n cur_attn_weights = model_output[layer_i][7]\n all_pos_layer_input.append(cur_layer_input[0].tolist())\n all_pos_attn_output.append(cur_attn_output[0].tolist())\n all_pos_residual_output.append(cur_residual_output[0].tolist())\n all_pos_ffn_output.append(cur_ffn_output[0].tolist())\n all_pos_layer_output.append(cur_layer_output[0].tolist())\n all_last_attn_subvalues.append(cur_last_attn_subvalues[0].tolist())\n all_pos_coefficient_scores.append(cur_coefficient_scores[0].tolist())\n all_attn_scores.append(cur_attn_weights)\n return all_pos_layer_input, all_pos_attn_output, all_pos_residual_output, all_pos_ffn_output, all_pos_layer_output, all_last_attn_subvalues, all_pos_coefficient_scores, all_attn_scores\n\ndef get_bsvalues(vector, model, final_var):\n E = torch.mean(vector, -1)\n vector_ln = (vector - E.unsqueeze(-1)) / final_var * model.transformer.ln_f.weight.data\n vector_bsvalues = model.lm_head(vector_ln).data\n return vector_bsvalues\n\ndef get_prob(vector):\n prob = torch.nn.Softmax(-1)(vector)\n return prob\n\ndef get_fc2_params(model, layer_num):\n return model.transformer.h[layer_num].mlp.c_proj.weight.data.T\n\ndef transfer_l(l):\n new_x, new_y = [], []\n for x in l:\n new_x.append(x[0])\n new_y.append(x[1])\n return new_x, new_y\n\ndef FFN_neuron(model, all_pos_coefficient_scores, all_pos_residual_output, final_var, predict_index):\n all_ffn_subvalues = []\n for layer_i in range(LAYER_NUM):\n coefficient_scores = torch.tensor(all_pos_coefficient_scores[layer_i][-1])\n fc2_vectors = get_fc2_params(model, layer_i)\n ffn_subvalues = (coefficient_scores * fc2_vectors).T\n all_ffn_subvalues.append(ffn_subvalues)\n ffn_subvalue_list = []\n for layer_i in range(LAYER_NUM):\n cur_ffn_subvalues = all_ffn_subvalues[layer_i]\n cur_residual = torch.tensor(all_pos_residual_output[layer_i][-1])\n origin_prob_log = torch.log(get_prob(get_bsvalues(cur_residual, model, final_var))[predict_index])\n cur_ffn_subvalues_plus = cur_ffn_subvalues + cur_residual\n cur_ffn_subvalues_bsvalues = get_bsvalues(cur_ffn_subvalues_plus, model, final_var)\n cur_ffn_subvalues_probs = get_prob(cur_ffn_subvalues_bsvalues)\n cur_ffn_subvalues_probs = cur_ffn_subvalues_probs[:, predict_index]\n cur_ffn_subvalues_probs_log = torch.log(cur_ffn_subvalues_probs)\n cur_ffn_subvalues_probs_log_increase = cur_ffn_subvalues_probs_log - origin_prob_log\n for index, ffn_increase in enumerate(cur_ffn_subvalues_probs_log_increase):\n ffn_subvalue_list.append([str(layer_i)+\"_\"+str(index), ffn_increase.item()])\n ffn_subvalue_list_sort = sorted(ffn_subvalue_list, key=lambda x: x[-1])[::-1]\n return ffn_subvalue_list_sort\n\ndef find_query_layer(model, all_pos_layer_input, all_pos_attn_output, all_pos_ffn_output, ffn_subvalue_list_sort):\n all_residual_scores = [0.0]*(1+2*LAYER_NUM)\n for l_n, increase_score in ffn_subvalue_list_sort[:100]:\n ffn_layer, ffn_neuron = l_n.split(\"_\")\n ffn_layer, ffn_neuron = int(ffn_layer), int(ffn_neuron)\n ffn_neuron_key = model.transformer.h[ffn_layer].mlp.c_fc.weight.data[:, ffn_neuron]\n ffn_neuron_key_new = ffn_neuron_key * model.transformer.h[ffn_layer].ln_2.weight.data\n last_layer_residualstream = [torch.tensor(all_pos_layer_input[0][-1]).unsqueeze(0)]\n for layer_i in range(ffn_layer):\n last_layer_residualstream.append(torch.tensor(all_pos_attn_output[layer_i][-1]).unsqueeze(0))\n last_layer_residualstream.append(torch.tensor(all_pos_ffn_output[layer_i][-1]).unsqueeze(0))\n last_layer_residualstream.append(torch.tensor(all_pos_attn_output[ffn_layer][-1]).unsqueeze(0))\n last_layer_residualstream_cat = torch.cat(last_layer_residualstream, 0)\n last_layer_residualstream_innerproduct = torch.sum(last_layer_residualstream_cat*ffn_neuron_key_new, -1)\n last_layer_residualstream_innerproduct_zip = list(zip(range(len(last_layer_residualstream_innerproduct)), last_layer_residualstream_innerproduct.tolist()))\n sum_inner_product = sum([x[1] for x in last_layer_residualstream_innerproduct_zip])\n for l, inner in last_layer_residualstream_innerproduct_zip:\n all_residual_scores[l] += inner/sum_inner_product * increase_score\n return all_residual_scores\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n modelname = \"gpt2-large\"\n tokenizer = GPT2Tokenizer.from_pretrained(modelname)\n model = GPT2LMHeadModel.from_pretrained(modelname)\n model.eval()\n model.cuda()\n test_sentence = \"Tim Duncan plays the sport of\"\n indexed_tokens = tokenizer.encode(test_sentence)\n tokens = [tokenizer.decode(x) for x in indexed_tokens]\n tokens_tensor = torch.tensor([indexed_tokens])\n with torch.no_grad():\n outputs = model(tokens_tensor)\n predictions = outputs[0]\n predicted_top10 = torch.argsort(predictions[0][-1], descending=True)[:10]\n predicted_text = [tokenizer.decode(x) for x in predicted_top10]\n print(test_sentence, \"=>\", predicted_text)\n all_pos_layer_input, all_pos_attn_output, all_pos_residual_output, all_pos_ffn_output, all_pos_layer_output, all_last_attn_subvalues, all_pos_coefficient_scores, all_attn_scores = transfer_output(outputs[1])\n final_var = ((torch.var(torch.tensor(all_pos_layer_output[-1][-1]), -1, unbiased=False)+1e-5)**0.5).item()\n pos_len = len(tokens)\n print(tokens)\n predict_index = predicted_top10[0].item()\n print(predict_index, tokenizer.decode(predict_index))\n ffn_subvalue_list_sort = FFN_neuron(model, all_pos_coefficient_scores, all_pos_residual_output, final_var, predict_index)\n cur_file_attn_neuron_list = []\n for test_layer in range(LAYER_NUM):\n cur_layer_input = torch.tensor(all_pos_layer_input[test_layer])\n cur_v_heads_recompute = torch.tensor(all_last_attn_subvalues[test_layer]).permute(1, 0, 2)\n cur_attn_o_split = model.transformer.h[test_layer].attn.c_proj.weight.data.view(HEAD_NUM, HEAD_DIM, -1)\n cur_attn_o_recompute = cur_attn_o_split * cur_v_heads_recompute.unsqueeze(-1)\n cur_layer_input_last = cur_layer_input[-1]\n origin_prob = torch.log(get_prob(get_bsvalues(cur_layer_input_last, model, final_var))[predict_index])\n cur_attn_o_head_plus = cur_attn_o_recompute + cur_layer_input_last\n cur_attn_plus_probs = torch.log(get_prob(get_bsvalues(\n cur_attn_o_head_plus, model, final_var))[:, :, :, predict_index])\n cur_attn_plus_probs_increase = cur_attn_plus_probs - origin_prob\n for pos_index in range(cur_attn_plus_probs_increase.size(0)):\n for head_index in range(cur_attn_plus_probs_increase.size(1)):\n for attn_neuron_index in range(cur_attn_plus_probs_increase.size(2)):\n cur_file_attn_neuron_list.append((str(test_layer)+\"_\"+str(head_index)+\"_\"+str(\n attn_neuron_index)+\"_\"+str(pos_index),\n cur_attn_plus_probs_increase[pos_index][head_index][attn_neuron_index].item()))\n cur_file_attn_neuron_list_sort = sorted(cur_file_attn_neuron_list, key=lambda x: x[-1])[::-1]\n print(list(zip(range(len(tokens)), tokens)))\n for x in cur_file_attn_neuron_list_sort[:10]:\n layer_i, head_i, neuron_i, _ = x[0].split(\"_\")\n layer_i, head_i, neuron_i = int(layer_i), int(head_i), int(neuron_i)\n cur_neuron = model.transformer.h[layer_i].attn.c_proj.weight.data.view(HEAD_NUM, HEAD_DIM, -1)[head_i][neuron_i]\n cur_neuron_bsvalue = get_bsvalues(cur_neuron, model, final_var)\n cur_neuron_bsvalue_sort = torch.argsort(cur_neuron_bsvalue, descending=True)\n print(x[0], round(x[1], 4), \"top10: \", [tokenizer.decode(a) for a in cur_neuron_bsvalue_sort[:10]])\n print(x[0], round(x[1], 4), \"last10: \", [tokenizer.decode(a) for a in cur_neuron_bsvalue_sort[-10:]])\n attn_value_neurons = [x[0] for x in cur_file_attn_neuron_list_sort[:300]]\n attn_layer_count_value = [int(x.split(\"_\")[0]) for x in list(attn_value_neurons)]\n attn_layer_count_value = Counter(attn_layer_count_value)\n attn_layer_count_value = sorted(zip(attn_layer_count_value.keys(), attn_layer_count_value.values()))\n gpt_attn_value_x, gpt_attn_value_y = transfer_l(attn_layer_count_value)\n all_residual_scores = [0.0]*(1+2*LAYER_NUM)\n for l_n, increase_score in ffn_subvalue_list_sort[:100]:\n ffn_layer, ffn_neuron = l_n.split(\"_\")\n ffn_layer, ffn_neuron = int(ffn_layer), int(ffn_neuron)\n ffn_neuron_key = model.transformer.h[ffn_layer].mlp.c_fc.weight.data[:, ffn_neuron]\n ffn_neuron_key_new = ffn_neuron_key * model.transformer.h[ffn_layer].ln_2.weight.data\n last_layer_residualstream = [torch.tensor(all_pos_layer_input[0][-1]).unsqueeze(0)]\n for layer_i in range(ffn_layer):\n last_layer_residualstream.append(torch.tensor(all_pos_attn_output[layer_i][-1]).unsqueeze(0))\n last_layer_residualstream.append(torch.tensor(all_pos_ffn_output[layer_i][-1]).unsqueeze(0))\n last_layer_residualstream.append(torch.tensor(all_pos_attn_output[ffn_layer][-1]).unsqueeze(0))\n last_layer_residualstream_cat = torch.cat(last_layer_residualstream, 0)\n last_layer_residualstream_innerproduct = torch.sum(last_layer_residualstream_cat*ffn_neuron_key_new, -1)\n last_layer_residualstream_innerproduct_zip = list(zip(range(len(last_layer_residualstream_innerproduct)), last_layer_residualstream_innerproduct.tolist()))\n sum_inner_product = sum([x[1] for x in last_layer_residualstream_innerproduct_zip])\n for l, inner in last_layer_residualstream_innerproduct_zip:\n all_residual_scores[l] += inner/sum_inner_product * increase_score\n all_residual_scores_zip = list(zip(range(len(all_residual_scores)), all_residual_scores))\n all_residual_scores_zip_sort = sorted(all_residual_scores_zip, key=lambda x: x[-1])[::-1]\n print([(a[0]/2-0.5, round(a[1],4)) for a in all_residual_scores_zip_sort])\n all_residual_scores = find_query_layer(model, all_pos_layer_input, all_pos_attn_output, all_pos_ffn_output, ffn_subvalue_list_sort)\n curfile_ffn_score_dict = {}\n for l_h_n_p, increase_score in cur_file_attn_neuron_list_sort[:30]:\n attn_layer, attn_head, attn_neuron, attn_pos = l_h_n_p.split(\"_\")\n attn_layer, attn_head, attn_neuron, attn_pos = int(attn_layer), int(attn_head), int(attn_neuron), int(attn_pos)\n cur_attn_neuron = attn_head*HEAD_DIM+attn_neuron\n attn_neuron_key = model.transformer.h[attn_layer].attn.c_attn.weight.data[:, 2560:][:, cur_attn_neuron]\n attn_neuron_key_new = attn_neuron_key * model.transformer.h[attn_layer].ln_1.weight.data\n cur_inner_all = torch.sum(torch.tensor(all_pos_layer_input[attn_layer][attn_pos])*attn_neuron_key_new, -1)\n for layer_i in range(attn_layer):\n cur_layer_neurons = (torch.tensor(all_pos_coefficient_scores[layer_i][attn_pos])*get_fc2_params(model, layer_i)).T\n cur_layer_neurons_innerproduct = torch.sum(cur_layer_neurons * attn_neuron_key_new, -1)/cur_inner_all\n for neuron_i in range(len(cur_layer_neurons_innerproduct)):\n if str(layer_i)+\"_\"+str(neuron_i) not in curfile_ffn_score_dict:\n curfile_ffn_score_dict[str(layer_i)+\"_\"+str(neuron_i)] = 0.0\n curfile_ffn_score_dict[str(layer_i)+\"_\"+str(neuron_i)] += cur_layer_neurons_innerproduct[neuron_i].item() * increase_score\n cur_file_neurons_ffn_zip = list(zip(curfile_ffn_score_dict.keys(), curfile_ffn_score_dict.values()))\n cur_file_neurons_ffn_zip_sort = sorted(cur_file_neurons_ffn_zip, key=lambda x: x[-1])[::-1]\n for x in cur_file_neurons_ffn_zip_sort[:10]:\n print(x[0], round(x[1], 4))\n layer = int(x[0].split(\"_\")[0])\n neuron = int(x[0].split(\"_\")[1])\n cur_vector = get_fc2_params(model, layer).T[neuron]\n cur_vector_bsvalue = get_bsvalues(cur_vector, model, final_var)\n cur_vector_bsvalue_sort = torch.argsort(cur_vector_bsvalue, descending=True)\n print(\"top10: \", [tokenizer.decode(a) for a in cur_vector_bsvalue_sort[:10]])\n print(\"last10: \", [tokenizer.decode(a) for a in cur_vector_bsvalue_sort[-10:]])\n value_neurons = [x[0] for x in ffn_subvalue_list_sort[:300]]\n query_neurons = [x[0] for x in cur_file_neurons_ffn_zip_sort[:300]]\n queryvalue_neurons = set(value_neurons) & set(query_neurons)\n queryonly_neurons = set(query_neurons) - queryvalue_neurons\n layer_count_queryonly = [int(x.split(\"_\")[0]) for x in list(queryonly_neurons)]\n layer_count_queryonly = Counter(layer_count_queryonly)\n layer_count_queryonly = sorted(zip(layer_count_queryonly.keys(), layer_count_queryonly.values()))\n gpt_queryonly_x, gpt_queryonly_y = transfer_l(layer_count_queryonly)\n layer_count_queryvalue = [int(x.split(\"_\")[0]) for x in list(queryvalue_neurons)]\n layer_count_queryvalue = Counter(layer_count_queryvalue)\n layer_count_queryvalue = sorted(zip(layer_count_queryvalue.keys(), layer_count_queryvalue.values()))\n gpt_queryvalue_x, gpt_queryvalue_y = transfer_l(layer_count_queryvalue)\n curfile_ffn_score_dict = {}\n l_h_n_p = \"21_19_7_1\"\n attn_layer, attn_head, attn_neuron, attn_pos = l_h_n_p.split(\"_\")\n attn_layer, attn_head, attn_neuron, attn_pos = int(attn_layer), int(attn_head), int(attn_neuron), int(attn_pos)\n cur_attn_neuron = attn_head*HEAD_DIM+attn_neuron\n attn_neuron_key = model.transformer.h[attn_layer].attn.c_attn.weight.data[:, 2560:][:, cur_attn_neuron]\n attn_neuron_key_new = attn_neuron_key * model.transformer.h[attn_layer].ln_1.weight.data\n cur_inner_all = torch.sum(torch.tensor(all_pos_layer_input[attn_layer][attn_pos])*attn_neuron_key_new, -1)\n for layer_i in range(attn_layer):\n cur_layer_neurons = (torch.tensor(all_pos_coefficient_scores[layer_i][attn_pos])*get_fc2_params(model, layer_i)).T\n cur_layer_neurons_innerproduct = torch.sum(cur_layer_neurons * attn_neuron_key_new, -1)/cur_inner_all\n for neuron_i in range(len(cur_layer_neurons_innerproduct)):\n if str(layer_i)+\"_\"+str(neuron_i) not in curfile_ffn_score_dict:\n curfile_ffn_score_dict[str(layer_i)+\"_\"+str(neuron_i)] = 0.0\n curfile_ffn_score_dict[str(layer_i)+\"_\"+str(neuron_i)] += cur_layer_neurons_innerproduct[neuron_i].item() * increase_score\n cur_file_neurons_ffn_zip = list(zip(curfile_ffn_score_dict.keys(), curfile_ffn_score_dict.values()))\n cur_file_neurons_ffn_zip_sort = sorted(cur_file_neurons_ffn_zip, key=lambda x: x[-1])[::-1]\n for x in cur_file_neurons_ffn_zip_sort[:10]:\n print(x[0], round(x[1], 4))\n layer = int(x[0].split(\"_\")[0])\n neuron = int(x[0].split(\"_\")[1])\n cur_vector = get_fc2_params(model, layer).T[neuron]\n cur_vector_bsvalue = get_bsvalues(cur_vector, model, final_var)\n cur_vector_bsvalue_sort = torch.argsort(cur_vector_bsvalue, descending=True)\n print(\"top10: \", [tokenizer.decode(a) for a in cur_vector_bsvalue_sort[:10]])\n print(\"last10: \", [tokenizer.decode(a) for a in cur_vector_bsvalue_sort[-10:]])\n attn_layer, attn_head, attn_neuron, attn_pos = l_h_n_p.split(\"_\")\n attn_layer, attn_head, attn_neuron, attn_pos = int(attn_layer), int(attn_head), int(attn_neuron), int(attn_pos)\n test_query_neuron = \"0_1984\"\n test_query_layer, test_query_index = test_query_neuron.split(\"_\")\n test_query_layer, test_query_index = int(test_query_layer), int(test_query_index)\n cur_neuron_vector = get_fc2_params(model, test_query_layer).T[test_query_index]\n cur_neuron_vector_ln = model.transformer.h[attn_layer].ln_1(cur_neuron_vector)\n cur_neuron_v = model.transformer.h[attn_layer].attn.c_attn(\n cur_neuron_vector_ln)[2560:][attn_head*HEAD_DIM:attn_head*HEAD_DIM+HEAD_DIM]\n cur_attn_o_split = model.transformer.h[attn_layer].attn.c_proj.weight.data.view(\n HEAD_NUM, HEAD_DIM, -1)[attn_head]\n cur_neuron_vo = torch.sum(cur_neuron_v.unsqueeze(1)*cur_attn_o_split, 0)\n cur_neuron_o_bsvalues = get_bsvalues(cur_neuron_vo, model, final_var)\n cur_neuron_o_bsvalues_sort = torch.argsort(cur_neuron_o_bsvalues, descending=True)\n print(\"top: \", [tokenizer.decode(x) for x in cur_neuron_o_bsvalues_sort[:10]])\n print(\"last: \", [tokenizer.decode(x) for x in cur_neuron_o_bsvalues_sort[-10:]])" } ] }, { "paper_id": 21, "paper_details": { "title": "RaTEScore: A Metric for Radiology Report Generation", "url": "https://arxiv.org/abs/2406.16845" }, "enviorment_name": "ratescore", "repo_original_url": "https://angelakeke.github.io/RaTEScore/", "project_path": "Benchmark/21-RaTEScore-main/RaTEScore-main", "file_organization": "\nRaTEScore-main/\n affinity_matrix/\n long_weight.json\n short_weight.json\n RaTEScore/\n __init__.py\n score.py\n scorer.py\n utils.py\n LICENSE\n README.md\n setup.py\n", "latex_code_path": "Benchmark/21-RaTEScore-main/arXiv-2406.16845v2", "task_details": [ { "task_id": 0, "indent": 1, "script": "\npython main.py\n", "latex_code": "\n\\subsection{Scoring Procedure}\n\\label{subsec:score}\nUpon obtaining the encoded entity set from each decomposed radiological report, \nwe proceed to the final scoring procedure. We first define the similarity metric between a candidate entity and a reference report, that is established by selecting an entity from the referenced text based on the cosine similarity of their name embeddings:\n\\begin{equation}\ni^* = \\arg\\max_{i \\leq M} \\cos(f_i, \\hat{f}_j)\n\\end{equation}\nwhere $\\cos(f_i, \\hat{f}_j)$ measures the cosine similarity between two entity name embeddings. The entity $e_{i^*}$, which best matches $\\hat{e}_j$ from the reference text, is chosen for further comparison.\nThe overall similarity score, $S(x, \\hat{x})$, is then computed as follows:\n\\vspace{-5pt}\n\\begin{equation}\n S(x, \\hat{x}) = \\frac{\\sum_j{W(t_{i^*}, t_j}) \\cdot \\text{sim}(e_{i^*}, \\hat{e}_j) }{\\sum_j{W(t_{i^*}, t_j)}}\n\\end{equation}\nHere, $W$ is a learnable $5 \\times 5$ affinity matrix between the five entity types, where $W(t_i, t_j)$ represents an element of the matrix, \nand $\\text{sim}(e_{i}, \\hat{e}_j)$ is an entity-wise similarity function, defined as:\n\\vspace{-5pt}\n\\begin{equation}\n \\text{sim}(e_{i}, \\hat{e}_j) = \\left \\{\n \\begin{aligned}\n {p} \\cos(f_{i}, \\hat{f}_j), \\quad if \\quad t_{i} \\neq t_j \\\\\n \\cos(f_{i}, \\hat{f}_j), \\quad if \\quad t_{i}=t_j\n \\end{aligned}\n \\right. \n\\end{equation}\nwhere we generally follow the cosine similarity on the name embedding,\nwith a learnable penalty value $p$ to punish the type mismatch.\nFor example, when comparing entities with identical names but different types\u2014such as (`pleural effusion', `Abnormality') and (`pleural effusion', `Non-Abnormality')\u2014the penalty term $p$ is applied to adjust the similarity score appropriately.\n\nAdditionally, the similarity between different entity types may be weighted differently in medical scenarios due to their clinical significance. For example, the similarity between two `Abnormality' entities is of much greater importance than the similarity between two `Non-abnormality' entities. This is because all body parts are assumed to be normal in radiology reports by default, and minor expression errors in normal findings will not critically impact the report's correctness. Therefore, we introduce $W$ to account for this clinical relevance.\n", "completion_path": "./RaTEScore/utils.py", "namespace": "RaTEScore.utils.compute", "type": "function", "signature_position": [ 76, 76 ], "body_position": [ 77, 92 ], "ReferenceCode_With_Comments": "\n# ----------------------------------------------------------------------------\n# Snippet 1: The function begins by referencing eq. (1) from the LaTeX, where\n# the cosine similarity metric \\cos(f_i, \\hat{f}_j) is crucial. Here, we\n# prepare for that computation by normalizing the embeddings, mapping to\n# the concept of sim(...) on name embeddings in eq. (3).\n# ----------------------------------------------------------------------------\n# [Begin Snippet 1]\ngt_embeds_word = F.normalize(gt_embeds_word, p=2, dim=1)\npred_embeds_word = F.normalize(pred_embeds_word, p=2, dim=1)\n# [End Snippet 1]\n\n# ----------------------------------------------------------------------------\n# Snippet 2: We compute the pairwise cosine similarities using a matrix\n# multiplication approach, reflecting \\cos(f_i, \\hat{f}_j) for all i and j,\n# consistent with the LaTeX statement that measures entity name embedding\n# similarity. This corresponds to eq. (1) before selecting i^*.\n# ----------------------------------------------------------------------------\n# [Begin Snippet 2]\nsimilarities = torch.matmul(gt_embeds_word, pred_embeds_word.T)\n# [End Snippet 2]\n\n# ----------------------------------------------------------------------------\n# Snippet 3: According to eq. (1) in the LaTeX, i^* is determined by the\n# maximum similarity. Here, we find the top-1 index for each ground\n# truth embedding, mirroring the argmax operation \\arg\\max_{i} \\cos(f_i, \\hat{f}_j).\n# ----------------------------------------------------------------------------\n# [Begin Snippet 3]\ntopk_values, topk_indices = torch.topk(similarities, k=1, dim=1, largest=True)\n# [End Snippet 3]\n\n# ----------------------------------------------------------------------------\n# Snippet 4: We then gather the predicted entity types associated with\n# the most similar embeddings. This step mirrors the selection of e_{i^*}\n# for further comparison in the LaTeX sub-section.\n# ----------------------------------------------------------------------------\n# [Begin Snippet 4]\ntopk_indices = topk_indices.squeeze(1).cpu().numpy().tolist()\ntopk_values = topk_values.squeeze(1).cpu().numpy().tolist()\ntopk_map = [pred_types[i] for i in topk_indices]\n# [End Snippet 4]\n\n# ----------------------------------------------------------------------------\n# Snippet 5: Here, we fetch the weight matrix values W(t_{i^*}, t_j) \n# and also define a penalty factor for type mismatches, reflecting in p.\n# This ensures that if t_{i} != t_j, the similarity is reduced proportionally.\n# ----------------------------------------------------------------------------\n# [Begin Snippet 5]\nweight_score = [weight_matrix.get((gt_type, pred_type), 0) for gt_type, pred_type in zip(gt_types, topk_map)]\ntype_score = [neg_weight if (gt_type, pred_type) in neg_class else 1 for gt_type, pred_type in zip(gt_types, topk_map)]\n# [End Snippet 5]\n\n# ----------------------------------------------------------------------------\n# Snippet 6: We now aggregate the individual similarity scores.\n# The numerator sums W(t_{i^*}, t_j) * sim(e_{i^*}, \\hat{e}_j), and we track the\n# sum of the weights in the denominator to compute the weighted average.\n# ----------------------------------------------------------------------------\n# [Begin Snippet 6]\nweighted_avg_score = 0\nweighted_sum = 0\nfor score, weight, type_factor in zip(topk_values, weight_score, type_score):\n weighted_avg_score += score * weight * type_factor\n weighted_sum += weight\n# [End Snippet 6]\n\n# ----------------------------------------------------------------------------\n# Snippet 7: Finally, we compute RaTE, analogous to S(x, \\hat{x})w.\n# If no valid weights are found, the score defaults to 0, preserving numerical stability.\n# ----------------------------------------------------------------------------\n# [Begin Snippet 7]\nRaTE = weighted_avg_score / weighted_sum if weighted_sum != 0 else 0\n\n\nreturn RaTE\n# [End Snippet 7]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - Explicit L2 normalization of embeddings before similarity calculation.\n - The LaTeX description does not specify the order of entity types when accessing the weight matrix W or applying the penalty. The reference code uses the (ground truth type, predicted type) order for both the weight matrix lookup and the penalty check in `neg_class`.\n - Handling of missing entries in the weight matrix. The LaTeX does not specify behavior for type pairs not present in the affinity matrix, while the reference code implicitly treats missing entries as 0 (exclusion from scoring) rather than using a default value.\n\n Mismatched Details:\n - LaTeX specifies learnable penalty p, but code uses fixed neg_weight.\n - Penalty application criteria. The LaTeX equation (3) applies penalty p when t_i \u2260 t_j (general type mismatch), but the reference code only applies penalties for specific (gt_type, pred_type) pairs defined in neg_class.\n", "Missing_details": [ "\n- Explicit L2 normalization of embeddings before similarity calculation.\n", "\n- The LaTeX description does not specify the order of entity types when accessing the weight matrix W or applying the penalty. The reference code uses the (ground truth type, predicted type) order for both the weight matrix lookup and the penalty check in `neg_class`.\n", "\n- Handling of missing entries in the weight matrix. The LaTeX does not specify behavior for type pairs not present in the affinity matrix, while the reference code implicitly treats missing entries as 0 (exclusion from scoring) rather than using a default value.\n" ], "Mismatched_details": [ "\n- LaTeX specifies learnable penalty p, but code uses fixed neg_weight.\n", "\n- Penalty application criteria. The LaTeX equation (3) applies penalty p when t_i \u2260 t_j (general type mismatch), but the reference code only applies penalties for specific (gt_type, pred_type) pairs defined in neg_class.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - gt_embeds_word (torch.Tensor, shape=[Num of truth entities, embedding_dim]): \n Ground truth entity name embeddings. \n - pred_embeds_word (torch.Tensor, shape=[Num of predicted entities, embedding_dim]): \n Predicted entity name embeddings.\n - gt_types (list[str]): \n List of ground truth entity types, each string representing a clinical or non-clinical category.\n - pred_types (list[str]): \n List of predicted entity types, aligned with pred_embeds_word.\n - weight_matrix (dict): \n Dictionary serving as the learnable 5x5 affinity matrix W from the LaTeX, mapping (type_i, type_j) to a numerical weight.\n - neg_class (list[tuple[str, str]]): \n Set of pairs (type_i, type_j) indicating type mismatches subject to a penalty factor.\n - neg_weight (float): \n Numerical penalty factor p to reduce similarity scores when (t_i != t_j).\n", "Arguments_list": [ { "name": "gt_embeds_word", "string": "\n- gt_embeds_word (torch.Tensor, shape=[Num of truth entities, embedding_dim]): \n Ground truth entity name embeddings. \n", "dependency": null }, { "name": "pred_embeds_word", "string": "\n- pred_embeds_word (torch.Tensor, shape=[Num of predicted entities, embedding_dim]): \n Predicted entity name embeddings.\n", "dependency": null }, { "name": "gt_types", "string": "\n- gt_types (list[str]):\n List of ground truth entity types, each string representing a clinical or non-clinical category.\n", "dependency": null }, { "name": "pred_types", "string": "\n- pred_types (list[str]):\n List of predicted entity types, aligned with pred_embeds_word.\n", "dependency": null }, { "name": "weight_matrix", "string": "\n- weight_matrix (dict):\n Dictionary serving as the learnable 5x5 affinity matrix W from the LaTeX, mapping (type_i, type_j) to a numerical weight.\n", "dependency": null }, { "name": "neg_class", "string": "\n- neg_class (list[tuple[str, str]]):\n Set of pairs (type_i, type_j) indicating type mismatches subject to a penalty factor.\n", "dependency": null }, { "name": "neg_weight", "string": "\n- neg_weight (float):\n Numerical penalty factor p to reduce similarity scores when (t_i != t_j).\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-File dependency: \n - None \n\n - Cross-File dependency: \n - None \n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.nn.functional.normalize\n - torch.matmul\n - torch.topk\n", "list": [ "torch.nn.functional.normalize", "torch.matmul", "torch.topk" ] }, "Return": { "Return_String": "\nOutput Variables:\n - RaTE (float): \n Final aggregated similarity score, analogous to S(x, \\hat{x}) in the LaTeX formulation.\n", "return_list": [ { "name": "RaTE", "string": "\n- RaTE (float):\n Final aggregated similarity score, analogous to S(x, \\hat{x}) in the LaTeX formulation.\n", "dependency": null } ] }, "ori_python_file": "import torch\nimport torch.nn.functional as F\nimport medspacy\nnlp = medspacy.load(medspacy_enable=[\"medspacy_pyrush\", \"medspacy_conte\"])\ndef sentence_split(text_list):\n clean_text_list = []\n is_start_list = []\n for text in text_list:\n doc = nlp(text)\n is_start = 1\n for sent in doc.sents:\n sent = str(sent).strip()\n if len(sent.split()) == 0:\n continue\n if len(sent) < 3:\n continue\n is_start_list.append(is_start)\n clean_text_list.append(sent)\n is_start = 0\n return clean_text_list, is_start_list\ndef post_process(tokenized_text, predicted_entities, tokenizer):\n entity_spans = []\n start = end = None\n entity_type = None\n for i, (token, label) in enumerate(zip(tokenized_text, predicted_entities[:len(tokenized_text)])):\n if token in [\"[CLS]\", \"[SEP]\"]:\n continue\n if label != \"O\" and i < len(predicted_entities) - 1:\n if label.startswith(\"B-\") and predicted_entities[i+1].startswith(\"I-\"):\n start = i\n entity_type = label[2:]\n elif label.startswith(\"B-\") and predicted_entities[i+1].startswith(\"B-\"):\n start = i\n end = i\n entity_spans.append((start, end, label[2:]))\n start = i\n entity_type = label[2:]\n elif label.startswith(\"B-\") and predicted_entities[i+1].startswith(\"O\"):\n start = i\n end = i\n entity_spans.append((start, end, label[2:]))\n start = end = None\n entity_type = None\n elif label.startswith(\"I-\") and predicted_entities[i+1].startswith(\"B-\"):\n end = i\n if start is not None:\n entity_spans.append((start, end, entity_type))\n start = i\n entity_type = label[2:]\n elif label.startswith(\"I-\") and predicted_entities[i+1].startswith(\"O\"):\n end = i\n if start is not None:\n entity_spans.append((start, end, entity_type))\n start = end = None\n entity_type = None\n if start is not None and end is None:\n end = len(tokenized_text) - 2\n entity_spans.append((start, end, entity_type))\n save_pair = []\n for start, end, entity_type in entity_spans:\n entity_str = tokenizer.convert_tokens_to_string(tokenized_text[start:end+1])\n save_pair.append((entity_str, entity_type))\n return save_pair\nneg_class = [\n ('NON-DISEASE', 'DISEASE'),\n ('NON-ABNORMALITY', 'ABNORMALITY'),\n ('DISEASE', 'NON-DISEASE'),\n ('ABNORMALITY', 'NON-ABNORMALITY'),\n ('NON-DISEASE', 'ABNORMALITY'),\n ('NON-ABNORMALITY', 'DISEASE'),\n ('DISEASE', 'NON-ABNORMALITY'),\n ('ABNORMALITY', 'NON-DISEASE'),\n]\nneg_weight = 0.3612\n\ndef compute(gt_embeds_word, pred_embeds_word, gt_types, pred_types, weight_matrix, neg_class=neg_class, neg_weight=neg_weight):\n gt_embeds_word = F.normalize(gt_embeds_word, p=2, dim=1)\n pred_embeds_word = F.normalize(pred_embeds_word, p=2, dim=1)\n similarities = torch.matmul(gt_embeds_word, pred_embeds_word.T)\n topk_values, topk_indices = torch.topk(similarities, k=1, dim=1, largest=True)\n topk_indices = topk_indices.squeeze(1).cpu().numpy().tolist()\n topk_values = topk_values.squeeze(1).cpu().numpy().tolist()\n topk_map = [pred_types[i] for i in topk_indices]\n weight_score = [weight_matrix.get((gt_type, pred_type), 0) for gt_type, pred_type in zip(gt_types, topk_map)]\n type_score = [neg_weight if (gt_type, pred_type) in neg_class else 1 for gt_type, pred_type in zip(gt_types, topk_map)]\n weighted_avg_score = 0\n weighted_sum = 0\n for score, weight, type_factor in zip(topk_values, weight_score, type_score):\n weighted_avg_score += score * weight * type_factor\n weighted_sum += weight\n RaTE = weighted_avg_score / weighted_sum if weighted_sum != 0 else 0\n return RaTE" }, { "task_id": 1, "indent": 2, "script": "\npython main.py\n", "latex_code": "\nFinally, due to the order of performing max indexing for selecting referenced entities and weighted sum pooling on all candidate entities, the final similarity metric $S(x,\\hat{x})$ does not comply with the commutative law. $S(x,\\hat{x})$ and $S(\\hat{x},x)$ can be analogous to precision and recall respectively. Thus, our final \\textbf{RaTEScore} is defined as the harmonic mean of $S(x,\\hat{x})$ and $S(\\hat{x},x)$, following classical F$_1$-score format:\n\\vspace{-5pt}\n\\[\n\\texttt{RaTEScore} = \n\\begin{cases} \n0,\\quad \\; \\ \\text{if } S(x,\\hat{x}) + S(\\hat{x},x) = 0, \\\\\n2 \\times \\frac{S(x,\\hat{x}) \\times S(\\hat{x},x)}{S(x,\\hat{x}) + S(\\hat{x},x)}, \\quad\\ \\text{otherwise}.\n\\end{cases}\n\\]\n", "completion_path": "./RaTEScore/scorer.py", "namespace": "RaTEScore.scorer.RaTEScore.compute_rate_score", "type": "method", "signature_position": [ 43, 43 ], "body_position": [ 44, 49 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Checks for empty ground truth or predicted embeddings to handle edge cases.\n# If either embeddings tensor is empty, a default RaTEScore of 0.5 is returned.\n# This ensures that the function gracefully handles scenarios with no data.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nif gt_embeds_word.size(0) == 0 or pred_embeds_word.size(0) == 0:\n return 0.5\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Computes the precision score by evaluating the similarity between \n# ground truth embeddings and predicted embeddings using the compute function.\n# This measures how well the predicted embeddings align with the ground truth.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nprecision_score = compute(gt_embeds_word, pred_embeds_word, gt_types, pred_types, self.affinity_matrix)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Computes the recall score by reversing the order of ground truth \n# and predicted embeddings in the compute function. This assesses how much of \n# the ground truth is captured by the predictions.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nrecall_score = compute(pred_embeds_word, gt_embeds_word, pred_types, gt_types, self.affinity_matrix)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Calculates the harmonic mean (RaTEScore) of precision and recall scores.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nharmonic_mean = 2 * precision_score * recall_score / (precision_score + recall_score)\nreturn harmonic_mean\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - None\n\n Mismatched Details:\n - The LaTeX formulation specifies that if the sum of precision and recall (S(x,\u02c6x) + S(\u02c6x,x)) is zero, the final score should be 0. In contrast, this implementation returns a default score of 0.5 when either the ground truth or predicted embeddings are empty.\n \n", "Missing_details": [], "Mismatched_details": [ "\n- The LaTeX formulation specifies that if the sum of precision and recall (S(x,\u02c6x) + S(\u02c6x,x)) is zero, the final score should be 0. In contrast, this implementation returns a default score of 0.5 when either the ground truth or predicted embeddings are empty.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - gt_embeds_word (torch.Tensor, shape=[num_gt_words, embed_dim]):\n Tensor containing the ground truth embeddings for each word.\n - pred_embeds_word (torch.Tensor, shape=[num_pred_words, embed_dim]):\n Tensor containing the predicted embeddings for each word.\n - gt_types (list[str]):\n List of types/categories corresponding to each ground truth word embedding.\n - pred_types (list[str]):\n List of types/categories corresponding to each predicted word embedding.\n", "Arguments_list": [ { "name": "gt_embeds_word", "string": "\n- gt_embeds_word (torch.Tensor, shape=[num_gt_words, embed_dim]):\n Tensor containing the ground truth embeddings for each word.\n", "dependency": null }, { "name": "pred_embeds_word", "string": "\n- pred_embeds_word (torch.Tensor, shape=[num_pred_words, embed_dim]):\n Tensor containing the predicted embeddings for each word.\n", "dependency": null }, { "name": "gt_types", "string": "\n- gt_types (list[str]):\n List of types/categories corresponding to each ground truth word embedding.\n", "dependency": null }, { "name": "pred_types", "string": "\n- pred_types (list[str]):\n List of types/categories corresponding to each predicted word embedding.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra File Dependencies:\n - RaTEScore.affinity_matrix\n\n Cross File Dependencies:\n - utils.compute\n", "intra_file": [ "RaTEScore.affinity_matrix" ], "cross_file": [ "utils.compute" ] }, "external_APIs": { "string": "\nExternal APIs:\n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - harmonic_mean (float):\n The computed RaTEScore representing the harmonic mean of precision and recall scores.\n", "return_list": [ { "name": "harmonic_mean", "string": "\n- harmonic_mean (float):\n The computed RaTEScore representing the harmonic mean of precision and recall scores.\n", "dependency": null } ] }, "ori_python_file": "import torch\nimport json\nimport numpy as np\nfrom transformers import AutoConfig, AutoModel, AutoTokenizer, AutoModelForTokenClassification\nimport pandas as pd\nimport os\nfrom .score import run_ner, process_embedding\nfrom .utils import compute\nDEFAULT_MATRIX = {\"abnormality_abnormality\": 0.4276119164393705, \"abnormality_anatomy\": 0.6240929990607657, \"abnormality_disease\": 0.0034478181112993847, \"abnormality_non-abnormality\": 0.5431049700217344, \"abnormality_non-disease\": 0.27005425386213877, \"anatomy_abnormality\": 0.7487824274337533, \"anatomy_anatomy\": 0.2856134859160784, \"anatomy_disease\": 0.4592143222158069, \"anatomy_non-abnormality\": 0.02097055139911715, \"anatomy_non-disease\": 0.00013736314126696204, \"disease_abnormality\": 0.8396510075734789, \"disease_anatomy\": 0.9950209388542061, \"disease_disease\": 0.8460555030578727, \"disease_non-abnormality\": 0.9820689020512646, \"disease_non-disease\": 0.3789136708096537, \"non-abnormality_abnormality\": 0.16546764653692908, \"non-abnormality_anatomy\": 0.018670610691852826, \"non-abnormality_disease\": 0.719397354576018, \"non-abnormality_non-abnormality\": 0.0009357166071730684, \"non-abnormality_non-disease\": 0.0927333564267591, \"non-disease_abnormality\": 0.7759420231214385, \"non-disease_anatomy\": 0.1839139293714062, \"non-disease_disease\": 0.10073046076318157, \"non-disease_non-abnormality\": 0.03860183811876373, \"non-disease_non-disease\": 0.34065681486566446}\nclass RaTEScore:\n def __init__(self,\n bert_model=\"Angelakeke/RaTE-NER-Deberta\",\n eval_model='FremyCompany/BioLORD-2023-C',\n batch_size=1,\n use_gpu=True,\n visualization_path=None,\n affinity_matrix=DEFAULT_MATRIX,\n ):\n if use_gpu:\n self.device = torch.device('cuda')\n else:\n self.device = torch.device('cpu')\n self.tokenizer = AutoTokenizer.from_pretrained(bert_model)\n self.model = AutoModelForTokenClassification.from_pretrained(bert_model).eval().to(self.device)\n self.eval_tokenizer = AutoTokenizer.from_pretrained(eval_model)\n self.eval_model = AutoModel.from_pretrained(eval_model).eval().to(self.device)\n if isinstance(affinity_matrix, str):\n self.matrix_path = json.load(open(affinity_matrix, 'r'))\n else:\n self.matrix_path = affinity_matrix\n self.affinity_matrix = {(k.split('_')[0].upper(), k.split('_')[1].upper()):v for k,v in self.matrix_path.items()}\n self.config = AutoConfig.from_pretrained(bert_model)\n self.label2idx = self.config.label2id\n self.idx2label = self.config.id2label\n self.batch_size = batch_size\n if visualization_path:\n self.visualization_path = visualization_path\n if not os.path.exists(os.path.dirname(visualization_path)):\n os.makedirs(os.path.dirname(visualization_path))\n else:\n self.visualization_path = None\n \n def compute_rate_score(self, gt_embeds_word, pred_embeds_word, gt_types, pred_types):\n if gt_embeds_word.size(0) == 0 or pred_embeds_word.size(0) == 0:\n return 0.5\n precision_score = compute(gt_embeds_word, pred_embeds_word, gt_types, pred_types, self.affinity_matrix)\n recall_score = compute(pred_embeds_word, gt_embeds_word, pred_types, gt_types, self.affinity_matrix)\n harmonic_mean = 2 * precision_score * recall_score / (precision_score + recall_score)\n return harmonic_mean\n \n def compute_score(self, candidate_list, reference_list):\n if not isinstance(candidate_list, list):\n raise ValueError(\"candidate must be a list\")\n if not isinstance(reference_list, list):\n raise ValueError(\"reference must be a list\")\n assert len(candidate_list) == len(reference_list), \"candidate and reference must have the same length\"\n if not all(isinstance(x, str) for x in candidate_list):\n raise ValueError(\"candidate must be a list of strings\")\n gt_pairs = run_ner(reference_list, self.idx2label, self.tokenizer, self.model, self.device, self.batch_size)\n pred_pairs = run_ner(candidate_list, self.idx2label, self.tokenizer, self.model, self.device, self.batch_size)\n rate_score = []\n for gt_pair, pred_pair in zip(gt_pairs, pred_pairs):\n gt_embeds_word, gt_types = process_embedding(gt_pair, self.eval_tokenizer, self.eval_model, self.device)\n pred_embeds_word, pred_types = process_embedding(pred_pair, self.eval_tokenizer, self.eval_model, self.device)\n score = self.compute_rate_score(gt_embeds_word, pred_embeds_word, gt_types, pred_types)\n rate_score.append(score)\n if self.visualization_path:\n save_file = pd.DataFrame({\n 'candidate': candidate_list,\n 'reference': reference_list,\n 'candidate_entities': pred_pairs,\n 'reference_entities': gt_pairs,\n 'rate_score': rate_score\n })\n save_file.to_json(os.path.join(self.visualization_path, 'rate_score.json'), lines=True, orient='records')\n return rate_score" } ] }, { "paper_id": 22, "paper_details": { "title": "GREEN: Generative Radiology Report Evaluation and Error Notation", "url": "https://arxiv.org/abs/2405.03595" }, "enviorment_name": "green_score", "repo_original_url": "https://github.com/Stanford-AIMI/GREEN", "project_path": "Benchmark/22-green/GREEN-main", "file_organization": "\nGREEN-main/\n green_score/\n __init__.py\n utils.py\n tests/\n test_repro.py\n .gitignore\n green.py\n main.py\n README.md\n requirements.txt\n setup.py\n", "latex_code_path": "Benchmark/22-green/arXiv-2405.03595v2", "task_details": [ { "task_id": 0, "indent": 2, "script": "\npython main.py\n", "latex_code": "\n\\subsection{GREEN Score} \\label{sec:green_score}\nThe GREEN score rewards matched findings, balancing the penalties for clinically significant errors by employing an inverse structure. Consequently, as reports become more concise and accurate, achieving a higher score becomes increasingly challenging.\n\nWe employed regular expressions (regex) to parse the counts of errors from the model's output. Specifically, we denoted the count of each type of error as $\\text{\\# error}_{s,i}$, where the error's clinical significance $s \\in \\{\\mathrm{sig.},\\mathrm{insig.}\\}$ and subcategory $i \\in \\{(a),(b),\\dots,(f)\\}$.\n\nTo calculate the GREEN score, we prioritized $\\text{\\# error}_{\\mathrm{sig.},i}$ (errors with the potential to alter clinical decision-making processes) alongside the counts of accurate matched findings, \\text{\\# matched findings}, for inversion.\n", "completion_path": "./green.py", "namespace": "green.GREEN.parse_error_counts", "type": "method", "signature_position": [ 238, 238 ], "body_position": [ 239, 271 ], "ReferenceCode_With_Comments": "\nif category not in self.categories:\n raise ValueError(\n f\"Category {category} is not a valid category. Please choose from {self.categories}.\"\n )\n\n# ---------------------------------------------------------------------------\n# Snippet 1: Construct a regex pattern to extract the text corresponding to the\n# specified category. This pattern searches for the category label followed by its\n# content until a double newline or the end of the string.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\npattern = rf\"\\[{category}\\]:\\s*(.*?)(?:\\n\\s*\\n|\\Z)\"\ncategory_text = re.search(pattern, text, re.DOTALL)\n\n\nsum_counts = 0\nsub_counts = [0 for i in range(6)]\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Handle cases where the category text is not found and return the initialized counts.\n# This ensures appropriate handling based on the context of usage.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nif not category_text:\n return sum_counts, sub_counts\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Check if the category text indicates the absence of errors by\n# starting with \"No\". If so, return the initialized counts without further processing.\n# This accounts for scenarios with zero errors reported.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nif category_text.group(1).startswith(\"No\"):\n return sum_counts, sub_counts\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Specifically handle the \"Matched Findings\" category by extracting\n# the count of matched findings using a regex that captures digits followed by a period.\n# This directly maps to the accurate matched findings required for the GREEN score.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nif category == \"Matched Findings\":\n counts = re.findall(r\"^\\b\\d+\\b(?=\\.)\", category_text.group(1))\n if len(counts) > 0:\n sum_counts = int(counts[0])\n return sum_counts, sub_counts\n# [End Snippet 4]\nelse:\n # ---------------------------------------------------------------------------\n # Snippet 5: For other categories, prepare subcategory labels and extract all\n # matching subcategory lines using regex. This sets up the parsing of individual\n # subcategories within the main category.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 5]\n sub_categories = [s.split(\" \", 1)[0] + \" \" for s in self.sub_categories]\n matches = sorted(re.findall(r\"\\([a-f]\\) .*\", category_text.group(1)))\n # [End Snippet 5]\n\n # ---------------------------------------------------------------------------\n # Snippet 6: If no alphabetical subcategory matches are found, attempt to find\n # numerical subcategory matches. This ensures flexibility in handling different\n # reporting formats that may use numbers instead of letters for subcategories.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 6]\n if len(matches) == 0:\n matches = sorted(re.findall(r\"\\([1-6]\\) .*\", category_text.group(1)))\n sub_categories = [\n f\"({i})\" + \" \" for i in range(1, len(self.sub_categories) + 1)\n ]\n # [End Snippet 6]\n\n # ---------------------------------------------------------------------------\n # Snippet 7: Iterate over each subcategory and its corresponding matches to extract\n # the count of errors. This populates the `sub_counts` list with the number of errors\n # for each subcategory, facilitating detailed error analysis.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 7]\n for position, sub_category in enumerate(sub_categories):\n for match in range(len(matches)):\n if matches[match].startswith(sub_category):\n count = re.findall(r\"(?<=: )\\b\\d+\\b(?=\\.)\", matches[match])\n if len(count) > 0:\n sub_counts[position] = int(count[0])\n # [End Snippet 7]\n\n # ---------------------------------------------------------------------------\n # Snippet 8: Aggregate the counts from all subcategories to obtain the total\n # number of errors for the category. This sum is essential for the overall GREEN score calculation.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 8]\n sum_counts = sum(sub_counts)\n\n return sum_counts, sub_counts\n # [End Snippet 8]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The function handles both alphabetical (a-f) and numerical (1-6) subcategories, accommodating different reporting formats that may not be explicitly detailed in the LaTeX code.\n - Handling of missing category blocks in the input text. The reference code explicitly returns initialized counts (sum=0, subcounts=zeros) when the category block is not found, ensuring numerical stability for downstream calculations. The LaTeX description does not mention this robustness requirement.\n - Explicit check for \"No errors\" declarations in category blocks. The reference code returns zero counts when a category block starts with \"No\".\n - There is no mention of a two-step extraction process for parsing subcategory error counts. The workflow should first identify lines in the text that correspond to specific subcategories (e.g., lines starting with a subcategory marker followed by descriptive text), then extract the numerical count from each identified line, ensuring counts are only assigned to explicitly mentioned subcategories rather than assuming a count for every possible subcategory.\n - The LaTeX description does not specify how to handle different formats for identifying subcategories of errors, such as using letters (e.g., (a), (b)) or numbers (e.g., (1), (2)). In practice, the process should first attempt to extract subcategory details using one format (like letters), and if none are found, switch to an alternative format (like numbers).\n\n Mismatched Details:\n - None \n", "Missing_details": [ "\n- The function handles both alphabetical (a-f) and numerical (1-6) subcategories, accommodating different reporting formats that may not be explicitly detailed in the LaTeX code.\n", "\n- Handling of missing category blocks in the input text. The reference code explicitly returns initialized counts (sum=0, subcounts=zeros) when the category block is not found, ensuring numerical stability for downstream calculations. The LaTeX description does not mention this robustness requirement.\n", "\n- Explicit check for \"No errors\" declarations in category blocks. The reference code returns zero counts when a category block starts with \"No\".\n", "\n- There is no mention of a two-step extraction process for parsing subcategory error counts. The workflow should first identify lines in the text that correspond to specific subcategories (e.g., lines starting with a subcategory marker followed by descriptive text), then extract the numerical count from each identified line, ensuring counts are only assigned to explicitly mentioned subcategories rather than assuming a count for every possible subcategory.\n", "\n- The LaTeX description does not specify how to handle different formats for identifying subcategories of errors, such as using letters (e.g., (a), (b)) or numbers (e.g., (1), (2)). In practice, the process should first attempt to extract subcategory details using one format (like letters), and if none are found, switch to an alternative format (like numbers).\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - text (str):\n The text from which error counts are to be parsed. This typically represents the\n model's output containing various categories and their corresponding error counts.\n - category (str):\n The specific category of errors to parse (e.g., \"Clinically Significant Errors\", \"Clinically Insignificant Errors\", and \"Matched Findings\")\n It must be one of the predefined categories within `GREEN.categories`.\n", "Arguments_list": [ { "name": "text", "string": "\n- text (str):\n The text from which error counts are to be parsed. This typically represents the\n model's output containing various categories and their corresponding error counts. \n", "dependency": null }, { "name": "category", "string": "\n- category (str):\n The specific category of errors to parse (e.g., \"Clinically Significant Errors\", \"Clinically Insignificant Errors\", and \"Matched Findings\")\n It must be one of the predefined categories within `GREEN.categories`.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra File Dependencies:\n - GREEN.categories\n - GREEN.sub_categories\n \n - Cross File Dependencies:\n - None\n", "intra_file": [ "GREEN.categories", "GREEN.sub_categories" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - re.search\n - re.findall\n", "list": [ "re.search", "re.findall" ] }, "Return": { "Return_String": "\nOutput Variables:\n - sum_counts (int or None):\n The total count of errors for the specified category. For \"Matched Findings\",\n it represents the number of accurately matched findings. \n\n - sub_counts (list of int or None):\n A list containing counts for each subcategory within the specified category.\n", "return_list": [ { "name": "sum_counts", "string": "\n- sum_counts (int or None):\n The total count of errors for the specified category. For \"Matched Findings\",\n it represents the number of accurately matched findings. \n", "dependency": null } ] }, "ori_python_file": "import re\nimport torch\nimport torch.distributed as dist\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nimport pandas as pd\nfrom datasets import Dataset\nfrom datasets.distributed import split_dataset_by_node\nimport os\nfrom tqdm import tqdm\nimport numpy as np\nimport time\nimport sys\nimport warnings\nfrom green_score.utils import compute_largest_cluster, flatten_values_lists_of_list_dicts_to_dict, make_prompt, clean_responses, gather_processes\nfrom transformers.utils import logging\nlogging.get_logger(\"transformers\").setLevel(logging.ERROR)\ndef get_rank():\n if not dist.is_initialized():\n return 0\n return dist.get_rank()\n\ndef is_main_process():\n return get_rank() == 0\n\ndef tqdm_on_main(*args, **kwargs):\n if is_main_process():\n print(\"==== Beginning Inference ====\")\n return tqdm(*args, **kwargs)\n else:\n return kwargs.get(\"iterable\", None)\n\nclass GREEN:\n def __init__(\n self, model_name, output_dir=\".\", cpu=False, compute_summary_stats=True\n ):\n super().__init__()\n warnings.filterwarnings(\n \"ignore\", message=\"A decoder-only architecture is being used*\"\n )\n self.cpu = cpu\n self.model_name = model_name.split(\"/\")[-1]\n self.output_dir = output_dir\n self.batch_size = 4\n self.max_length = 2048\n self.categories = [\n \"Clinically Significant Errors\",\n \"Clinically Insignificant Errors\",\n \"Matched Findings\",\n ]\n self.sub_categories = [\n \"(a) False report of a finding in the candidate\",\n \"(b) Missing a finding present in the reference\",\n \"(c) Misidentification of a finding's anatomic location/position\",\n \"(d) Misassessment of the severity of a finding\",\n \"(e) Mentioning a comparison that isn't in the reference\",\n \"(f) Omitting a comparison detailing a change from a prior study\",\n ]\n self.prompts = None\n self.completions = None\n self.green_scores = None\n self.error_counts = None\n if torch.cuda.is_available() and torch.cuda.device_count() > 1 and not self.cpu:\n if not dist.is_initialized():\n dist.init_process_group(\n backend=\"nccl\",\n )\n torch.cuda.set_device(dist.get_rank())\n if dist.get_rank() == 0:\n print(\n \"Distributed training with\", torch.cuda.device_count(), \"GPUs\"\n )\n self.model = AutoModelForCausalLM.from_pretrained(\n model_name,\n trust_remote_code=False if \"Phi\" in model_name else True,\n device_map=(\n {\"\": \"cuda:{}\".format(torch.cuda.current_device())}\n if not self.cpu\n else {\"\": \"cpu\"}\n ),\n torch_dtype=torch.float16,\n )\n self.model.eval()\n self.tokenizer = AutoTokenizer.from_pretrained(\n model_name,\n add_eos_token=True,\n use_fast=True,\n trust_remote_code=True,\n padding_side=\"left\",\n )\n chat_template = \"{% for message in messages %}\\n{% if message['from'] == 'human' %}\\n{{ '<|user|>\\n' + message['value'] + eos_token }}\\n{% elif message['from'] == 'system' %}\\n{{ '<|system|>\\n' + message['value'] + eos_token }}\\n{% elif message['from'] == 'gpt' %}\\n{{ '<|assistant|>\\n' + message['value'] + eos_token }}\\n{% endif %}\\n{% if loop.last and add_generation_prompt %}\\n{{ '<|assistant|>' }}\\n{% endif %}\\n{% endfor %}\"\n self.tokenizer.chat_template = chat_template\n self.tokenizer.pad_token = self.tokenizer.eos_token\n self.tokenizer.clean_up_tokenization_spaces = True\n assert self.tokenizer.padding_side == \"left\"\n self.compute_summary_stats = compute_summary_stats\n \n def __call__(self, refs, hyps):\n print(\"Processing data...making prompts\")\n dataset = Dataset.from_dict({\"reference\": refs, \"prediction\": hyps})\n dataset = self.process_data(dataset)\n print(\"Done.\")\n self.dataset = dataset\n t = time.time()\n mean, std, green_scores, summary, results_df = self.infer()\n t = time.time() - t\n print(\"Seconds per example: \", t / len(refs))\n if not is_main_process():\n print(f\"Rank {dist.get_rank()} exiting.\")\n dist.destroy_process_group()\n sys.exit()\n return mean, std, green_scores, summary, results_df\n \n def process_data(self, dataset):\n def prompting(examples):\n return {\n \"prompt\": [\n make_prompt(r, p)\n for r, p in zip(examples[\"reference\"], examples[\"prediction\"])\n ]\n }\n dataset = dataset.map(prompting, batched=True)\n return dataset\n \n @torch.inference_mode()\n def infer(self):\n if torch.cuda.is_available() and torch.cuda.device_count() > 1 and not self.cpu:\n dataset_dist = split_dataset_by_node(\n self.dataset,\n rank=get_rank(),\n world_size=int(os.environ[\"WORLD_SIZE\"]),\n )\n print(\"Distributed dataset created on rank: \", int(os.environ[\"RANK\"]))\n else:\n dataset_dist = self.dataset\n local_completions = []\n local_references = []\n for batch in tqdm_on_main(\n iterable=dataset_dist.iter(batch_size=self.batch_size),\n total=len(dataset_dist) // self.batch_size,\n ):\n local_references.extend(batch[\"prompt\"])\n local_completions.extend(self.get_response(batch))\n if torch.cuda.is_available() and torch.cuda.device_count() > 1 and not self.cpu:\n self.completions, self.prompts = gather_processes(\n local_completions, local_references\n )\n else:\n self.completions = local_completions\n self.prompts = local_references\n if is_main_process():\n print(\"==== End Inference ====\")\n if len(self.completions) != len(self.prompts):\n print(\"Length of prompts and completions are not equal!\")\n return self.process_results()\n \n def tokenize_batch_as_chat(self, batch):\n local_rank = int(os.environ.get(\"LOCAL_RANK\", 0)) if not self.cpu else \"cpu\"\n batch = [\n self.tokenizer.apply_chat_template(\n i, tokenize=False, add_generation_prompt=True\n )\n for i in batch\n ]\n batch = self.tokenizer.batch_encode_plus(\n batch,\n return_tensors=\"pt\",\n padding=True,\n truncation=True,\n max_length=self.max_length,\n ).to(local_rank)\n return batch\n \n def get_response(self, batch):\n assert \"prompt\" in batch.keys(), \"prompt is not in batch keys\"\n batch = [\n [{\"from\": \"human\", \"value\": prompt}, {\"from\": \"gpt\", \"value\": \"\"}]\n for prompt in batch[\"prompt\"]\n ]\n batch = self.tokenize_batch_as_chat(batch)\n outputs = self.model.generate(\n input_ids=batch[\"input_ids\"],\n attention_mask=batch[\"attention_mask\"],\n eos_token_id=self.tokenizer.eos_token_id,\n pad_token_id=self.tokenizer.pad_token_id,\n max_length=2048,\n do_sample=False,\n temperature=None,\n top_p=None,\n )\n responses = self.tokenizer.batch_decode(outputs, skip_special_tokens=True)\n response_list = []\n if isinstance(responses, list):\n for response in responses:\n response = clean_responses(response)\n response_list.append(response)\n else:\n responses = clean_responses(responses)\n response_list.append(responses)\n return response_list\n \n def process_results(self):\n self.green_scores = [\n self.compute_green(response, self.categories) for response in self.completions\n ]\n self.error_counts = pd.DataFrame(\n [self.compute_error_count(response) for response in self.completions],\n columns=self.sub_categories + [\"Matched Findings\"],\n )\n results_df = pd.DataFrame(\n {\n \"reference\": self.dataset[\"reference\"],\n \"predictions\": self.dataset[\"prediction\"],\n \"green_analysis\": self.completions,\n \"green_score\": self.green_scores,\n **self.error_counts,\n }\n )\n mean, std, summary = None, None, None\n if self.compute_summary_stats:\n mean, std, summary = self.compute_summary()\n return mean, std, self.green_scores, summary, results_df\n \n def compute_error_count(self, response):\n _, sig_errors = self.parse_error_counts(response, self.categories[0])\n matched_findings, _ = self.parse_error_counts(response, self.categories[2])\n return sig_errors + [matched_findings]\n \n def compute_green(self, response, categories):\n sig_present, sig_errors = self.parse_error_counts(response, categories[0])\n matched_findings, _ = self.parse_error_counts(response, categories[2])\n if matched_findings == 0:\n return 0\n if sig_present is None or matched_findings is None:\n return None\n score = matched_findings / (matched_findings + sum(sig_errors))\n return score\n \n def parse_error_counts(self, text, category):\n if category not in self.categories:\n raise ValueError(\n f\"Category {category} is not a valid category. Please choose from {self.categories}.\"\n )\n pattern = rf\"\\[{category}\\]:\\s*(.*?)(?:\\n\\s*\\n|\\Z)\"\n category_text = re.search(pattern, text, re.DOTALL)\n sum_counts = 0\n sub_counts = [0 for i in range(6)]\n if not category_text:\n return sum_counts, sub_counts\n if category_text.group(1).startswith(\"No\"):\n return sum_counts, sub_counts\n if category == \"Matched Findings\":\n counts = re.findall(r\"^\\b\\d+\\b(?=\\.)\", category_text.group(1))\n if len(counts) > 0:\n sum_counts = int(counts[0])\n return sum_counts, sub_counts\n else:\n sub_categories = [s.split(\" \", 1)[0] + \" \" for s in self.sub_categories]\n matches = sorted(re.findall(r\"\\([a-f]\\) .*\", category_text.group(1)))\n if len(matches) == 0:\n matches = sorted(re.findall(r\"\\([1-6]\\) .*\", category_text.group(1)))\n sub_categories = [\n f\"({i})\" + \" \" for i in range(1, len(self.sub_categories) + 1)\n ]\n for position, sub_category in enumerate(sub_categories):\n for match in range(len(matches)):\n if matches[match].startswith(sub_category):\n count = re.findall(r\"(?<=: )\\b\\d+\\b(?=\\.)\", matches[match])\n if len(count) > 0:\n sub_counts[position] = int(count[0])\n sum_counts = sum(sub_counts)\n return sum_counts, sub_counts\n \n def parse_error_sentences(self, response, category):\n if category not in self.categories:\n raise ValueError(\n f\"Category {category} is not a valid category. Please choose from {self.categories}.\"\n )\n pattern = rf\"\\[{category}\\]:\\s*(.*?)(?:\\n\\s*\\n|\\Z)\"\n category_text = re.search(pattern, response, re.DOTALL)\n sub_category_dict_sentences = {}\n for sub_category in self.sub_categories:\n sub_category_dict_sentences[sub_category] = []\n if not category_text:\n return sub_category_dict_sentences\n if category_text.group(1).startswith(\"No\"):\n return sub_category_dict_sentences\n if category == \"Matched Findings\":\n return (\n category_text.group(1).rsplit(\":\", 1)[-1].rsplit(\".\", 1)[-1].split(\";\")\n )\n matches = sorted(re.findall(r\"\\([a-f]\\) .*\", category_text.group(1)))\n if len(matches) == 0:\n matches = sorted(re.findall(r\"\\([1-6]\\) .*\", category_text.group(1)))\n self.sub_categories = [\n f\"({i})\" + \" \" for i in range(1, len(self.sub_categories) + 1)\n ]\n for position, sub_category in enumerate(self.sub_categories):\n for match in range(len(matches)):\n if matches[match].startswith(sub_category):\n sentences_list = (\n matches[match].rsplit(\":\", 1)[-1].split(\".\", 1)[-1].split(\";\")\n )\n sub_category_dict_sentences[self.sub_categories[position]] = (\n sentences_list\n )\n return sub_category_dict_sentences\n \n def compute_sentences(self, response):\n return self.parse_error_sentences(response, self.categories[0])\n \n def get_representative_sentences(self, responses):\n list_sentences = []\n for i in responses:\n sentences = self.compute_sentences(i)\n list_sentences.append(sentences)\n dict_sentences = flatten_values_lists_of_list_dicts_to_dict(list_sentences)\n result_sentences_dict = {}\n for i in self.sub_categories:\n sentences = dict_sentences[i]\n sentences = [i for i in sentences if i.strip() != \"\"]\n _, sentences_of_largest_cluster = compute_largest_cluster(sentences)\n result_sentences_dict[i] = sentences_of_largest_cluster\n return result_sentences_dict\n \n def compute_accuracy(self, responses):\n counts = []\n for response in responses:\n _, sig_errors = self.parse_error_counts(response, self.categories[0])\n counts.append(sig_errors)\n counts = np.array(counts)\n dict_acc = {}\n for i in range(len(self.sub_categories)):\n error_counts = counts[:, i]\n accuracy = np.mean(error_counts == 0)\n dict_acc[self.sub_categories[i]] = accuracy\n return dict_acc\n \n def compute_summary(self):\n print(\"Computing summary ...\")\n representative_sentences = self.get_representative_sentences(self.completions)\n accuracies = self.compute_accuracy(self.completions)\n mean = np.mean(self.green_scores)\n std = np.std(self.green_scores)\n summary = f\"\\n-------------{self.model_name}----------------\\n [Summary]: Green average {mean} and standard deviation {std} \\n [Clinically Significant Errors Analyses]: . \\n\\n\"\n for idx, sub_category in enumerate(self.sub_categories):\n accuracy = accuracies[sub_category]\n sentences = representative_sentences[sub_category]\n summary += f\"{sub_category}: {accuracy}. \\n {sentences} \\n\\n\"\n summary += \"----------------------------------\\n\"\n return mean, std, summary\nif __name__ == \"__main__\":\n pass" }, { "task_id": 1, "indent": 2, "script": "\npython main.py\n", "latex_code": "\nThe formula for the GREEN score is then expressed as:\n\\begin{align}\n\\text{GREEN} = \\frac{\\text{\\# matched findings}}{\\text{\\# matched findings} + \\sum\\limits_{i=(a)}^{(f)} \\text{\\# error}_{\\mathrm{sig.},i}}\n\\end{align}\nif \\# matched findings > 0, otherwise 0.\nThus, the GREEN score ($\\uparrow$) is bounded between 0 and 1.\n", "completion_path": "./green.py", "namespace": "green.GREEN.compute_green", "type": "method", "signature_position": [ 228, 228 ], "body_position": [ 229, 236 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Extract the presence of significant errors and their counts by parsing the\n# response text. This aligns with identifying clinically significant errors as described in the GREEN score formula.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nsig_present, sig_errors = self.parse_error_counts(response, categories[0])\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Extract the number of matched findings by parsing the response text.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nmatched_findings, _ = self.parse_error_counts(response, categories[2])\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Check if there are no matched findings. If so, return a GREEN score of 0,\n# indicating the absence of accurate and concise reporting as per the formula.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nif matched_findings == 0:\n return 0\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Validate that both the presence of significant errors and the number of\n# matched findings are available. If either is `None`, return `None` to indicate\n# that the GREEN score cannot be computed due to missing data.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nif sig_present is None or matched_findings is None:\n return None\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Calculate the GREEN score by dividing the number of matched findings by the\n# sum of matched findings and the total number of significant errors. \n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nscore = matched_findings / (matched_findings + sum(sig_errors))\n\nreturn score\n# [End Snippet 5]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - None\n \n Mismatched Details:\n - None\n", "Missing_details": [], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - response (str):\n The text response from which error counts and matched findings are to be parsed. This typically\n contains categorized error information that will be analyzed to compute the GREEN score.\n - categories (list[str]): It shows the categories of errors to parse.\n categories = [\n \"Clinically Significant Errors\",\n \"Clinically Insignificant Errors\",\n \"Matched Findings\",\n ]\n", "Arguments_list": [ { "name": "response", "string": "\n- response (str):\n The text response from which error counts and matched findings are to be parsed. This typically\n contains categorized error information that will be analyzed to compute the GREEN score.\n", "dependency": null }, { "name": "categories", "string": "\n- categories (list[str]): It shows the categories of errors to parse.\n categories = [\n \"Clinically Significant Errors\",\n \"Clinically Insignificant Errors\",\n \"Matched Findings\",\n ]\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra File Dependencies:\n - GREEN.parse_error_counts\n\n - Cross File Dependencies:\n - None\n", "intra_file": [ "GREEN.parse_error_counts" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - score (float or None):\n A floating-point value representing the GREEN score, calculated as the ratio of matched findings\n to the sum of matched findings and significant errors. The score ranges from 0 to 1.\n Returns 0 if there are no matched findings, and `None` if required counts are unavailable.\n", "return_list": [ { "name": "score", "string": "\n- score (float or None):\n A floating-point value representing the GREEN score, calculated as the ratio of matched findings\n to the sum of matched findings and significant errors. The score ranges from 0 to 1.\n Returns 0 if there are no matched findings, and `None` if required counts are unavailable.\n", "dependency": null } ] }, "ori_python_file": "import re\nimport torch\nimport torch.distributed as dist\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nimport pandas as pd\nfrom datasets import Dataset\nfrom datasets.distributed import split_dataset_by_node\nimport os\nfrom tqdm import tqdm\nimport numpy as np\nimport time\nimport sys\nimport warnings\nfrom green_score.utils import compute_largest_cluster, flatten_values_lists_of_list_dicts_to_dict, make_prompt, clean_responses, gather_processes\nfrom transformers.utils import logging\nlogging.get_logger(\"transformers\").setLevel(logging.ERROR)\ndef get_rank():\n if not dist.is_initialized():\n return 0\n return dist.get_rank()\n\ndef is_main_process():\n return get_rank() == 0\n\ndef tqdm_on_main(*args, **kwargs):\n if is_main_process():\n print(\"==== Beginning Inference ====\")\n return tqdm(*args, **kwargs)\n else:\n return kwargs.get(\"iterable\", None)\n\nclass GREEN:\n def __init__(\n self, model_name, output_dir=\".\", cpu=False, compute_summary_stats=True\n ):\n super().__init__()\n warnings.filterwarnings(\n \"ignore\", message=\"A decoder-only architecture is being used*\"\n )\n self.cpu = cpu\n self.model_name = model_name.split(\"/\")[-1]\n self.output_dir = output_dir\n self.batch_size = 4\n self.max_length = 2048\n self.categories = [\n \"Clinically Significant Errors\",\n \"Clinically Insignificant Errors\",\n \"Matched Findings\",\n ]\n self.sub_categories = [\n \"(a) False report of a finding in the candidate\",\n \"(b) Missing a finding present in the reference\",\n \"(c) Misidentification of a finding's anatomic location/position\",\n \"(d) Misassessment of the severity of a finding\",\n \"(e) Mentioning a comparison that isn't in the reference\",\n \"(f) Omitting a comparison detailing a change from a prior study\",\n ]\n self.prompts = None\n self.completions = None\n self.green_scores = None\n self.error_counts = None\n if torch.cuda.is_available() and torch.cuda.device_count() > 1 and not self.cpu:\n if not dist.is_initialized():\n dist.init_process_group(\n backend=\"nccl\",\n )\n torch.cuda.set_device(dist.get_rank())\n if dist.get_rank() == 0:\n print(\n \"Distributed training with\", torch.cuda.device_count(), \"GPUs\"\n )\n self.model = AutoModelForCausalLM.from_pretrained(\n model_name,\n trust_remote_code=False if \"Phi\" in model_name else True,\n device_map=(\n {\"\": \"cuda:{}\".format(torch.cuda.current_device())}\n if not self.cpu\n else {\"\": \"cpu\"}\n ),\n torch_dtype=torch.float16,\n )\n self.model.eval()\n self.tokenizer = AutoTokenizer.from_pretrained(\n model_name,\n add_eos_token=True,\n use_fast=True,\n trust_remote_code=True,\n padding_side=\"left\",\n )\n chat_template = \"{% for message in messages %}\\n{% if message['from'] == 'human' %}\\n{{ '<|user|>\\n' + message['value'] + eos_token }}\\n{% elif message['from'] == 'system' %}\\n{{ '<|system|>\\n' + message['value'] + eos_token }}\\n{% elif message['from'] == 'gpt' %}\\n{{ '<|assistant|>\\n' + message['value'] + eos_token }}\\n{% endif %}\\n{% if loop.last and add_generation_prompt %}\\n{{ '<|assistant|>' }}\\n{% endif %}\\n{% endfor %}\"\n self.tokenizer.chat_template = chat_template\n self.tokenizer.pad_token = self.tokenizer.eos_token\n self.tokenizer.clean_up_tokenization_spaces = True\n assert self.tokenizer.padding_side == \"left\"\n self.compute_summary_stats = compute_summary_stats\n \n def __call__(self, refs, hyps):\n print(\"Processing data...making prompts\")\n dataset = Dataset.from_dict({\"reference\": refs, \"prediction\": hyps})\n dataset = self.process_data(dataset)\n print(\"Done.\")\n self.dataset = dataset\n t = time.time()\n mean, std, green_scores, summary, results_df = self.infer()\n t = time.time() - t\n print(\"Seconds per example: \", t / len(refs))\n if not is_main_process():\n print(f\"Rank {dist.get_rank()} exiting.\")\n dist.destroy_process_group()\n sys.exit()\n return mean, std, green_scores, summary, results_df\n \n def process_data(self, dataset):\n def prompting(examples):\n return {\n \"prompt\": [\n make_prompt(r, p)\n for r, p in zip(examples[\"reference\"], examples[\"prediction\"])\n ]\n }\n dataset = dataset.map(prompting, batched=True)\n return dataset\n \n @torch.inference_mode()\n def infer(self):\n if torch.cuda.is_available() and torch.cuda.device_count() > 1 and not self.cpu:\n dataset_dist = split_dataset_by_node(\n self.dataset,\n rank=get_rank(),\n world_size=int(os.environ[\"WORLD_SIZE\"]),\n )\n print(\"Distributed dataset created on rank: \", int(os.environ[\"RANK\"]))\n else:\n dataset_dist = self.dataset\n local_completions = []\n local_references = []\n for batch in tqdm_on_main(\n iterable=dataset_dist.iter(batch_size=self.batch_size),\n total=len(dataset_dist) // self.batch_size,\n ):\n local_references.extend(batch[\"prompt\"])\n local_completions.extend(self.get_response(batch))\n if torch.cuda.is_available() and torch.cuda.device_count() > 1 and not self.cpu:\n self.completions, self.prompts = gather_processes(\n local_completions, local_references\n )\n else:\n self.completions = local_completions\n self.prompts = local_references\n if is_main_process():\n print(\"==== End Inference ====\")\n if len(self.completions) != len(self.prompts):\n print(\"Length of prompts and completions are not equal!\")\n return self.process_results()\n \n def tokenize_batch_as_chat(self, batch):\n local_rank = int(os.environ.get(\"LOCAL_RANK\", 0)) if not self.cpu else \"cpu\"\n batch = [\n self.tokenizer.apply_chat_template(\n i, tokenize=False, add_generation_prompt=True\n )\n for i in batch\n ]\n batch = self.tokenizer.batch_encode_plus(\n batch,\n return_tensors=\"pt\",\n padding=True,\n truncation=True,\n max_length=self.max_length,\n ).to(local_rank)\n return batch\n \n def get_response(self, batch):\n assert \"prompt\" in batch.keys(), \"prompt is not in batch keys\"\n batch = [\n [{\"from\": \"human\", \"value\": prompt}, {\"from\": \"gpt\", \"value\": \"\"}]\n for prompt in batch[\"prompt\"]\n ]\n batch = self.tokenize_batch_as_chat(batch)\n outputs = self.model.generate(\n input_ids=batch[\"input_ids\"],\n attention_mask=batch[\"attention_mask\"],\n eos_token_id=self.tokenizer.eos_token_id,\n pad_token_id=self.tokenizer.pad_token_id,\n max_length=2048,\n do_sample=False,\n temperature=None,\n top_p=None,\n )\n responses = self.tokenizer.batch_decode(outputs, skip_special_tokens=True)\n response_list = []\n if isinstance(responses, list):\n for response in responses:\n response = clean_responses(response)\n response_list.append(response)\n else:\n responses = clean_responses(responses)\n response_list.append(responses)\n return response_list\n \n def process_results(self):\n self.green_scores = [\n self.compute_green(response, self.categories) for response in self.completions\n ]\n self.error_counts = pd.DataFrame(\n [self.compute_error_count(response) for response in self.completions],\n columns=self.sub_categories + [\"Matched Findings\"],\n )\n results_df = pd.DataFrame(\n {\n \"reference\": self.dataset[\"reference\"],\n \"predictions\": self.dataset[\"prediction\"],\n \"green_analysis\": self.completions,\n \"green_score\": self.green_scores,\n **self.error_counts,\n }\n )\n mean, std, summary = None, None, None\n if self.compute_summary_stats:\n mean, std, summary = self.compute_summary()\n return mean, std, self.green_scores, summary, results_df\n \n def compute_error_count(self, response):\n _, sig_errors = self.parse_error_counts(response, self.categories[0])\n matched_findings, _ = self.parse_error_counts(response, self.categories[2])\n return sig_errors + [matched_findings]\n \n def compute_green(self, response, categories):\n sig_present, sig_errors = self.parse_error_counts(response, categories[0])\n matched_findings, _ = self.parse_error_counts(response, categories[2])\n if matched_findings == 0:\n return 0\n if sig_present is None or matched_findings is None:\n return None\n score = matched_findings / (matched_findings + sum(sig_errors))\n return score\n \n def parse_error_counts(self, text, category):\n if category not in self.categories:\n raise ValueError(\n f\"Category {category} is not a valid category. Please choose from {self.categories}.\"\n )\n pattern = rf\"\\[{category}\\]:\\s*(.*?)(?:\\n\\s*\\n|\\Z)\"\n category_text = re.search(pattern, text, re.DOTALL)\n sum_counts = 0\n sub_counts = [0 for i in range(6)]\n if not category_text:\n return sum_counts, sub_counts\n if category_text.group(1).startswith(\"No\"):\n return sum_counts, sub_counts\n if category == \"Matched Findings\":\n counts = re.findall(r\"^\\b\\d+\\b(?=\\.)\", category_text.group(1))\n if len(counts) > 0:\n sum_counts = int(counts[0])\n return sum_counts, sub_counts\n else:\n sub_categories = [s.split(\" \", 1)[0] + \" \" for s in self.sub_categories]\n matches = sorted(re.findall(r\"\\([a-f]\\) .*\", category_text.group(1)))\n if len(matches) == 0:\n matches = sorted(re.findall(r\"\\([1-6]\\) .*\", category_text.group(1)))\n sub_categories = [\n f\"({i})\" + \" \" for i in range(1, len(self.sub_categories) + 1)\n ]\n for position, sub_category in enumerate(sub_categories):\n for match in range(len(matches)):\n if matches[match].startswith(sub_category):\n count = re.findall(r\"(?<=: )\\b\\d+\\b(?=\\.)\", matches[match])\n if len(count) > 0:\n sub_counts[position] = int(count[0])\n sum_counts = sum(sub_counts)\n return sum_counts, sub_counts\n \n def parse_error_sentences(self, response, category):\n if category not in self.categories:\n raise ValueError(\n f\"Category {category} is not a valid category. Please choose from {self.categories}.\"\n )\n pattern = rf\"\\[{category}\\]:\\s*(.*?)(?:\\n\\s*\\n|\\Z)\"\n category_text = re.search(pattern, response, re.DOTALL)\n sub_category_dict_sentences = {}\n for sub_category in self.sub_categories:\n sub_category_dict_sentences[sub_category] = []\n if not category_text:\n return sub_category_dict_sentences\n if category_text.group(1).startswith(\"No\"):\n return sub_category_dict_sentences\n if category == \"Matched Findings\":\n return (\n category_text.group(1).rsplit(\":\", 1)[-1].rsplit(\".\", 1)[-1].split(\";\")\n )\n matches = sorted(re.findall(r\"\\([a-f]\\) .*\", category_text.group(1)))\n if len(matches) == 0:\n matches = sorted(re.findall(r\"\\([1-6]\\) .*\", category_text.group(1)))\n self.sub_categories = [\n f\"({i})\" + \" \" for i in range(1, len(self.sub_categories) + 1)\n ]\n for position, sub_category in enumerate(self.sub_categories):\n for match in range(len(matches)):\n if matches[match].startswith(sub_category):\n sentences_list = (\n matches[match].rsplit(\":\", 1)[-1].split(\".\", 1)[-1].split(\";\")\n )\n sub_category_dict_sentences[self.sub_categories[position]] = (\n sentences_list\n )\n return sub_category_dict_sentences\n \n def compute_sentences(self, response):\n return self.parse_error_sentences(response, self.categories[0])\n \n def get_representative_sentences(self, responses):\n list_sentences = []\n for i in responses:\n sentences = self.compute_sentences(i)\n list_sentences.append(sentences)\n dict_sentences = flatten_values_lists_of_list_dicts_to_dict(list_sentences)\n result_sentences_dict = {}\n for i in self.sub_categories:\n sentences = dict_sentences[i]\n sentences = [i for i in sentences if i.strip() != \"\"]\n _, sentences_of_largest_cluster = compute_largest_cluster(sentences)\n result_sentences_dict[i] = sentences_of_largest_cluster\n return result_sentences_dict\n \n def compute_accuracy(self, responses):\n counts = []\n for response in responses:\n _, sig_errors = self.parse_error_counts(response, self.categories[0])\n counts.append(sig_errors)\n counts = np.array(counts)\n dict_acc = {}\n for i in range(len(self.sub_categories)):\n error_counts = counts[:, i]\n accuracy = np.mean(error_counts == 0)\n dict_acc[self.sub_categories[i]] = accuracy\n return dict_acc\n \n def compute_summary(self):\n print(\"Computing summary ...\")\n representative_sentences = self.get_representative_sentences(self.completions)\n accuracies = self.compute_accuracy(self.completions)\n mean = np.mean(self.green_scores)\n std = np.std(self.green_scores)\n summary = f\"\\n-------------{self.model_name}----------------\\n [Summary]: Green average {mean} and standard deviation {std} \\n [Clinically Significant Errors Analyses]: . \\n\\n\"\n for idx, sub_category in enumerate(self.sub_categories):\n accuracy = accuracies[sub_category]\n sentences = representative_sentences[sub_category]\n summary += f\"{sub_category}: {accuracy}. \\n {sentences} \\n\\n\"\n summary += \"----------------------------------\\n\"\n return mean, std, summary\nif __name__ == \"__main__\":\n pass" } ] }, { "paper_id": 23, "paper_details": { "title": "Style-Specific Neurons for Steering LLMs in Text Style Transfer", "url": "https://arxiv.org/abs/2410.00593" }, "enviorment_name": "sneuron", "repo_original_url": "https://github.com/wenlai-lavine/sNeuron-TST", "project_path": "Benchmark/23-SpecificNeuro/sNeuron-TST-main", "file_organization": "\nsNeuron-TST-main/\n activation/\n activation.ParaDetox.neutral.train.llama-7b\n activation.ParaDetox.toxic.train.llama-7b\n activation.py\n Analysis/\n select_neurons.py\n compare.py\n data/\n id.formal.neutral.train.llama\n id.formal.toxic.train.llama\n test.neutral.txt\n test.toxic.txt\n train.neutral.txt\n train.toxic.txt\n data_pre/\n GYAFC/\n split_data.py\n ParaDetox/\n split_data.py\n politeness/\n split_data.py\n Politics/\n split_data.py\n Shakespeare/\n split_data.py\n env.sh\n Evaluation/\n cls/\n authorship.py\n formality.py\n politics.py\n politness.py\n run_cls.py\n sentiment.py\n toxicity.py\n fluency/\n fluency.py\n flu_eval.py\n mean_bleurt/\n eval_bleurt.py\n test.py\n mean_labse/\n mean_eval.py\n test.py\n sim/\n content_similarity.py\n sim_eval.py\n wieting_similarity/\n __init__.py\n similarity_evaluator.py\n sim_models.py\n sim_utils.py\n identify/\n inter_neurons/\n ParaDetox.inter_neurons.llama-7b\n non_inter_neurons/\n ParaDetox.neutral.llama-7b\n ParaDetox.toxic.llama-7b\n ParaDetox.llama-7b\n statistic_neurons.csv\n identify.py\n Our/\n contra_neurons.py\n dola.py\n gen_contrast_neurons.py\n run_gen_dola.py\n utils_new.py\n ppl.py\n README.md\n", "latex_code_path": "Benchmark/23-SpecificNeuro/arXiv-2410.00593v1", "task_details": [ { "task_id": 0, "indent": 1, "script": "\npython identify.py\n", "latex_code": "\nTo eliminate the overlap between neurons of different styles, we identify style-specific neurons and their intersection.\nFormally, suppose we have two distinct styles, denoted as $A$ and $B$.\nWe feed the corpora of the two styles to an LLM separately, to obtain the activation values of the neurons in the FFN layers for both styles, as described in Eq~(\\ref{eq:act_val}).\nWe then select the neurons whose activation value exceeds zero, forming two sets denoted as $S_A$ and $S_B$, respectively.\nSubsequently, we sort the activation values within $S_A$ and $S_B$ in descending order and select the neurons with the top $k$ values ($k = 500n, n\\in\\{1,2,3,\\dots,20\\}$ tuned on the validation set), resulting in $S_{A}^{\\prime}$ and $S_{B}^{\\prime}$.\n", "completion_path": "./identify.py", "namespace": "identify.identify_neurons", "type": "function", "signature_position": [ 21, 21 ], "body_position": [ 22, 56 ], "ReferenceCode_With_Comments": "\ntotal_neurons_list = []\nnum_layers, intermediate_size = positive_activation['over_zero'].size()\n \n# ---------------------------------------------------------------------------\n# Snippet 1: Compute activation differences (style A minus style B) and\n# select the top neurons for style A. The LaTeX describes forming sets of neurons\n# that exceed a threshold. Here, topk identifies those neurons most strongly \n# activated for style A.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\npositive_negative_difference = positive_activation['over_zero'] - negative_activation['over_zero']\npositive_negative_difference_sorted = torch.topk(positive_negative_difference.view(-1), threshold)\npositive_neurons = positive_negative_difference_sorted.indices.tolist()\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Organize these style-A neurons by layer, analogous to creating \n# S_A' in the LaTeX, and store them in a list for subsequent usage. \n# Sorting ensures consistent ordering within each layer\u2019s neuron indices.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nfinal_positive_neurons_list = [[] for _ in range(num_layers)]\nfor pn in positive_neurons:\n row_index = pn // intermediate_size\n col_index = pn % intermediate_size\n final_positive_neurons_list[row_index].append(col_index)\n\nfinal_positive_neurons = []\nfor fpn in final_positive_neurons_list:\n if fpn:\n tmp_list = sorted(fpn)\n final_positive_neurons.append(torch.tensor(tmp_list).long())\n else:\n final_positive_neurons.append(torch.tensor(fpn).long())\n\ntotal_neurons_list.append(final_positive_neurons)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Repeat the topk selection but with reversed subtraction \n# (style B minus style A). This identifies those neurons predominantly \n# contributing to style B, corresponding to S_B' in the LaTeX.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nnegative_positive_difference = negative_activation['over_zero'] - positive_activation['over_zero']\nnegative_positive_difference_sorted = torch.topk(negative_positive_difference.view(-1), args.threshold)\nnegative_neurons = negative_positive_difference_sorted.indices.tolist()\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Organize these style-B neurons per layer, completing the \n# LaTeX idea of forming disjoint style-specific sets. As with style A, \n# sorted lists of indices are created for each layer.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nfinal_negative_neurons_list = [[] for _ in range(num_layers)]\nfor nn in negative_neurons:\n row_index = nn // intermediate_size\n col_index = nn % intermediate_size\n final_negative_neurons_list[row_index].append(col_index)\n\nfinal_negative_neurons = []\nfor fnn in final_negative_neurons_list:\n if fnn:\n tmp_list = sorted(fnn)\n final_negative_neurons.append(torch.tensor(tmp_list).long())\n else:\n final_negative_neurons.append(torch.tensor(fnn).long())\n# [End Snippet 4]\n\ntotal_neurons_list.append(final_negative_neurons)\n\nreturn total_neurons_list\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The LaTeX description does not specify that neuron selection should be based on the **difference in activation counts** between the two styles. The reference code explicitly computes this difference (style A activations minus style B activations) to rank neurons, ensuring style-specific neurons are those with the strongest relative activation bias.\n - The LaTeX omits the requirement to **globally select top-k neurons across all layers**. The reference code flattens activation differences across all layers and selects the top-k neurons globally.\n\n - Mismatched Details:\n - The LaTeX describes selecting neurons \"whose activation value exceeds zero\" as the initial sets \\(S_A\\) and \\(S_B\\). However, the reference code **does not directly use these sets** but instead uses activation differences to define style-specific neurons.\n", "Missing_details": [ "\n- The LaTeX description does not specify that neuron selection should be based on the **difference in activation counts** between the two styles. The reference code explicitly computes this difference (style A activations minus style B activations) to rank neurons, ensuring style-specific neurons are those with the strongest relative activation bias.\n", "\n- The LaTeX omits the requirement to **globally select top-k neurons across all layers**. The reference code flattens activation differences across all layers and selects the top-k neurons globally.\n" ], "Mismatched_details": [ "\n- The LaTeX describes selecting neurons \"whose activation value exceeds zero\" as the initial sets \\(S_A\\) and \\(S_B\\). However, the reference code **does not directly use these sets** but instead uses activation differences to define style-specific neurons.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - positive_activation (dict): Precomputed activation stats for style A\n - Structure: {'over_zero': torch.Tensor[float, shape=(num_layers, intermediate_size)]}\n In this context, 'over_zero' represents the count of activations exceeding zero for each neuron across all layers in the corpus of style A.\n - negative_activation (dict): Precomputed activation stats for style B\n - Structure: {'over_zero': torch.Tensor[float, shape=(num_layers, intermediate_size)]}\n In this context, 'over_zero' represents the count of activations exceeding zero for each neuron across all layers in the corpus of style B.\n - threshold (int): Number of top neurons to select for each style\n", "Arguments_list": [ { "name": "positive_activation", "string": "\n- positive_activation (dict): Precomputed activation stats for style A\n - Structure: {'over_zero': torch.Tensor[float, shape=(num_layers, intermediate_size)]}\n In this context, 'over_zero' represents the count of activations exceeding zero for each neuron across all layers in the corpus of style A.\n", "dependency": null }, { "name": "negative_activation", "string": "\n- negative_activation (dict): Precomputed activation stats for style B\n - Structure: {'over_zero': torch.Tensor[float, shape=(num_layers, intermediate_size)]}\n In this context, 'over_zero' represents the count of activations exceeding zero for each neuron across all layers in the corpus of style B.\n", "dependency": null }, { "name": "threshold", "string": "\n- threshold (int): Number of top neurons to select for each style\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra File Dependencies:\n - None\n \n - Cross File Dependencies:\n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.topk\n - torch.tensor\n", "list": [ "torch.topk", "torch.tensor" ] }, "Return": { "Return_String": "\nOutput Variables:\n - total_neurons_list (list):\n [0] Style A specific neurons (list of LongTensors per layer)\n [1] Style B specific neurons (list of LongTensors per layer)\n", "return_list": [ { "name": "total_neurons_list", "string": "\n- total_neurons_list (list):\n [0] Style A specific neurons (list of LongTensors per layer)\n [1] Style B specific neurons (list of LongTensors per layer)\n", "dependency": null } ] }, "ori_python_file": "import argparse\nimport torch\nfrom tqdm import tqdm\nimport os\n\ndef identify_disjoint_neurons(positive_neurons, negative_neurons):\n positive_neurons_list = [i.tolist() for i in positive_neurons]\n negative_neurons_list = [i.tolist() for i in negative_neurons]\n final_inter_tensor = []\n pos_non_inter_tensor = []\n neg_non_inter_tensor = []\n for _, (pos, neg) in enumerate(zip(positive_neurons_list, negative_neurons_list)):\n tmp_inter = list(set(pos).intersection(set(neg)))\n final_inter_tensor.append(torch.tensor(tmp_inter).long())\n tmp_pos_non_inter = list(set(pos).difference(set(neg)))\n pos_non_inter_tensor.append(torch.tensor(tmp_pos_non_inter).long())\n tmp_neg_non_inter = list(set(neg).difference(set(pos)))\n neg_non_inter_tensor.append(torch.tensor(tmp_neg_non_inter).long())\n return final_inter_tensor, pos_non_inter_tensor, neg_non_inter_tensor\n\ndef identify_neurons(positive_activation, negative_activation, threshold):\n total_neurons_list = []\n num_layers, intermediate_size = positive_activation['over_zero'].size()\n positive_negative_difference = positive_activation['over_zero'] - negative_activation['over_zero']\n positive_negative_difference_sorted = torch.topk(positive_negative_difference.view(-1), threshold)\n positive_neurons = positive_negative_difference_sorted.indices.tolist()\n final_positive_neurons_list = [[] for _ in range(num_layers)]\n for pn in positive_neurons:\n row_index = pn // intermediate_size\n col_index = pn % intermediate_size\n final_positive_neurons_list[row_index].append(col_index)\n final_positive_neurons = []\n for fpn in final_positive_neurons_list:\n if fpn:\n tmp_list = sorted(fpn)\n final_positive_neurons.append(torch.tensor(tmp_list).long())\n else:\n final_positive_neurons.append(torch.tensor(fpn).long())\n total_neurons_list.append(final_positive_neurons)\n negative_positive_difference = negative_activation['over_zero'] - positive_activation['over_zero']\n negative_positive_difference_sorted = torch.topk(negative_positive_difference.view(-1), args.threshold)\n negative_neurons = negative_positive_difference_sorted.indices.tolist()\n final_negative_neurons_list = [[] for _ in range(num_layers)]\n for nn in negative_neurons:\n row_index = nn // intermediate_size\n col_index = nn % intermediate_size\n final_negative_neurons_list[row_index].append(col_index)\n final_negative_neurons = []\n for fnn in final_negative_neurons_list:\n if fnn:\n tmp_list = sorted(fnn)\n final_negative_neurons.append(torch.tensor(tmp_list).long())\n else:\n final_negative_neurons.append(torch.tensor(fnn).long())\n total_neurons_list.append(final_negative_neurons)\n return total_neurons_list\n\ndef main(args):\n style_list = ['ParaDetox']\n style_dict = {\n 'ParaDetox': ['toxic', 'neutral']\n }\n if not os.path.exists(args.out_path):\n os.makedirs(args.out_path, exist_ok=True)\n statistic_out_file = open(os.path.join(args.out_path, 'statistic_neurons.csv'), 'w')\n statistic_out_file.write('Style, Style_Name, Neurons\\n')\n for style in tqdm(style_list):\n positive_style = style_dict[style][0]\n negative_style = style_dict[style][1]\n positive_activation = torch.load(f\"{args.activation_path}/activation.{style}.{positive_style}.train.llama-7b\")\n negative_activation = torch.load(f\"{args.activation_path}/activation.{style}.{negative_style}.train.llama-7b\")\n total_neurons_list = identify_neurons(positive_activation, negative_activation, args.threshold)\n final_inter_tensor, pos_non_inter_tensor, neg_non_inter_tensor = identify_disjoint_neurons(total_neurons_list[0], total_neurons_list[1])\n torch.save(total_neurons_list, f\"{args.out_path}/{style}.llama-7b\")\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-t\", \"--threshold\", type=int, default=10000)\n parser.add_argument(\"-ap\", \"--activation_path\", type=str, default=\"./activation\")\n parser.add_argument(\"-tap\", \"--task_activation_path\", type=str, default=\"formal\")\n parser.add_argument(\"-o\", \"--out_path\", type=str, default=\"./identify\")\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n main(args)" }, { "task_id": 1, "indent": 1, "script": "\npython identify.py\n", "latex_code": "\nFinally, we identify the neurons associated with strictly one of the styles by computing the disjoint sets of the two smaller sets:\n$N_A = S_{A}^{\\prime} \\setminus S_{B}^{\\prime}$ and $N_B = S_{B}^{\\prime} \\setminus S_{A}^{\\prime}$.\n", "completion_path": "./identify.py", "namespace": "identify.identify_disjoint_neurons", "type": "function", "signature_position": [ 6, 6 ], "body_position": [ 7, 19 ], "ReferenceCode_With_Comments": "\npositive_neurons_list = [i.tolist() for i in positive_neurons]\nnegative_neurons_list = [i.tolist() for i in negative_neurons]\n\nfinal_inter_tensor = []\npos_non_inter_tensor = []\nneg_non_inter_tensor = []\n\nfor _, (pos, neg) in enumerate(zip(positive_neurons_list, negative_neurons_list)):\n # ---------------------------------------------------------------------------\n # Snippet 1: Intersection: Implements the insetsection of set A and set B: |S_A' \u2229 S_B'| \n # ---------------------------------------------------------------------------\n # [Begin Snippet 1]\n tmp_inter = list(set(pos).intersection(set(neg)))\n final_inter_tensor.append(torch.tensor(tmp_inter).long())\n # [End Snippet 1]\n \n # ---------------------------------------------------------------------------\n # Snippet 2: Style A Exclusives: Direct implementation of N_A = S_A' \\ S_B'\n # ---------------------------------------------------------------------------\n # [Begin Snippet 2]\n tmp_pos_non_inter = list(set(pos).difference(set(neg)))\n pos_non_inter_tensor.append(torch.tensor(tmp_pos_non_inter).long())\n # [End Snippet 2]\n \n # ---------------------------------------------------------------------------\n # Snippet 3: Exclusives: Direct implementation of N_B = S_B' \\ S_A'\n # ---------------------------------------------------------------------------\n # [Begin Snippet 3]\n tmp_neg_non_inter = list(set(neg).difference(set(pos)))\n neg_non_inter_tensor.append(torch.tensor(tmp_neg_non_inter).long())\n # [End Snippet 3]\n\nreturn final_inter_tensor, pos_non_inter_tensor, neg_non_inter_tensor\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - None\n \n - Mismatched Details:\n - None\n", "Missing_details": [], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - positive_neurons (list of torch.Tensor, num_layers of shape [num_neurons_in_layer]): \n Each element is a tensor representing neuron indices for style A in a particular \n layer. The shapes may vary, but typically each tensor is one-dimensional \n (i.e., [num_neurons_in_layer]).\n - negative_neurons (list of torch.Tensor, num_layers of shape [num_neurons_in_layer]):\n Each element is a tensor representing neuron indices for style B in a particular \n layer, analogous to `positive_neurons`.\n", "Arguments_list": [ { "name": "positive_neurons", "string": "\n- positive_neurons (list of torch.Tensor, num_layers of shape [num_neurons_in_layer]):\n Each element is a tensor representing neuron indices for style A in a particular \n layer. The shapes may vary, but typically each tensor is one-dimensional \n (i.e., [num_neurons_in_layer]).\n", "dependency": null }, { "name": "negative_neurons", "string": "\n- negative_neurons (list of torch.Tensor, num_layers of shape [num_neurons_in_layer]):\n Each element is a tensor representing neuron indices for style B in a particular \n layer, analogous to `positive_neurons`.\n", "dependency": null } ] }, "dependency": { "string": "\nRepository Dependencies:\n - Intra-File dependency: \n - None\n \n - Cross-File dependency: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.tensor\n", "list": [ "torch.tensor" ] }, "Return": { "Return_String": "\nOutput Variables:\n - final_inter_tensor (list of torch.Tensor):\n A list of tensors, where each tensor contains neuron indices that belong \n to both style A and style B in the corresponding layer.\n - pos_non_inter_tensor (list of torch.Tensor):\n A list of tensors, where each tensor contains neuron indices exclusive to style A \n in the corresponding layer.\n - neg_non_inter_tensor (list of torch.Tensor):\n A list of tensors, where each tensor contains neuron indices exclusive to style B \n in the corresponding layer.\n", "return_list": [ { "name": "final_inter_tensor", "string": "\n- final_inter_tensor (list of torch.Tensor):\n A list of tensors, where each tensor contains neuron indices that belong \n to both style A and style B in the corresponding layer.\n", "dependency": null }, { "name": "pos_non_inter_tensor", "string": "\n- pos_non_inter_tensor (list of torch.Tensor):\n A list of tensors, where each tensor contains neuron indices exclusive to style A \n in the corresponding layer.\n", "dependency": null }, { "name": "neg_non_inter_tensor", "string": "\n- neg_non_inter_tensor (list of torch.Tensor):\n A list of tensors, where each tensor contains neuron indices exclusive to style B \n in the corresponding layer.\n", "dependency": null } ] }, "ori_python_file": "import argparse\nimport torch\nfrom tqdm import tqdm\nimport os\n\ndef identify_disjoint_neurons(positive_neurons, negative_neurons):\n positive_neurons_list = [i.tolist() for i in positive_neurons]\n negative_neurons_list = [i.tolist() for i in negative_neurons]\n final_inter_tensor = []\n pos_non_inter_tensor = []\n neg_non_inter_tensor = []\n for _, (pos, neg) in enumerate(zip(positive_neurons_list, negative_neurons_list)):\n tmp_inter = list(set(pos).intersection(set(neg)))\n final_inter_tensor.append(torch.tensor(tmp_inter).long())\n tmp_pos_non_inter = list(set(pos).difference(set(neg)))\n pos_non_inter_tensor.append(torch.tensor(tmp_pos_non_inter).long())\n tmp_neg_non_inter = list(set(neg).difference(set(pos)))\n neg_non_inter_tensor.append(torch.tensor(tmp_neg_non_inter).long())\n return final_inter_tensor, pos_non_inter_tensor, neg_non_inter_tensor\n\ndef identify_neurons(positive_activation, negative_activation, threshold):\n total_neurons_list = []\n num_layers, intermediate_size = positive_activation['over_zero'].size()\n positive_negative_difference = positive_activation['over_zero'] - negative_activation['over_zero']\n positive_negative_difference_sorted = torch.topk(positive_negative_difference.view(-1), threshold)\n positive_neurons = positive_negative_difference_sorted.indices.tolist()\n final_positive_neurons_list = [[] for _ in range(num_layers)]\n for pn in positive_neurons:\n row_index = pn // intermediate_size\n col_index = pn % intermediate_size\n final_positive_neurons_list[row_index].append(col_index)\n final_positive_neurons = []\n for fpn in final_positive_neurons_list:\n if fpn:\n tmp_list = sorted(fpn)\n final_positive_neurons.append(torch.tensor(tmp_list).long())\n else:\n final_positive_neurons.append(torch.tensor(fpn).long())\n total_neurons_list.append(final_positive_neurons)\n negative_positive_difference = negative_activation['over_zero'] - positive_activation['over_zero']\n negative_positive_difference_sorted = torch.topk(negative_positive_difference.view(-1), args.threshold)\n negative_neurons = negative_positive_difference_sorted.indices.tolist()\n final_negative_neurons_list = [[] for _ in range(num_layers)]\n for nn in negative_neurons:\n row_index = nn // intermediate_size\n col_index = nn % intermediate_size\n final_negative_neurons_list[row_index].append(col_index)\n final_negative_neurons = []\n for fnn in final_negative_neurons_list:\n if fnn:\n tmp_list = sorted(fnn)\n final_negative_neurons.append(torch.tensor(tmp_list).long())\n else:\n final_negative_neurons.append(torch.tensor(fnn).long())\n total_neurons_list.append(final_negative_neurons)\n return total_neurons_list\n\ndef main(args):\n style_list = ['ParaDetox']\n style_dict = {\n 'ParaDetox': ['toxic', 'neutral']\n }\n if not os.path.exists(args.out_path):\n os.makedirs(args.out_path, exist_ok=True)\n statistic_out_file = open(os.path.join(args.out_path, 'statistic_neurons.csv'), 'w')\n statistic_out_file.write('Style, Style_Name, Neurons\\n')\n for style in tqdm(style_list):\n positive_style = style_dict[style][0]\n negative_style = style_dict[style][1]\n positive_activation = torch.load(f\"{args.activation_path}/activation.{style}.{positive_style}.train.llama-7b\")\n negative_activation = torch.load(f\"{args.activation_path}/activation.{style}.{negative_style}.train.llama-7b\")\n total_neurons_list = identify_neurons(positive_activation, negative_activation, args.threshold)\n final_inter_tensor, pos_non_inter_tensor, neg_non_inter_tensor = identify_disjoint_neurons(total_neurons_list[0], total_neurons_list[1])\n torch.save(total_neurons_list, f\"{args.out_path}/{style}.llama-7b\")\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-t\", \"--threshold\", type=int, default=10000)\n parser.add_argument(\"-ap\", \"--activation_path\", type=str, default=\"./activation\")\n parser.add_argument(\"-tap\", \"--task_activation_path\", type=str, default=\"formal\")\n parser.add_argument(\"-o\", \"--out_path\", type=str, default=\"./identify\")\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n main(args)" } ] }, { "paper_id": 24, "paper_details": { "title": "Language-Specific Neurons: The Key to Multilingual Capabilities in Large Language Models", "url": "https://arxiv.org/pdf/2402.16438" }, "enviorment_name": "sneuron", "repo_original_url": "https://github.com/RUCAIBox/Language-Specific-Neurons", "project_path": "Benchmark/24-Language_Neuron/Language-Specific-Neurons-main", "file_organization": "\nLanguage-Specific-Neurons-main/\n activations/\n activation.en.train.llama-7b\n activation.es.train.llama-7b\n activation.fr.train.llama-7b\n activation.id.train.llama-7b\n activation.ja.train.llama-7b\n activation.vi.train.llama-7b\n activation.zh.train.llama-7b\n data/\n mvicuna/\n en.txt\n es.txt\n fr.txt\n id.txt\n ja.txt\n vi.txt\n zh.txt\n activation.py\n generation.py\n identify.py\n ppl.py\n README.md\n", "latex_code_path": "Benchmark/24-Language_Neuron/arXiv-2402.16438v2", "task_details": [ { "task_id": 0, "indent": 1, "script": "\npython identify.py\n", "latex_code": "\nOur research primarily focuses on pre-trained foundation models (\\eg LLaMA-2 and BLOOM), rather than fine-tuned models that have undergone instruction tuning or RLHF, which helps reduce other influencing factors.\nSpecially, we feed existing LLMs with multilingual texts, each written in a single language. \nFor the $j$-th neuron in the $i$-th layer, we then compute the \\emph{activation probability} when processing texts in language $k$:\n\\begin{equation} \\label{eq-4} \np^k_{i,j} = \\mathbb{E}\\left(\\mathbb{I}(\\text{act\\_fn}(\\tilde{\\bm{h}}^i \\bm{W}^i_1)_j > 0) \\mid \\text{language } k \\right),\n\\end{equation}\nwhere $\\mathbb{I}$ is the indicator function.\nThe activation probability is empirically estimated by the likelihood that the neuron's activation value exceeds zero.\nSubsequently, we can obtain the distribution $\\bm{p}_{i,j} = (p^1_{i,j}, \\dots, p^k_{i,j}, \\dots, p^l_{i,j})$ for each neuron, indicating its probability of activation for each language.\nTo convert $\\bm{p}_{i,j}$ into a valid probability distribution, we apply L1 normalization, yielding $\\bm{p}_{i,j}'$. The entropy of this distribution, which we refer to as \\emph{language activation probability entropy}, is computed to quantify the neuron's language activation reaction:\n\\begin{equation} \\label{eq-5}\n \\text{LAPE}_{i,j} = -\\sum_{k=1}^l p'^{k}_{i,j} \\log (p'^{k}_{i,j}).\n\\end{equation}\nWe designate neurons with low LAPE scores as ``\\textbf{language-specific neurons}'', as they demonstrate a predilection for activation in response to one or two languages, while showing reduced activation probabilities for others.\n\n\nIn implementation, we collect multilingual corpora sourced from Wikipedia, a widely recognized and high-quality resource for diverse languages, and sample documents to create a dataset comprising 100 million tokens for each language. Subsequently, we input these tokens into a target LLM and follow Equations~\\ref{eq-4} and~\\ref{eq-5} to compute the LAPE score for individual neurons. Finally, we select neurons that fall within the lowest percentile of LAPE scores, specifically targeting the bottom 1\\%. To refine our selection, we further impose a predefined threshold to exclude neurons exhibiting negligible activation probability: a neuron is deemed specific to language $k$ if its corresponding activation probability $p^{k}_{i,j}$ surpasses the threshold.\n", "completion_path": "./identify.py", "namespace": "identify.activation", "type": "function", "signature_position": [ 4, 4 ], "body_position": [ 5, 37 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Calculate the activation probabilities by normalizing the \n# 'over_zero' tensor with the total number of samples 'n'. This corresponds \n# to Equation (4) in the LaTeX code, where the activation probability \n# p^k_{i,j} is computed.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nactivation_probs = over_zero / n # layer x neuron x lang_num\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Normalize the activation probabilities across languages using \n# L1 normalization to obtain a valid probability distribution. This step aligns \n# with the normalization process described before computing entropy in Equation (5).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nnormed_activation_probs = activation_probs / activation_probs.sum(dim=-1, keepdim=True)\nnormed_activation_probs[torch.isnan(normed_activation_probs)] = 0\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Compute the logarithm of the normalized activation probabilities, \n# ensuring numerical stability by setting log probabilities to zero where \n# probabilities are zero.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nlog_probs = torch.where(normed_activation_probs > 0, normed_activation_probs.log(), 0)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Calculate the entropy for each neuron by summing the product \n# of normalized probabilities and their logarithms, as defined in Equation (5).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nentropy = -torch.sum(normed_activation_probs * log_probs, dim=-1)\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Determine the threshold for filtering neurons by finding the \n# top probability value based on the 'filter_rate'. Neurons with no language \n# exceeding this threshold are assigned an infinite entropy to exclude them \n# from selection.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nlargest = False\nflattened_probs = activation_probs.flatten()\ntop_prob_value = flattened_probs.kthvalue(round(len(flattened_probs) * filter_rate)).values.item()\nprint(top_prob_value)\ntop_position = (activation_probs > top_prob_value).sum(dim=-1)\nentropy[top_position == 0] = -torch.inf if largest else torch.inf\n# [End Snippet 5]\n\n# ---------------------------------------------------------------------------\n# Snippet 6: Flatten the entropy tensor and select the top neurons with the \n# lowest entropy scores based on the 'top_rate'. This corresponds to selecting \n# the bottom 1% of neurons with the lowest LAPE scores.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 6]\nflattened_entropy = entropy.flatten()\ntop_entropy_value = round(len(flattened_entropy) * top_rate)\n_, index = flattened_entropy.topk(top_entropy_value, largest=largest)\n# [End Snippet 6]\n\n# ---------------------------------------------------------------------------\n# Snippet 7: Retrieve the row and column indices of the selected neurons and \n# extract their corresponding activation probabilities.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 7]\nrow_index = index // entropy.size(1)\ncol_index = index % entropy.size(1)\nselected_probs = activation_probs[row_index, col_index] # n x lang\n# [End Snippet 7]\n\n# ---------------------------------------------------------------------------\n# Snippet 8: Transpose the selected probabilities and apply the activation bar \n# ratio to further filter neurons that exceed the activation threshold.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 8]\nselected_probs = selected_probs.transpose(0, 1)\nactivation_bar = flattened_probs.kthvalue(round(len(flattened_probs) * activation_bar_ratio)).values.item()\nprint((selected_probs > activation_bar).sum(dim=1).tolist())\nlang, indice = torch.where(selected_probs > activation_bar)\n# [End Snippet 8]\n\n# ---------------------------------------------------------------------------\n# Snippet 9: Merge the row and column indices, sort them, and organize the final \n# selected neuron indices by layer and language. This finalizes the selection of \n# language-specific neurons based on the computed entropy and activation thresholds.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 9]\nmerged_index = torch.stack((row_index, col_index), dim=-1)\nfinal_indice = []\nfor _, index in enumerate(indice.split(torch.bincount(lang).tolist())):\n lang_index = [tuple(row.tolist()) for row in merged_index[index]]\n lang_index.sort()\n layer_index = [[] for _ in range(num_layers)]\n for l, h in lang_index:\n layer_index[l].append(h)\n for l, h in enumerate(layer_index):\n layer_index[l] = torch.tensor(h).long()\n final_indice.append(layer_index)\n# [End Snippet 9]\n\nreturn final_indice\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The process of filtering neurons based on a global threshold derived from the distribution of all activation probabilities across layers, neurons, and languages is not detailed. Specifically, after calculating activation probabilities, an additional step is needed to determine a cutoff value (e.g., based on a high percentile of all activation probabilities) and use it to exclude neurons that do not have at least one language exceeding this threshold. \n - Handling of zero-sum normalization edge cases. The LaTeX does not mention how to handle neurons with zero activation across all languages during L1 normalization. The reference code explicitly sets normalized probabilities to zero in such cases, but the LaTeX lacks this specification.\n \n Mismatched Details:\n - The LaTeX description implies that neuron selection is finalized by applying a predefined threshold to the activation probability for a specific language after entropy computation (i.e., a neuron is deemed specific to a language if its activation probability for that language exceeds the threshold). However, the reference implementation first selects neurons with the lowest entropy scores globally across all layers and neurons, then applies a threshold to the activation probabilities of these selected neurons to assign language specificity. This mismatch in sequence\u2014global entropy-based selection followed by threshold filtering versus threshold filtering as part of the final designation\u2014alters which neurons are ultimately chosen as language-specific.\n", "Missing_details": [ "\n- The process of filtering neurons based on a global threshold derived from the distribution of all activation probabilities across layers, neurons, and languages is not detailed. Specifically, after calculating activation probabilities, an additional step is needed to determine a cutoff value (e.g., based on a high percentile of all activation probabilities) and use it to exclude neurons that do not have at least one language exceeding this threshold. \n", "\n- Handling of zero-sum normalization edge cases. The LaTeX does not mention how to handle neurons with zero activation across all languages during L1 normalization. The reference code explicitly sets normalized probabilities to zero in such cases, but the LaTeX lacks this specification.\n" ], "Mismatched_details": [ "\n- The LaTeX description implies that neuron selection is finalized by applying a predefined threshold to the activation probability for a specific language after entropy computation (i.e., a neuron is deemed specific to a language if its activation probability for that language exceeds the threshold). However, the reference implementation first selects neurons with the lowest entropy scores globally across all layers and neurons, then applies a threshold to the activation probabilities of these selected neurons to assign language specificity. This mismatch in sequence\u2014global entropy-based selection followed by threshold filtering versus threshold filtering as part of the final designation\u2014alters which neurons are ultimately chosen as language-specific.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - n (torch.Tensor, shape=[language_num]): The total number of samples or instances considered for activation probability calculation.\n - over_zero (torch.Tensor, dtype=torch.float32, shape=[layer, neuron, language_num]): \n Tensor indicating the number of times each neuron in each layer was activated \n (i.e., activation value exceeded zero) for each language.\n - top_rate (float, default=0.01): \n The proportion of neurons with the lowest entropy scores to select as language-specific.\n - filter_rate (float, default=0.95): \n The percentile threshold to determine the top probability value for filtering neurons.\n - activation_bar_ratio (float, default=0.95): \n The threshold ratio to further filter neurons based on their activation probabilities.\n", "Arguments_list": [ { "name": "text", "string": "\n- n (torch.Tensor, shape=[language_num]): The total number of samples or instances considered for activation probability calculation.\n", "dependency": null }, { "name": "over_zero", "string": "\n- over_zero (torch.Tensor, dtype=torch.float32, shape=[layer, neuron, language_num]): \n Tensor indicating the number of times each neuron in each layer was activated \n (i.e., activation value exceeded zero) for each language.\n", "dependency": null }, { "name": "top_rate", "string": "\n- top_rate (float, default=0.01):\n The proportion of neurons with the lowest entropy scores to select as language-specific.\n", "dependency": null }, { "name": "filter_rate", "string": "\n- filter_rate (float, default=0.95):\n The percentile threshold to determine the top probability value for filtering neurons.\n", "dependency": null }, { "name": "activation_bar_ratio", "string": "\n- activation_bar_ratio (float, default=0.95):\n The threshold ratio to further filter neurons based on their activation probabilities.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra File Dependencies:\n - None\n \n - Cross File Dependencies:\n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.where\n - torch.sum\n - torch.isnan\n - torch.stack\n - torch.bincount\n - torch.tensor\n", "list": [ "torch.where", "torch.sum", "torch.isnan", "torch.stack", "torch.bincount", "torch.tensor" ] }, "Return": { "Return_String": "\nOutput Variables:\n - final_indice (list[list[torch.Tensor]], [language_num x layer x neuron]): \n A structured list containing the indices of selected language-specific neurons \n organized by layer and language.\n", "return_list": [ { "name": "final_indice", "string": "\n- final_indice (list[list[torch.Tensor]], [language_num x layer x neuron]): \n A structured list containing the indices of selected language-specific neurons \n organized by layer and language.\n", "dependency": null } ] }, "ori_python_file": "import torch\nimport torch.nn.functional as F\n\ndef activation(n, over_zero, num_layers, top_rate=0.01, filter_rate=0.95, activation_bar_ratio=0.95):\n activation_probs = over_zero / n\n normed_activation_probs = activation_probs / activation_probs.sum(dim=-1, keepdim=True)\n normed_activation_probs[torch.isnan(normed_activation_probs)] = 0\n log_probs = torch.where(normed_activation_probs > 0, normed_activation_probs.log(), 0)\n entropy = -torch.sum(normed_activation_probs * log_probs, dim=-1)\n largest = False\n flattened_probs = activation_probs.flatten()\n top_prob_value = flattened_probs.kthvalue(round(len(flattened_probs) * filter_rate)).values.item()\n print(top_prob_value)\n top_position = (activation_probs > top_prob_value).sum(dim=-1)\n entropy[top_position == 0] = -torch.inf if largest else torch.inf\n flattened_entropy = entropy.flatten()\n top_entropy_value = round(len(flattened_entropy) * top_rate)\n _, index = flattened_entropy.topk(top_entropy_value, largest=largest)\n row_index = index // entropy.size(1)\n col_index = index % entropy.size(1)\n selected_probs = activation_probs[row_index, col_index]\n selected_probs = selected_probs.transpose(0, 1)\n activation_bar = flattened_probs.kthvalue(round(len(flattened_probs) * activation_bar_ratio)).values.item()\n print((selected_probs > activation_bar).sum(dim=1).tolist())\n lang, indice = torch.where(selected_probs > activation_bar)\n merged_index = torch.stack((row_index, col_index), dim=-1)\n final_indice = []\n for _, index in enumerate(indice.split(torch.bincount(lang).tolist())):\n lang_index = [tuple(row.tolist()) for row in merged_index[index]]\n lang_index.sort()\n layer_index = [[] for _ in range(num_layers)]\n for l, h in lang_index:\n layer_index[l].append(h)\n for l, h in enumerate(layer_index):\n layer_index[l] = torch.tensor(h).long()\n final_indice.append(layer_index)\n return final_indice\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n n, over_zero = [], []\n for lang in ['en', 'zh', 'fr', 'es', 'vi', 'id', 'ja']:\n data = torch.load(f'./activations/activation.{lang}.train.llama-7b')\n n.append(data['n'])\n over_zero.append(data['over_zero'])\n n = torch.tensor(n)\n over_zero = torch.stack(over_zero, dim=-1)\n num_layers, intermediate_size, lang_num = over_zero.size()\n final_indice = activation(n, over_zero, num_layers)" }, { "task_id": 1, "indent": 1, "script": "\npython activation.py\n", "latex_code": "\nSpecially, we feed existing LLMs with multilingual texts, each written in a single language. \nFor the $j$-th neuron in the $i$-th layer, we then compute the \\emph{activation probability} when processing texts in language $k$:\n\\begin{equation} \\label{eq-4} \np^k_{i,j} = \\mathbb{E}\\left(\\mathbb{I}(\\text{act\\_fn}(\\tilde{\\bm{h}}^i \\bm{W}^i_1)_j > 0) \\mid \\text{language } k \\right),\n\\end{equation}\nwhere $\\mathbb{I}$ is the indicator function.\nThe activation probability is empirically estimated by the likelihood that the neuron's activation value exceeds zero.\n", "completion_path": "./activation.py", "namespace": "activation.find_activation", "type": "function", "signature_position": [ 6, 6 ], "body_position": [ 7, 23 ], "ReferenceCode_With_Comments": "\nover_zero = torch.zeros(num_layers, intermediate_size, dtype=torch.int32).to('cuda')\n\n# ---------------------------------------------------------------------------\n# Snippet 1: This inner function conceptually intercepts the model's MLP \n# computation to register how often each neuron\u2019s activation is greater \n# than zero, reflecting the indicator function I(. > 0) in Eq. (4).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\ndef factory(idx):\n def llama_forward(self, x):\n gate_up, _ = self.gate_up_proj(x)\n i = gate_up.size(-1)\n\n # Apply an activation function as described in Eq. (4), tracking which\n # outputs exceed zero.\n gate_up[:, :i // 2] = torch.nn.SiLU()(gate_up[:, :i // 2])\n\n activation = gate_up[:, :i // 2].float()\n\n # Accumulate the count of positive activations for each neuron,\n # paralleling the indicator function in Eq. (4).\n over_zero[idx, :] += (activation > 0).sum(dim=0)\n\n # The snippet then continues with the model\u2019s usual MLP flow,\n # which is beyond the direct scope of Eq. (4).\n x = gate_up[:, :i // 2] * gate_up[:, i // 2:]\n x, _ = self.down_proj(x)\n return x\n\n return llama_forward\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Here, we systematically hook the newly defined forward method \n# to each MLP layer. This step ensures that we capture the neuron activation \n# counts across all targeted layers, consistent with the multi-layer notion\n# implied in Eq. (4).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nfor i in range(num_layers):\n obj = model.llm_engine.model_executor.driver_worker.model_runner.model.model.layers[i].mlp\n obj.forward = MethodType(factory(i), obj)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: The function next generates outputs from the model, prompting \n# it with the specified tokens. As the model processes the tokens, the \n# activation counters are updated to reflect the indicator sums from Eq. (4). \n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\noutput = model.generate(prompt_token_ids=input_ids.tolist(), sampling_params=SamplingParams(max_tokens=1))\n\nreturn over_zero\n# [End Snippet 3]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX description does not specify the exact point within the model's multilayer perceptron (MLP) where the activation probability is calculated. In practice, the computation involves splitting an intermediate projection into two parts, applying an activation function to one part, and then measuring how often the resulting values exceed zero.\n\n Mismatched Details:\n - The LaTeX generically references \"act_fn\" but does not explicitly state that SiLU is used instead of ReLU. This mismatch causes the generated code to apply an incorrect activation function (ReLU) for threshold detection.\n - The reference code modifies the entire transformation rather than just hooking a single feedforward layer. In other words, the LaTeX-based outline omits the step that fully replaces the internal forward pass to track neuron activations at the correct stage of computation.\n", "Missing_details": [ "\n- The LaTeX description does not specify the exact point within the model's multilayer perceptron (MLP) where the activation probability is calculated. In practice, the computation involves splitting an intermediate projection into two parts, applying an activation function to one part, and then measuring how often the resulting values exceed zero.\n" ], "Mismatched_details": [ "\n- The LaTeX generically references \"act_fn\" but does not explicitly state that SiLU is used instead of ReLU. This mismatch causes the generated code to apply an incorrect activation function (ReLU) for threshold detection.\n", "\n- The reference code modifies the entire transformation rather than just hooking a single feedforward layer. In other words, the LaTeX-based outline omits the step that fully replaces the internal forward pass to track neuron activations at the correct stage of computation.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - input_ids (torch.Tensor, shape=(batch_size, max_length)): \n Token IDs representing the text inputs to be processed by the model.\n - model (an object of the vllm.entrypoints.llm.LLM class): \n A vllm.entrypoints.llm.LLM instance providing a generate method and containing the layers in which we capture neuron activations.\n - num_layers (int): \n The number of layers in the model whose neuron activations are tracked.\n - intermediate_size (int): \n The dimensionality of the neuron's intermediate output in each layer.\n", "Arguments_list": [ { "name": "input_ids", "string": "\n- input_ids (torch.Tensor, shape=(batch_size, max_length)):\n Token IDs representing the text inputs to be processed by the model.\n", "dependency": null }, { "name": "model", "string": "\n- model (an object of the vllm.entrypoints.llm.LLM class):\n A vllm.entrypoints.llm.LLM instance providing a generate method and containing the layers in which we capture neuron activations.\n", "dependency": "vllm.entrypoints.llm.LLM" }, { "name": "num_layers", "string": "\n- num_layers (int):\n The number of layers in the model whose neuron activations are tracked.\n", "dependency": null }, { "name": "intermediate_size", "string": "\n- intermediate_size (int):\n The dimensionality of the neuron's intermediate output in each layer.\n", "dependency": null } ] }, "dependency": { "string": "\nRepository Dependencies:\n - Intra-File Dependency: \n - None\n\n - Cross-File Dependency: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - vllm.SamplingParams\n - types.MethodType\n - torch.nn.SiLU\n - torch.zeros\n", "list": [ "vllm.SamplingParams", "types.MethodType", "torch.nn.SiLU", "torch.zeros" ] }, "Return": { "Return_String": "\nOutput Variables:\n - over_zero (torch.Tensor, shape=(num of layers, hidden_dim)): a tensor holding the summed activations above zero across all neurons in all tracked layers.\n", "return_list": [ { "name": "over_zero", "string": "\n- over_zero (torch.Tensor, shape=(num of layers, hidden_dim)): a tensor holding the summed activations above zero across all neurons in all tracked layers.\n", "dependency": null } ] }, "ori_python_file": "import argparse\nfrom types import MethodType\nimport torch\nfrom vllm import LLM, SamplingParams\n\ndef find_activation(input_ids, model, num_layers, intermediate_size):\n over_zero = torch.zeros(num_layers, intermediate_size, dtype=torch.int32).to('cuda')\n def factory(idx):\n def llama_forward(self, x):\n gate_up, _ = self.gate_up_proj(x)\n i = gate_up.size(-1)\n gate_up[:, :i // 2] = torch.nn.SiLU()(gate_up[:, :i // 2])\n activation = gate_up[:, :i // 2].float()\n over_zero[idx, :] += (activation > 0).sum(dim=0)\n x = gate_up[:, :i // 2] * gate_up[:, i // 2:]\n x, _ = self.down_proj(x)\n return x\n return llama_forward\n for i in range(num_layers):\n obj = model.llm_engine.model_executor.driver_worker.model_runner.model.model.layers[i].mlp\n obj.forward = MethodType(factory(i), obj)\n output = model.generate(prompt_token_ids=input_ids.tolist(), sampling_params=SamplingParams(max_tokens=1))\n return over_zero\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-m\", \"--model\", type=str, default=\"meta-llama/Llama-2-7b-hf\")\n parser.add_argument(\"-l\", \"--lang\", type=str, default=\"zh\")\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n is_llama = bool(args.model.lower().find('llama') >= 0)\n model = LLM(model=args.model, tensor_parallel_size=torch.cuda.device_count(), enforce_eager=True)\n max_length = model.llm_engine.model_config.max_model_len\n num_layers = model.llm_engine.model_config.hf_config.num_hidden_layers\n intermediate_size = model.llm_engine.model_config.hf_config.intermediate_size if is_llama else model.llm_engine.model_config.hf_config.hidden_size * 4\n lang = args.lang\n ids = torch.load(f'data/id.{lang}.train.llama')\n ids = torch.tensor(ids).to('cuda')\n l = ids.size(0)\n l = min(l, 99999744) // max_length * max_length\n input_ids = ids[:l].reshape(-1, max_length)\n output = find_activation(input_ids, model, num_layers, intermediate_size)" } ] }, { "paper_id": 25, "paper_details": { "title": "Reasoning Paths Optimization: Learning to Reason and Explore From Diverse Paths", "url": "https://arxiv.org/abs/2410.10858" }, "enviorment_name": "rpo", "repo_original_url": "https://github.com/DAMO-NLP-SG/reasoning-paths-optimization", "project_path": "Benchmark/25-reasoning_path/reasoning-paths-optimization-main", "file_organization": "\nreasoning-paths-optimization-main/\n branching.py\n data_loading.py\n dataset_info.json\n demonstrations.py\n evaluation.py\n inference.py\n LICENSE\n Llama\n merging.py\n models/\n Meta-Llama-3-8B/\n config.json\n generation_config.json\n LICENSE\n model-00001-of-00004.safetensors\n model-00002-of-00004.safetensors\n model-00003-of-00004.safetensors\n model-00004-of-00004.safetensors\n model.safetensors.index.json\n original/\n consolidated.00.pth\n params.json\n tokenizer.model\n README.md\n special_tokens_map.json\n tokenizer_config.json\n tokenizer.json\n USE_POLICY.md\n punkt.zip\n README.md\n requirements.txt\n run_orpo.py\n scripts/\n rpo_quick_start.sh\n train_reason_paths.sh\n utils.py\n", "latex_code_path": "Benchmark/25-reasoning_path/arXiv-2410.10858v1", "task_details": [ { "task_id": 0, "indent": 1, "script": "\npython evaluation.py --data_name gsm8k --demo_name gsm8k --path_model models/Meta-Llama-3-8B --data_split train \n", "latex_code": "\n\\subsection{Reasoning Generation}\n\\label{sec:RG}\nWhile training with explanations or step-by-step reasoning paths \\cite{mukherjee2023orca} can improve the reasoning performance of language models, it is labor-intensive and \ncostly\nto annotate such data.\nHence, our framework begins with\na reasoning generation stage that automatically generates the reference reasoning paths.\nConcretely, given a problem question \\( Q \\), we use chain-of-thought prompting \\cite{wei2022chain} to generate reasoning paths. \nThe chain-of-thought demonstration input $D_{CoT}$ consists of $m$ ground-truth examples, \nwhere each example is a pair consisting of a problem question and its corresponding reasoning path.\nLet $M$ be the base model, and we sample the reference reasoning path $P$ by prompting the model with the chain-of-thought demonstration $D_{CoT}$ and the given question $Q$. \nWe use temperature sampling \\cite{fan-etal-2018-hierarchical} with a fixed temperature $T$:\n\n\\begin{align}\n P \\sim M(D_{CoT}, Q | T)\n\\end{align}\n \nWe consider the generated path as correct if it concludes with a correct answer. Therefore, we define the following function \\( \\mathcal{F} \\) to verify if the last step $S_n \\in P$ contains the ground-truth answer $A$:\n\\begin{align}\n\\mathcal{F}(P) = \n\\begin{cases} \n1 & \\text{if } A \\in S_n \\\\\n0 & \\text{otherwise}\n\\end{cases}\n\\end{align}\n\nIf the outputs are incorrect, i.e., \\( \\mathcal{F}(P_i) = 0 \\), we repeat the sampling and verification process until \\( \\mathcal{F}(P_i) = 1 \\) \nwith a cap of 10 attempts, i.e., $i \\leq 10$.\n", "completion_path": "./evaluation.py", "namespace": "evaluation.gen_reason", "type": "function", "signature_position": [ 80, 80 ], "body_position": [ 81, 92 ], "ReferenceCode_With_Comments": "\nscores = []\nprogress = tqdm(samples)\n\nfor i, sample in enumerate(progress):\n\n # -----------------------------------------------------------------------\n # Snippet 1: Constructs the chain-of-thought style prompt (D_{CoT}, Q) and \n # obtains multiple reasoning paths (raw_outputs). This corresponds to the \n # LaTeX sampling process \\( P \\sim M(D_{CoT}, Q | T) \\). The code then \n # extracts answers from each raw output, similar to verifying if \\( A \\in S_n \\).\n # -----------------------------------------------------------------------\n # [Begin Snippet 1]\n sample.prompt = demo.make_prompt(sample.question)\n sample.raw_outputs = model.run_many(sample.prompt, num_sample)\n for o in sample.raw_outputs:\n sample.preds.append(demo.extract_answer(o))\n sample.accept_answer = demo.extract_answer(sample.accept_answer)\n # [End Snippet 1]\n\n # -----------------------------------------------------------------------\n # Snippet 2: Evaluates the correctness of the predictions by checking if \n # the most common predicted answer matches the ground-truth. This aligns \n # with the function \\(\\mathcal{F}(P)\\) in the LaTeX, albeit in a simplified \n # form without repeated sampling.\n # -----------------------------------------------------------------------\n # [Begin Snippet 2]\n scores.append(get_most_common(sample.preds) == sample.accept_answer)\n progress.set_postfix(accuracy=sum(scores) / len(scores))\n # [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Computes and returns the overall accuracy of the model's predictions,\n# akin to summarizing how many samples satisfied the correctness condition in \n# the LaTeX description.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\naverage_accuracy = sum(scores) / len(scores)\n\nreturn average_accuracy\n# [End Snippet 3]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Detail: \n - The LaTeX says \"repeat the sampling and verification process until F(Pi) = 1 with a cap of 10 attempts.\" The reference code does *not* repeat the sampling process for each question. Instead, the reference code sample num_sample times for one question and check them all uses majority vote across 10 paths.\n\n - Mismatched Detail: \n - None\n", "Missing_details": [ "\n- The LaTeX says \"repeat the sampling and verification process until F(Pi) = 1 with a cap of 10 attempts.\" The reference code does *not* repeat the sampling process for each question. Instead, the reference code sample num_sample times for one question and check them all uses majority vote across 10 paths.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - samples (list[ReasonSample]): \n A list of ReasonSample objects defined in data_loading.py. Each sample object is expected to have attributes such as\n 'question', 'accept_explanation', and placeholders for 'answer_prefix', 'prompt', etc.\n - demo (an object of the GSM8KDemonstration class defined in demonstrations.py):\n An object designed to handle demonstration construction.\n - model (an object of VLLMModel class defined in inference.py):\n It is responsible for generating multiple outputs (branches) for a given input prompt.\n - num_sample (int, default=10): Specifies how many outputs (reasoning paths) to sample per question in a single pass.\n", "Arguments_list": [ { "name": "samples", "string": "\n- samples (list[ReasonSample]): \n A list of ReasonSample objects defined in data_loading.py. Each sample object is expected to have attributes such as\n 'question', 'accept_explanation', and placeholders for 'answer_prefix', 'prompt', etc.\n", "dependency": "data_loading.ReasonSample" }, { "name": "demo", "string": "\n- demo (an object of the GSM8KDemonstration class defined in demonstrations.py):\n An object designed to handle demonstration construction.\n", "dependency": "demonstrations.GSM8KDemonstration" }, { "name": "model", "string": "\n- model (an object of VLLMModel class defined in inference.py):\n It is responsible for generating multiple outputs (branches) for a given input prompt.\n", "dependency": "inference.VLLMModel" }, { "name": "num_sample", "string": "\n- num_sample (int, default=10): Specifies how many outputs (reasoning paths) to sample per question in a single pass.\n", "dependency": null } ] }, "dependency": { "string": "\nRepository Dependencies:\n - Intra-File Dependencies: \n - get_most_common\n \n - Cross-File Dependencies:\n - None\n", "intra_file": [ "get_most_common" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - tqdm.tqdm\n", "list": [ "tqdm.tqdm" ] }, "Return": { "Return_String": "\nOutput Variables:\n - average_accuracy (float): The fraction of questions for which the most \n frequently predicted answer matches the ground-truth answer. Serves as an \n overall measure of correctness.\n", "Return_list": [ { "name": "average_accuracy", "string": "\n- average_accuracy (float): The fraction of questions for which the most\n frequently predicted answer matches the ground-truth answer. Serves as an\n overall measure of correctness.\n", "dependency": null } ] }, "ori_python_file": "import os\nfrom pathlib import Path\nfrom collections import Counter\nfrom fire import Fire\nfrom tqdm import tqdm\nfrom data_loading import select_data\nfrom demonstrations import select_demonstration\nfrom inference import VLLMModel\nimport argparse\n\ndef make_output_name(**kwargs) -> str:\n parts = [f\"{k}={str(v).replace('/', '-')}\" for k, v in kwargs.items()]\n return \"-\".join(parts)\n\ndef evaluate(data_name: str, demo_name: str, output_dir: str = \"outputs\", **kwargs):\n os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n path_out = Path(\n output_dir, make_output_name(eval_data=data_name, demo=demo_name, **kwargs)\n ).with_suffix(\".jsonl\")\n model = VLLMModel(**kwargs)\n data = select_data(data_name, data_split=\"test\")\n demo = select_demonstration(demo_name)\n model.stopping_words = demo.get_stopping_words()\n scores = []\n progress = tqdm(data.samples, desc=str(path_out))\n path_out.parent.mkdir(parents=True, exist_ok=True)\n with open(path_out, \"w\") as f:\n for i, sample in enumerate(progress):\n sample.prompt = demo.make_prompt(sample.question)\n sample.raw_outputs.append(model.run(sample.prompt))\n for o in sample.raw_outputs:\n sample.preds.append(demo.extract_answer(o))\n sample.accept_answer = demo.extract_answer(sample.accept_answer)\n scores.append(sample.preds[0] == sample.accept_answer)\n progress.set_postfix(accuracy=sum(scores) / len(scores))\n print(sample.model_dump_json(indent=2))\n print(sample.model_dump_json(), file=f)\n print(dict(sample=i, average_accuracy=sum(scores) / len(scores)))\n return sum(scores) / len(scores)\n\ndef evaluate_batched(\n data_name: str,\n demo_name: str,\n output_dir: str = \"outputs_batched\",\n batch_size: int = 32,\n **kwargs,\n):\n os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n path_out = Path(\n output_dir, make_output_name(eval_data=data_name, demo=demo_name, **kwargs)\n ).with_suffix(\".jsonl\")\n model = VLLMModel(**kwargs)\n data = select_data(data_name, data_split=\"test\")\n demo = select_demonstration(demo_name)\n model.stopping_words = demo.get_stopping_words()\n scores = []\n progress = tqdm(range(0, len(data.samples), batch_size), desc=str(path_out))\n path_out.parent.mkdir(parents=True, exist_ok=True)\n with open(path_out, \"w\") as f:\n for i in progress:\n batch = data.samples[i : i + batch_size]\n for sample in batch:\n sample.prompt = demo.make_prompt(sample.question)\n outputs = model.run_batch([s.prompt for s in batch])\n for j, sample in enumerate(batch):\n sample.raw_outputs.append(outputs[j])\n for o in sample.raw_outputs:\n sample.preds.append(demo.extract_answer(o))\n sample.accept_answer = demo.extract_answer(sample.accept_answer)\n scores.append(sample.preds[0] == sample.accept_answer)\n progress.set_postfix(accuracy=sum(scores) / len(scores))\n print(sample.model_dump_json(indent=2))\n print(sample.model_dump_json(), file=f)\n print(dict(sample=i, average_accuracy=sum(scores) / len(scores)))\n return sum(scores) / len(scores)\n\ndef get_most_common(values: list):\n return Counter(values).most_common()[0][0]\n\ndef gen_reason(samples, demo, model, num_sample=10):\n scores = []\n progress = tqdm(samples)\n for i, sample in enumerate(progress):\n sample.prompt = demo.make_prompt(sample.question)\n sample.raw_outputs = model.run_many(sample.prompt, num_sample)\n for o in sample.raw_outputs:\n sample.preds.append(demo.extract_answer(o))\n sample.accept_answer = demo.extract_answer(sample.accept_answer)\n scores.append(get_most_common(sample.preds) == sample.accept_answer)\n progress.set_postfix(accuracy=sum(scores) / len(scores))\n average_accuracy = sum(scores) / len(scores)\n return average_accuracy\n\ndef evaluate_sc(\n data_name: str,\n demo_name: str,\n path_model: str,\n data_split: str = \"test\",\n output_dir: str = \"outputs_sc\",\n num_sample: int = 10,\n **kwargs,\n):\n os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n path_out = Path(\n output_dir,\n make_output_name(\n eval_data=data_name,\n demo=demo_name,\n split=data_split,\n num_sample=num_sample,\n **kwargs,\n ),\n ).with_suffix(\".jsonl\")\n model = VLLMModel(path_model=path_model)\n data = select_data(data_name, data_split=data_split)\n if args.TestCode:\n data.samples = data.samples[:10]\n demo = select_demonstration(demo_name)\n model.stopping_words = demo.get_stopping_words()\n average_accuracy = gen_reason(data.samples, demo, model, num_sample)\n return average_accuracy\n\ndef run_eval_many(*paths: str, **kwargs):\n records = []\n for p in tqdm(paths):\n try:\n score = evaluate_batched(path_model=p, **kwargs)\n except Exception as e:\n print(e)\n score = -1\n records.append(dict(path=p, score=score))\n for rec in records:\n print(rec)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Script for running a model with specific dataset and configurations.\")\n parser.add_argument(\"--data_name\", type=str, required=True,\n help=\"The name of the dataset to use.\")\n parser.add_argument(\"--demo_name\", type=str, required=True,\n help=\"The name of the demo dataset or example data (usually the same as data_name).\")\n parser.add_argument(\"--path_model\", type=str, required=True,\n help=\"The path to the base model or pre-trained model.\")\n parser.add_argument(\"--data_split\", type=str, choices=[\"train\", \"test\", \"validation\"], default=\"train\",\n help=\"The data split to use (default: 'train').\")\n parser.add_argument(\"--TestCode\", action='store_true')\n args = parser.parse_args()\n evaluate_sc(args.data_name, args.demo_name, args.path_model, data_split=args.data_split)" }, { "task_id": 1, "indent": 1, "script": "\npython branching.py --data_name gsm8k --demo_name gsm8k --path_model models/Meta-Llama-3-8B --path_out Llama --data_split train \n", "latex_code": "\n\\subsection{Reasoning Exploration}\n\\label{sec:RE}\nTo consider potential mistakes that can occur from each reasoning step, the exploration stage of our framework explores multiple branches at each step.\nConcretely, given the problem \\( Q \\), chain-of-thought demonstration, and previous steps of the generated reasoning path \\( P_{1:i-1} = (S_1, S_2, \\ldots, S_{i-1}) \\), we use temperature sampling \\cite{fan-etal-2018-hierarchical} to obtain diverse branches from the current point in the reasoning path:\n\n\\begin{align}\n B_i \\sim M(D_{CoT}, Q, P_{1:i-1} | T),\n\\end{align}\nwhere each branch $B_i = (S'_{i}, S'_{i+1}, \\ldots, S'_l)$ should contain the current step up to the final step. \nWe aim to obtain a favorable branch $B_i^+$ and an unfavorable branch $B_i^-$ \nwhere the favorable branch leads to the correct final answer, and the unfavorable branch does not: \n\\begin{align}\n\\mathcal{F}(B_i^+) = 1, \\quad\n\\mathcal{F}(B_i^-) = 0\n\\end{align}\nTo achieve this, we iteratively sample multiple branches starting at each step $S'_i$ and verify each one using the function \\(\\mathcal{F}\\), until we obtain one favorable branch and one unfavorable branch, thus forming a reasoning branch pair $(B_i^+, B_i^-)$.\n", "completion_path": "./branching.py", "namespace": "branching.branching", "type": "function", "signature_position": [ 92, 92 ], "body_position": [ 93, 110 ], "ReferenceCode_With_Comments": "\npredict = list()\n\nfrom tqdm import tqdm\nfor i, sample in enumerate(tqdm(samples)):\n\n # -----------------------------------------------------------------------\n # Snippet 1: We obtain the chain-of-thought steps by splitting the accepted\n # explanation from the sample. The code excludes the last element ('[:-1]'),\n # mirroring the iterative exploration of partial steps in the reasoning path.\n # -----------------------------------------------------------------------\n # [Begin Snippet 1]\n steps = splitter.run(sample.accept_explanation)[:-1]\n prefixes = [\"\"] + [\"\\n\".join(steps[:j]) for j in range(1, len(steps) + 1)]\n # [End Snippet 1]\n\n predict_tmp = list()\n for prefix in prefixes:\n # -----------------------------------------------------------------------\n # Snippet 2: For each prefix, we adjust the 'answer_prefix' in the sample,\n # then construct the full prompt using 'demo.make_prompt'. This reflects\n # the chain-of-thought demonstration input to the model (D_{CoT} in the LaTeX).\n # -----------------------------------------------------------------------\n # [Begin Snippet 2]\n if prefix:\n sample.answer_prefix = \" \" + prefix + \"\\n\"\n else:\n assert sample.answer_prefix == \"\"\n # [End Snippet 2]\n\n # -------------------------------------------------------------------\n # Snippet 3: Here, we invoke the model to generate multiple branches\n # (raw outputs) for the current prefix. This aligns with Eq. (1) from\n # the LaTeX snippet, where B_i is sampled from the model distribution\n # M(D_{CoT}, Q, P_{1:i-1}|T). The final extraction step accumulates\n # the resulting answers in 'predict_tmp'.\n # -------------------------------------------------------------------\n # [Begin Snippet 3]\n sample.prompt = demo.make_prompt(sample.question) + sample.answer_prefix\n sample.raw_outputs = model.run_many(sample.prompt, num_sample)\n sample.preds = []\n for o in sample.raw_outputs:\n predict_tmp.append(demo.extract_answer(o))\n # [End Snippet 3]\n\n predict.append(predict_tmp)\n\nreturn predict\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Detail:\n - The process of trimming the last reasoning step during step extraction is not described in the LaTeX. The workflow should explicitly exclude the final step when splitting the chain-of-thought explanation to align with iterative partial exploration.\n - The LaTeX omits how the final answer is extracted from the raw output generated by the language model for each branch. The code uses a specific function to extract the relevant answer from model's raw output, implying post-processing or filtering might be involved.\n\n - Mismatched Detail:\n - None\n", "Missing_details": [ "\n- The process of trimming the last reasoning step during step extraction is not described in the LaTeX. The workflow should explicitly exclude the final step when splitting the chain-of-thought explanation to align with iterative partial exploration.\n", "\n- The LaTeX omits how the final answer is extracted from the raw output generated by the language model for each branch. The code uses a specific function to extract the relevant answer from model's raw output, implying post-processing or filtering might be involved.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - input_ids (torch.Tensor, shape=(batch_size, max_length)): \n Token IDs representing the text inputs to be processed by the model.\n - model (an object of the vllm.entrypoints.llm.LLM class): \n A vllm.entrypoints.llm.LLM instance providing a generate method and containing the layers in which we capture neuron activations.\n - num_layers (int): \n The number of layers in the model whose neuron activations are tracked.\n - intermediate_size (int): \n The dimensionality of the neuron's intermediate output in each layer.\n", "Arguments_list": [ { "name": "input_ids", "string": "\n- input_ids (torch.Tensor, shape=(batch_size, max_length)):\n Token IDs representing the text inputs to be processed by the model.\n", "dependency": "torch.Tensor" }, { "name": "model", "string": "\n- model (an object of the vllm.entrypoints.llm.LLM class):\n A vllm.entrypoints.llm.LLM instance providing a generate method and containing the layers in which we capture neuron activations.\n", "dependency": "vllm.entrypoints.llm.LLM" }, { "name": "num_layers", "string": "\n- num_layers (int):\n The number of layers in the model whose neuron activations are tracked.\n", "dependency": null }, { "name": "intermediate_size", "string": "\n- intermediate_size (int):\n The dimensionality of the neuron's intermediate output in each layer.\n", "dependency": null } ] }, "dependency": { "string": "\nRepository Dependencies:\n - Intra-File Dependencies:\n - ReasonStepSplitter\n\n - Cross-File Dependencies:\n - ReasonSample (from data_loading.py)\n - VLLMModel (from inference.py)\n - GSM8KDemonstration (from demonstrations.py)\n", "intra_file": [ "ReasonStepSplitter" ], "cross_file": [ "data_loading.ReasonSample", "inference.VLLMModel", "demonstrations.GSM8KDemonstration" ] }, "external_APIs": { "string": "\nExternal APIs:\n - tqdm.tqdm\n", "list": [ "tqdm" ] }, "Return": { "Return_String": "\nOutput Variables:\n - predict (list[str]):\n A nested list where each element corresponds to one sample\u2019s set of generated\n answers (branches). For a given sample, multiple answers are produced and stored in\n a sub-list, reflecting the different prefixes (partial reasoning steps) applied.\n", "Return_list": [ { "name": "predict", "string": "\n- predict (list[str]):\n A nested list where each element corresponds to one sample\u2019s set of generated\n answers (branches). For a given sample, multiple answers are produced and stored in\n a sub-list, reflecting the different prefixes (partial reasoning steps) applied.\n", "dependency": null } ] }, "ori_python_file": "import json\nimport os\nimport random\nfrom collections import Counter\nfrom pathlib import Path\nfrom typing import List\nfrom zipfile import ZipFile\nimport nltk\nfrom fire import Fire\nfrom pydantic import BaseModel\nfrom tqdm import tqdm\nfrom data_loading import select_data, ReasonData, DataInfo\nfrom demonstrations import select_demonstration\nfrom inference import VLLMModel\nfrom evaluation import make_output_name\nimport argparse\n\nclass ReasonStepSplitter(BaseModel):\n source_path: str = \"punkt.zip\"\n extract_path: str = \"~/nltk_data/tokenizers\"\n \n def load(self):\n folder = Path(self.extract_path).expanduser()\n if not folder.exists():\n folder.mkdir(parents=True, exist_ok=True)\n with ZipFile(self.source_path) as f:\n f.extractall(folder)\n try:\n nltk.sent_tokenize(\"\")\n print(\"NLTK loaded successfully\")\n except LookupError:\n print(\"NLTK not loaded properly, downloading now\")\n nltk.download(\"punkt\")\n \n def run(self, text: str) -> List[str]:\n self.load()\n outputs = []\n for part in text.split(\"\\n\"):\n if part.strip():\n for sent in nltk.sent_tokenize(part.strip()):\n if sent.strip():\n outputs.append(sent.strip())\n return outputs\n\ndef generate_paths(\n data_name: str,\n demo_name: str,\n path_out: str,\n path_model: str,\n data_split: str = \"test\",\n TestCode: bool = False,\n num_sample: int = 10,\n start_index: int = None,\n end_index: int = None,\n existing_preds_path: str = \"\",\n **kwargs,\n):\n os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n model = VLLMModel(path_model=path_model)\n data = select_data(data_name, data_split=data_split)\n if TestCode:\n data.samples = data.samples[:10]\n demo = select_demonstration(demo_name)\n model.stopping_words = demo.get_stopping_words()\n Path(path_out).parent.mkdir(parents=True, exist_ok=True)\n splitter = ReasonStepSplitter()\n print(dict(splitter=type(splitter).__name__))\n random.seed(0)\n if existing_preds_path:\n data = ReasonData.load(existing_preds_path)\n for s in data.samples:\n lst = [o for o, p in zip(s.raw_outputs, s.preds) if p == s.accept_answer]\n s.accept_explanation = \"\" if not lst else lst[0]\n data.samples = [s for s in data.samples if s.accept_explanation]\n print(dict(existing_preds_path=existing_preds_path, data=len(data.samples)))\n else:\n existing_preds_path = Path(\n \"outputs_sc\",\n make_output_name(\n eval_data=data_name,\n demo=demo_name,\n split=data_split,\n num_sample=num_sample,\n **kwargs,\n ),\n ).with_suffix(\".jsonl\")\n if start_index is not None and end_index is not None:\n data.samples = data.samples[start_index:end_index]\n print(dict(start=start_index, end=end_index, samples=len(data.samples)))\n predict = branching(data.samples, splitter, model, demo, num_sample)\n\ndef branching(samples, splitter, model, demo, num_sample):\n predict = list()\n from tqdm import tqdm\n for i, sample in enumerate(tqdm(samples)):\n steps = splitter.run(sample.accept_explanation)[:-1]\n prefixes = [\"\"] + [\"\\n\".join(steps[:j]) for j in range(1, len(steps) + 1)]\n predict_tmp = list()\n for prefix in prefixes:\n if prefix:\n sample.answer_prefix = \" \" + prefix + \"\\n\"\n else:\n assert sample.answer_prefix == \"\"\n sample.prompt = demo.make_prompt(sample.question) + sample.answer_prefix\n sample.raw_outputs = model.run_many(sample.prompt, num_sample)\n sample.preds = []\n for o in sample.raw_outputs:\n predict_tmp.append(demo.extract_answer(o))\n predict.append(predict_tmp)\n return predict\n\ndef merge_path_data(*paths: str, path_out: str):\n samples = []\n for p in paths:\n data = ReasonData.load(p)\n samples.extend(data.samples)\n data = ReasonData(samples=samples)\n data.save(path_out)\n print(dict(path_out=path_out, data=len(data.samples)))\n\ndef save_tuning_data(\n path_in: str,\n path_out: str,\n use_gold_only: bool = False,\n use_single_pair_only: bool = False,\n path_info: str = \"dataset_info.json\",\n):\n outputs = []\n counts = []\n data = ReasonData.load(path_in)\n seen = set()\n for sample in tqdm(data.samples):\n gold = sample.accept_answer\n pool = sample.raw_outputs\n assert len(sample.raw_outputs) == len(sample.preds)\n counts.append(len(sample.raw_outputs))\n accepts = [o for i, o in enumerate(pool) if sample.preds[i] == gold]\n rejects = [o for i, o in enumerate(pool) if sample.preds[i] != gold]\n if use_gold_only:\n if accepts == [] or rejects == [] or sample.question in seen:\n continue\n seen.add(sample.question)\n prefix = \" \" if rejects and rejects[0].startswith(\" \") else \"\"\n a = f\"{prefix}{sample.accept_explanation.strip('.')}. So the answer is \\\\boxed{{{sample.accept_answer}}}.\"\n b = rejects[0]\n raw = dict(\n instruction=sample.question,\n input=\"\",\n output=[a, sample.answer_prefix + b],\n )\n outputs.append(raw)\n continue\n if use_single_pair_only:\n if accepts == [] or rejects == [] or sample.question in seen:\n continue\n seen.add(sample.question)\n raw = dict(\n instruction=sample.question,\n input=\"\",\n output=[\n sample.answer_prefix + accepts[0],\n sample.answer_prefix + rejects[0],\n ],\n )\n outputs.append(raw)\n continue\n for a in sorted(set(accepts)):\n for b in sorted(set(rejects)):\n raw = dict(\n instruction=sample.question,\n input=\"\",\n output=[sample.answer_prefix + a, sample.answer_prefix + b],\n )\n outputs.append(raw)\n Path(path_out).parent.mkdir(exist_ok=True, parents=True)\n with open(path_out, \"w\") as f:\n json.dump(outputs, f, indent=2)\n info = DataInfo.load(path_info)\n info.add_new_data(\n Path(path_out).stem,\n dict(file_name=path_out, ranking=True, formatting=\"alpaca\"),\n )\n if use_gold_only or use_single_pair_only:\n questions = [raw[\"instruction\"] for raw in outputs]\n if len(questions) != len(set(questions)):\n breakpoint()\n raise ValueError\n info.save(path_info)\n print(\"Printing output samples\")\n random.seed(0)\n for raw in random.sample(outputs, k=10):\n print(json.dumps(raw, indent=2))\n print(dict(path_out=path_out, samples=len(outputs), num_outputs=Counter(counts)))\n print(dict(orig_questions=len(set(s.question for s in data.samples))))\n print(dict(filtered_questions=len(set(raw[\"instruction\"] for raw in outputs))))\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Script for running a model with specific dataset and configurations.\")\n parser.add_argument(\"--data_name\", type=str, required=True,\n help=\"The name of the dataset to use.\")\n parser.add_argument(\"--demo_name\", type=str, required=True,\n help=\"The name of the demo dataset or example data (usually the same as data_name).\")\n parser.add_argument(\"--path_out\", type=str, required=True,\n help=\"The path to the base model or pre-trained model.\")\n parser.add_argument(\"--path_model\", type=str, required=True,\n help=\"The path to the base model or pre-trained model.\")\n parser.add_argument(\"--data_split\", type=str, choices=[\"train\", \"test\", \"validation\"], default=\"train\",\n help=\"The data split to use (default: 'train').\")\n parser.add_argument(\"--TestCode\", action='store_true')\n args = parser.parse_args()\n generate_paths(args.data_name, args.demo_name, args.path_out, args.path_model, args.data_split, args.TestCode)" }, { "task_id": 2, "indent": 2, "script": "\npython run_orpo.py --stage orpo --do_train --output_dir outputs_paths/gsm8k --model_name_or_path models/Meta-Llama-3-8B --dataset Llama --template default --finetuning_type lora --lora_target q_proj,v_proj --overwrite_cache --overwrite_output_dir --cutoff_len 1024 --preprocessing_num_workers 16 --per_device_train_batch_size 1 --gradient_accumulation_steps 8 --lr_scheduler_type cosine --warmup_steps 100 --logging_steps 10 --learning_rate 5e-5 --num_train_epochs 3.0 --orpo_beta 0.1 --fp16 \n", "latex_code": "\nIn this work, we mainly focus on the objective proposed by \\citet{hong2024orpo} due to its simplicity and empirical effectiveness.\nConcretely, the branch pair loss $\\mathcal{L}_{bp, i}$ at the $i$-th step can be computed as the log odd-ratio between the favorable branch $B_i^+$ and unfavorable branch $B_i^-$, conditioned on the input question $Q$ and reference path $P$:\n\\begin{align}\n \\mathcal{L}_{bp, i} = \\log \\frac{\\textbf{odds}_M(B_{i}^+ \\mid Q, P)}{\\textbf{odds}_M(B_{i}^- \\mid Q, P)}\n \\label{eq:branch_pair}\n\\end{align}\nThe odds\nof generating a branch can be computed as the ratio between the probability of generating the branch and the probability of not generating it, conditioned on the input question $Q$ and the previous steps $P_{1:i-1}$ of the reference path: \n\n\\begin{align}\n\\textbf{odds}_M(B_i \\mid Q, P) = \\frac{Pr_M(B_i \\mid Q, P_{1:i-1})}{1 - Pr_M(B_i \\mid Q, P_{1:i-1})}\n\\end{align} \n", "completion_path": "./run_orpo.py", "namespace": "run_orpo.CustomORPOTrainer.odds_ratio_loss", "type": "method", "signature_position": [ 82, 84 ], "body_position": [ 85, 90 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Calculates the difference in log probabilities between the chosen\n# and rejected branches, as described in the LaTeX for odds computation.\n# It also subtracts the difference of their complementary log probabilities\n# to form the complete log-odds measure.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nlog_odds = (chosen_logps - rejected_logps) - (\n torch.log1p(-torch.exp(chosen_logps))\n - torch.log1p(-torch.exp(rejected_logps))\n)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Applies the negative log-sigmoid function on the computed log-odds,\n# corresponding to the -log \u03c3(...) operation that the LaTeX states is\n# used to optimize the model toward favoring the chosen branch.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nodds_ratio_loss = -F.logsigmoid(log_odds)\n# [End Snippet 2]\n\nreturn odds_ratio_loss\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The LaTeX description defines the branch pair loss as the log of the odds ratio between the favorable and unfavorable branches, but it does not specify how this log odds ratio is transformed into a final loss value suitable for optimization. In practice, after computing the log odds ratio, an additional step is needed to convert it into a form that penalizes the model effectively. This involves applying a negative log-sigmoid operation to the log odds ratio, which ensures the result is a positive loss that increases when the favorable branch is not sufficiently preferred over the unfavorable one. The workflow starts with calculating the difference in log odds, then passes this difference through a log-sigmoid function to map it to a probability-like value between 0 and 1, and finally takes the negative logarithm of that value to produce the loss.\n - The LaTeX description provides the formula for the odds as a ratio of probabilities, but it does not address how to handle numerical stability when computing these terms in a computational setting. Specifically, when converting log probabilities into probabilities and then forming the odds, small values can lead to precision issues or underflow in standard arithmetic. A practical implementation requires a numerically stable method, such as using a specialized logarithmic function that directly computes log(1 + x) for small x, avoiding subtraction of near-equal values.\n\n - Mismatched Details:\n - While the LaTeX description specifies the computation of log odds via the ratio of branch generation probabilities and their complements, it does not detail the explicit subtraction of the complementary log probabilities. In the reference implementation, this subtraction is performed to accurately represent the odds of both generating and not generating a branch, ensuring the loss reflects the complete odds ratio.\n", "Missing_details": [ "\n- The LaTeX description defines the branch pair loss as the log of the odds ratio between the favorable and unfavorable branches, but it does not specify how this log odds ratio is transformed into a final loss value suitable for optimization. In practice, after computing the log odds ratio, an additional step is needed to convert it into a form that penalizes the model effectively. This involves applying a negative log-sigmoid operation to the log odds ratio, which ensures the result is a positive loss that increases when the favorable branch is not sufficiently preferred over the unfavorable one. The workflow starts with calculating the difference in log odds, then passes this difference through a log-sigmoid function to map it to a probability-like value between 0 and 1, and finally takes the negative logarithm of that value to produce the loss.\n", "\n- The LaTeX description provides the formula for the odds as a ratio of probabilities, but it does not address how to handle numerical stability when computing these terms in a computational setting. Specifically, when converting log probabilities into probabilities and then forming the odds, small values can lead to precision issues or underflow in standard arithmetic. A practical implementation requires a numerically stable method, such as using a specialized logarithmic function that directly computes log(1 + x) for small x, avoiding subtraction of near-equal values.\n", "\n- While the LaTeX description specifies the computation of log odds via the ratio of branch generation probabilities and their complements, it does not detail the explicit subtraction of the complementary log probabilities. In the reference implementation, this subtraction is performed to accurately represent the odds of both generating and not generating a branch, ensuring the loss reflects the complete odds ratio.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - chosen_logps (torch.Tensor, shape=[batch_size]):\n A tensor representing the log probabilities for a favorable branch. Each entry is derived from the model's outputs when generating a branch considered correct or desired.\n - rejected_logps (torch.Tensor, shape=[batch_size]):\n A tensor representing the log probabilities for an unfavorable branch. Each entry is derived from the model's outputs when generating a branch considered incorrect or less desired.\n", "Arguments_list": [ { "name": "chosen_logps", "string": "\n- chosen_logps (torch.Tensor, shape=[batch_size]):\n A tensor representing the log probabilities for a favorable branch. Each entry is derived from the model's outputs when generating a branch considered correct or desired.\n", "dependency": null }, { "name": "rejected_logps", "string": "\n- rejected_logps (torch.Tensor, shape=[batch_size]):\n A tensor representing the log probabilities for an unfavorable branch. Each entry is derived from the model's outputs when generating a branch considered incorrect or less desired.\n", "dependency": null } ] }, "dependency": { "string": "\nRepository Dependencies:\n - Intra-File Dependencies:\n - None \n\n - Cross-File Dependencies:\n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.log1p\n - torch.exp\n - torch.nn.functional.logsigmoid\n", "list": [ "torch.log1p", "torch.exp", "torch.nn.functional.logsigmoid" ] }, "Return": { "Return_String": "\nOutput Variables:\n - odds_ratio_loss (torch.Tensor, shape [batch_size]):\n A tensor of loss values that can be aggregated or averaged externally. Each entry quantifies how much the model needs to correct itself to favor the chosen branch over the rejected branch, following the log odds-ratio principle.\n", "Return_list": [ { "name": "odds_ratio_loss", "string": "\n- odds_ratio_loss (torch.Tensor, shape [batch_size]):\n A tensor of loss values that can be aggregated or averaged externally. Each entry quantifies how much the model needs to correct itself to favor the chosen branch over the rejected branch, following the log odds-ratio principle.\n", "dependency": null } ] }, "ori_python_file": "import json\nimport math\nimport random\nfrom collections import defaultdict\nfrom dataclasses import dataclass\nfrom typing import List, Optional, Union, Dict, Tuple, Literal, Any\nimport argparse\nimport torch\n\n# noinspection PyPep8Naming\nimport torch.nn.functional as F\nfrom datasets import Dataset\nfrom llmtuner.data import PairwiseDataCollatorWithPadding, get_dataset, split_dataset\nfrom llmtuner.extras.callbacks import LogCallback\nfrom llmtuner.extras.constants import IGNORE_INDEX\nfrom llmtuner.extras.ploting import plot_loss\nfrom llmtuner.hparams import (\n ModelArguments,\n get_train_args,\n FinetuningArguments,\n DataArguments,\n)\nfrom llmtuner.model import load_model, load_tokenizer\nfrom llmtuner.train.utils import create_custom_optimzer, create_custom_scheduler\nfrom transformers import (\n Trainer,\n PreTrainedModel,\n Seq2SeqTrainingArguments,\n TrainerCallback,\n)\nfrom trl import DPOTrainer\nfrom trl.trainer.utils import disable_dropout_in_model\n\n\nclass CustomORPOTrainer(DPOTrainer):\n def __init__(\n self,\n model: Union[PreTrainedModel, torch.nn.Module],\n finetuning_args: FinetuningArguments,\n disable_dropout: bool = True,\n **kwargs,\n ):\n if disable_dropout:\n disable_dropout_in_model(model)\n\n self.finetuning_args = finetuning_args\n self.reference_free = False\n self.use_dpo_data_collator = True # hack to avoid warning\n self.generate_during_eval = False # disable at evaluation\n self.label_pad_token_id = IGNORE_INDEX\n self.padding_value = 0\n self.is_encoder_decoder = model.config.is_encoder_decoder\n self.precompute_ref_log_probs = False\n self._precomputed_train_ref_log_probs = False\n self._precomputed_eval_ref_log_probs = False\n self._peft_has_been_casted_to_bf16 = False\n\n self.beta = finetuning_args.orpo_beta\n self._stored_metrics = defaultdict(lambda: defaultdict(list))\n\n Trainer.__init__(self, model=model, **kwargs)\n print(\"Orpo new CustomORPOTrainer\")\n\n def create_optimizer(self) -> \"torch.optim.Optimizer\":\n if self.optimizer is None:\n # noinspection PyTypeChecker\n self.optimizer = create_custom_optimzer(\n self.model, self.args, self.finetuning_args\n )\n return super().create_optimizer()\n\n def create_scheduler(\n self,\n num_training_steps: int,\n optimizer: Optional[\"torch.optim.Optimizer\"] = None,\n ) -> \"torch.optim.lr_scheduler.LRScheduler\":\n # noinspection PyTypeChecker\n create_custom_scheduler(self.args, num_training_steps, optimizer)\n return super().create_scheduler(num_training_steps, optimizer)\n\n @staticmethod\n def odds_ratio_loss(\n chosen_logps: \"torch.Tensor\", rejected_logps: \"torch.Tensor\"\n ) -> \"torch.Tensor\":\n log_odds = (chosen_logps - rejected_logps) - (\n torch.log1p(-torch.exp(chosen_logps))\n - torch.log1p(-torch.exp(rejected_logps))\n )\n odds_ratio_loss = -F.logsigmoid(log_odds)\n return odds_ratio_loss\n\n\n def concatenated_forward(\n self, model: \"PreTrainedModel\", batch: Dict[str, \"torch.Tensor\"]\n ) -> Tuple[\"torch.Tensor\", \"torch.Tensor\", \"torch.Tensor\", \"torch.Tensor\"]:\n r\"\"\"\n Computes the average log probabilities of the labels under the given logits.\n \"\"\"\n all_logits: \"torch.Tensor\" = model(\n input_ids=batch[\"input_ids\"],\n attention_mask=batch[\"attention_mask\"],\n return_dict=True,\n use_cache=False,\n ).logits.to(torch.float32)\n\n # noinspection PyTypeChecker\n all_logps = self.get_batch_logps(\n logits=all_logits,\n labels=batch[\"labels\"],\n average_log_prob=True,\n is_encoder_decoder=self.is_encoder_decoder,\n label_pad_token_id=self.label_pad_token_id,\n )\n batch_size = batch[\"input_ids\"].size(0) // 2\n chosen_logps, rejected_logps = all_logps.split(batch_size, dim=0)\n chosen_logits, rejected_logits = all_logits.split(batch_size, dim=0)\n return chosen_logps, rejected_logps, chosen_logits, rejected_logits\n\n def decode_sequences(self, x: torch.Tensor) -> List[str]:\n sequences = [[i for i in lst if i >= 0] for lst in x.tolist()]\n return self.tokenizer.batch_decode(sequences)\n\n @staticmethod\n def check_valid(labels) -> bool:\n for i, lst in enumerate(labels.tolist()):\n if len(set(lst)) == 1:\n print(f\"Invalid label row at index {i}\")\n return False\n return True\n\n def get_prefix_removed_logps(self, chosen_logits, rejected_logits, labels):\n batch_size = labels.size(0) // 2\n chosen_labels, rejected_labels = labels.clone().split(batch_size, dim=0)\n assert chosen_labels.shape == rejected_labels.shape\n\n # For a chosen and rejected rationale, we want to ignore the front part that is the same\n # So we create a mask that denotes the longest common prefix\n # Then the labels based on the mask will cause the logp computation to ignore those positions\n matches = torch.eq(chosen_labels, rejected_labels)\n mask = torch.cumprod(matches, dim=1).bool()\n chosen_labels = torch.where(mask, self.label_pad_token_id, chosen_labels)\n rejected_labels = torch.where(mask, self.label_pad_token_id, rejected_labels)\n if not self.check_valid(chosen_labels) or not self.check_valid(rejected_labels):\n breakpoint()\n\n chosen_logps = self.get_batch_logps(\n logits=chosen_logits,\n labels=chosen_labels,\n average_log_prob=True,\n is_encoder_decoder=self.is_encoder_decoder,\n label_pad_token_id=self.label_pad_token_id,\n )\n\n rejected_logps = self.get_batch_logps(\n logits=rejected_logits,\n labels=rejected_labels,\n average_log_prob=True,\n is_encoder_decoder=self.is_encoder_decoder,\n label_pad_token_id=self.label_pad_token_id,\n )\n\n if torch.isnan(chosen_logps).any() or torch.isnan(rejected_logps).any():\n breakpoint()\n return chosen_logps, rejected_logps\n\n def get_batch_loss_metrics(\n self,\n model: \"PreTrainedModel\",\n batch: Dict[str, \"torch.Tensor\"],\n train_eval: Literal[\"train\", \"eval\"] = \"train\",\n ) -> Tuple[\"torch.Tensor\", Dict[str, \"torch.Tensor\"]]:\n r\"\"\"\n Computes the ORPO loss and other metrics for the given batch of inputs for train or test.\n \"\"\"\n metrics = {}\n chosen_logps, rejected_logps, chosen_logits, rejected_logits = (\n self.concatenated_forward(model, batch)\n )\n sft_loss = -chosen_logps\n chosen_logps, rejected_logps = self.get_prefix_removed_logps(\n chosen_logits, rejected_logits, batch[\"labels\"]\n )\n odds_ratio_loss = self.odds_ratio_loss(chosen_logps, rejected_logps)\n batch_loss = (sft_loss + self.beta * odds_ratio_loss).mean()\n\n chosen_rewards = self.beta * chosen_logps.detach()\n rejected_rewards = self.beta * rejected_logps.detach()\n reward_accuracies = (chosen_rewards > rejected_rewards).float()\n\n prefix = \"eval_\" if train_eval == \"eval\" else \"\"\n metrics[\"{}rewards/chosen\".format(prefix)] = chosen_rewards.cpu().mean()\n metrics[\"{}rewards/rejected\".format(prefix)] = rejected_rewards.cpu().mean()\n metrics[\"{}rewards/accuracies\".format(prefix)] = reward_accuracies.cpu().mean()\n metrics[\"{}rewards/margins\".format(prefix)] = (\n (chosen_rewards - rejected_rewards).cpu().mean()\n )\n metrics[\"{}logps/rejected\".format(prefix)] = (\n rejected_logps.detach().cpu().mean()\n )\n metrics[\"{}logps/chosen\".format(prefix)] = chosen_logps.detach().cpu().mean()\n metrics[\"{}logits/rejected\".format(prefix)] = (\n rejected_logits.detach().cpu().mean()\n )\n metrics[\"{}logits/chosen\".format(prefix)] = chosen_logits.detach().cpu().mean()\n metrics[\"{}sft_loss\".format(prefix)] = sft_loss.detach().cpu().mean()\n metrics[\"{}odds_ratio_loss\".format(prefix)] = (\n odds_ratio_loss.detach().cpu().mean()\n )\n\n return batch_loss, metrics\n\n\ndef count_prefix_overlap(lst_a: List[int], lst_b: List[int]) -> int:\n count = 0\n for a, b in zip(lst_a, lst_b):\n if a == b:\n count += 1\n else:\n break\n return count\n\n\n@dataclass\nclass ReasonPathsCollator(PairwiseDataCollatorWithPadding):\n dataset: Dataset = None\n sample_groups: Dict[str, List[dict]] = None\n is_seeded: bool = False\n max_group_size: int = 8\n max_length: int = round(1024 * 0.9)\n\n def load(self):\n if not self.is_seeded:\n random.seed(0)\n self.is_seeded = True\n\n if self.sample_groups is None:\n assert self.dataset is not None\n assert self.tokenizer is not None\n self.sample_groups = {}\n\n for i in range(len(self.dataset)):\n sample = self.dataset[i]\n key = str(sample[\"prompt_ids\"])\n self.sample_groups.setdefault(key, []).append(sample)\n\n print(dict(ReasonPathsCollator_sample_groups=len(self.sample_groups)))\n for key in random.sample(self.sample_groups.keys(), k=4):\n for raw in self.sample_groups[key][:4]:\n info = dict(\n prompt=self.tokenizer.decode(raw[\"prompt_ids\"]),\n chosen=self.tokenizer.decode(raw[\"chosen_ids\"]),\n reject=self.tokenizer.decode(raw[\"rejected_ids\"]),\n prefix_overlap=count_prefix_overlap(\n raw[\"chosen_ids\"], raw[\"rejected_ids\"]\n ),\n )\n print(json.dumps(info, indent=2))\n print(\"#\" * 80)\n group_sizes = [len(lst) for lst in self.sample_groups.values()]\n print(dict(min_group_size=min(group_sizes), max=max(group_sizes)))\n self.test_filter_by_length()\n\n def count_num_training_steps(self, args: Seq2SeqTrainingArguments) -> int:\n self.load()\n num_questions = len(self.sample_groups)\n batch_size = args.train_batch_size * args.gradient_accumulation_steps\n batch_size *= args.world_size\n return math.ceil(num_questions * args.num_train_epochs / batch_size)\n\n def test_filter_by_length(self):\n groups = list(self.sample_groups.values())\n info = dict(\n max_length=self.max_length,\n original=sum(len(lst) for lst in groups),\n filtered=sum(len(self.filter_by_length(lst)) for lst in groups),\n original_qns=len(groups),\n filtered_qns=len([lst for lst in groups if self.filter_by_length(lst)]),\n )\n print(json.dumps(info, indent=2))\n\n def filter_by_length(self, samples: List[dict]) -> List[dict]:\n outputs = []\n for raw in samples:\n chosen = raw[\"prompt_ids\"] + raw[\"chosen_ids\"]\n reject = raw[\"prompt_ids\"] + raw[\"rejected_ids\"]\n if len(chosen) < self.max_length and len(reject) < self.max_length:\n outputs.append(raw)\n return outputs\n\n def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, torch.Tensor]:\n self.load()\n assert features is not None\n del features\n\n while True:\n # Avoid bias from large groups, which will have more raw samples\n key = random.choice(sorted(self.sample_groups.keys()))\n\n group = self.filter_by_length(self.sample_groups[key])\n if not group:\n print(f\"Empty group after filter: {self.tokenizer.decode(eval(key))}\")\n continue\n\n if len(group) > self.max_group_size:\n group = random.sample(group, k=self.max_group_size)\n return super().__call__(group)\n\n\ndef run_train(\n model_args: ModelArguments,\n data_args: DataArguments,\n training_args: Seq2SeqTrainingArguments,\n finetuning_args: FinetuningArguments,\n callbacks: Optional[List[TrainerCallback]] = None,\n TestCode=False,\n):\n print(locals())\n if data_args.dataset.startswith(\"math\"):\n data_args.cutoff_len = 1536 # MATH has longer solutions\n tokenizer = load_tokenizer(model_args)\n dataset = get_dataset(tokenizer, model_args, data_args, training_args, stage=\"rm\")\n model = load_model(tokenizer, model_args, finetuning_args, training_args.do_train)\n\n data_collator = ReasonPathsCollator(\n tokenizer=tokenizer,\n pad_to_multiple_of=8,\n label_pad_token_id=(\n IGNORE_INDEX\n if data_args.ignore_pad_token_for_loss\n else tokenizer.pad_token_id\n ),\n dataset=dataset,\n max_length=round(data_args.cutoff_len * 0.9),\n )\n\n # Update arguments\n training_args.remove_unused_columns = False # important for pairwise dataset\n training_args.max_steps = data_collator.count_num_training_steps(training_args)\n\n # Initialize our Trainer\n trainer = CustomORPOTrainer(\n model=model,\n args=training_args,\n finetuning_args=finetuning_args,\n tokenizer=tokenizer,\n data_collator=data_collator,\n callbacks=callbacks,\n **split_dataset(dataset, data_args, training_args),\n )\n\n # Training\n if training_args.do_train:\n train_result = trainer.train(\n resume_from_checkpoint=training_args.resume_from_checkpoint\n )\n trainer.save_model()\n # noinspection PyArgumentList\n trainer.log_metrics(\"train\", train_result.metrics)\n # noinspection PyArgumentList\n trainer.save_metrics(\"train\", train_result.metrics)\n # noinspection PyArgumentList\n trainer.save_state()\n if trainer.is_world_process_zero() and finetuning_args.plot_loss:\n # noinspection PyTypeChecker\n plot_loss(\n training_args.output_dir,\n keys=[\"loss\", \"eval_loss\", \"rewards/accuracies\", \"sft_loss\"],\n )\n\n\ndef main(\n args: Optional[Dict[str, Any]] = None,\n callbacks: Optional[List[TrainerCallback]] = None,\n):\n print(\"Orpo new main\")\n args1 = args.copy()\n args1.pop('TestCode')\n model_args, data_args, training_args, finetuning_args, generating_args = (\n get_train_args(args1)\n )\n callbacks = [LogCallback()] if callbacks is None else callbacks\n run_train(model_args, data_args, training_args, finetuning_args, callbacks, args['TestCode'])\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Script for training with ORPO and LoRA configurations.\")\n \n # Add arguments\n parser.add_argument(\"--stage\", type=str, required=True, help=\"The training stage, e.g., 'orpo'.\")\n parser.add_argument(\"--do_train\", action=\"store_true\", help=\"Flag to indicate training mode.\")\n parser.add_argument(\"--output_dir\", type=str, required=True, help=\"Directory to save outputs.\")\n parser.add_argument(\"--model_name_or_path\", type=str, required=True, help=\"Path to the base model.\")\n parser.add_argument(\"--dataset\", type=str, required=True, help=\"Name of the dataset.\")\n parser.add_argument(\"--dataset_dir\", type=str, default=\"\", help=\"Directory for the dataset.\")\n parser.add_argument(\"--template\", type=str, default=\"default\", help=\"Template name for data processing.\")\n parser.add_argument(\"--finetuning_type\", type=str, choices=[\"lora\"], default=\"lora\", help=\"Type of finetuning (default: lora).\")\n parser.add_argument(\"--lora_target\", type=str, default=\"q_proj,v_proj\", help=\"Comma-separated list of LoRA target layers.\")\n parser.add_argument(\"--overwrite_cache\", action=\"store_true\", help=\"Overwrite the cache if set.\")\n parser.add_argument(\"--overwrite_output_dir\", action=\"store_true\", help=\"Overwrite the output directory if set.\")\n parser.add_argument(\"--cutoff_len\", type=int, default=1024, help=\"Maximum sequence length.\")\n parser.add_argument(\"--preprocessing_num_workers\", type=int, default=16, help=\"Number of workers for preprocessing.\")\n parser.add_argument(\"--per_device_train_batch_size\", type=int, default=1, help=\"Batch size per device for training.\")\n parser.add_argument(\"--gradient_accumulation_steps\", type=int, default=8, help=\"Number of gradient accumulation steps.\")\n parser.add_argument(\"--lr_scheduler_type\", type=str, choices=[\"cosine\"], default=\"cosine\", help=\"Learning rate scheduler type.\")\n parser.add_argument(\"--warmup_steps\", type=int, default=100, help=\"Number of warmup steps for learning rate scheduler.\")\n parser.add_argument(\"--logging_steps\", type=int, default=10, help=\"Number of steps for logging metrics.\")\n parser.add_argument(\"--learning_rate\", type=float, default=5e-5, help=\"Learning rate.\")\n parser.add_argument(\"--num_train_epochs\", type=float, default=3.0, help=\"Number of training epochs.\")\n parser.add_argument(\"--orpo_beta\", type=float, default=0.1, help=\"Beta value for ORPO.\")\n parser.add_argument(\"--fp16\", action=\"store_true\", help=\"Use mixed precision (fp16) if set.\")\n parser.add_argument('--TestCode', action='store_true')\n args = parser.parse_args()\n args = vars(args)\n main(args)\n" } ] }, { "paper_id": 26, "paper_details": { "title": "Lifelong Knowledge Editing for LLMs with Retrieval-Augmented Continuous Prompt Learning", "url": "https://arxiv.org/abs/2405.03279" }, "repo_original_url": "https://github.com/qizhou000/RECIPE", "project_path": "Benchmark/26-recipe/RECIPE-main", "enviorment_name": "recipe", "file_organization": "\nRECIPE-main/\n README.md\n LICENSE\n requirement.txt\n test_recipe.py\n train_recipe.py\n configs/\n readme.md\n recipe/\n gpt2-xl.yaml\n gpt-j-6b.yaml\n llama-7b.yaml\n data/\n evaluation/\n cf/\n counterfact-edit.json\n ripple_effect/\n ripe_test.json\n zsre/\n zsre_mend_eval.json\n meta-train/\n cf/\n counterfact-train.json\n ripple_effect/\n ripe_train.json\n zsre/\n zsre_mend_train.json\n editors/\n editor.py\n __init__.py\n recipe/\n data.py\n __init__.py\n models.py\n recipe.py\n utils/\n generate.py\n __init__.py\n evaluation/\n editor_eval.py\n __init__.py\n llm_general_eval.py\n figures/\n recipe.svg\n models/\n gpt2-xl/\n config.json\n gpt-j-6b/\n config.json\n llama-2-7b-hf/\n config.json\n roberta-base/\n config.json\n readme.md\n utils/\n data.py\n global_attrs.py\n __init__.py\n utils.py\n", "latex_code_path": "Benchmark/26-recipe/arXiv-2405.03279v3", "task_details": [ { "task_id": 0, "indent": 2, "script": "\npython test_recipe.py -en 'recipe' -mn 'llama-7b' -et 'sequential' -dn 'zsre' -edn 1000 \n", "completion_path": "./editors/recipe/recipe.py", "latex_code": "\n\\subsection{Construction and Update of Knowledge Retrieval Repository}\n\\label{subsection:Updating_KRR}\nThe knowledge retrieval repository is initialized as empty, i.e., $\\mathcal{K}_0=\\{\\}$, and is updated from $\\mathcal{K}_{t-1}$ to $\\mathcal{K}_t$ by adding a new key-value pair corresponding to new editing knowledge, $k_t$, at each timestep $t$ in our lifelong editing setting. \n\nSpecifically, at timestep $t$, given a new knowledge statement $k_t$, the knowledge representation $r_{k_t}\\in \\mathcal{R}^{d_r}$ is achieved through an encoder $f_{rm}$ (e.g.,~RoBERTa \\cite{roberta}) stacked with a multilayer perceptron (MLP) $\\mathbf{MLP}_K$: \n\\begin{equation}\n r_{k_t} = \\mathbf{MLP}_K(f_{rm}(k_t))\n \\label{equation:knowledge_representation}\n\\end{equation}\nwhere $f_{rm}$ concatenates the maximum, minimum, and average pooling of its output token representations (including the $\\mathrm{[CLS]}$ token) into a vector to maximally retain the semantic information of the input. Then, the continuous prompt $p_{k_t}\\in \\mathbb{R}^{l\\times d_{llm}}$ is generated through another MLP, i.e.,~$\\mathbf{MLP}_P$:\n\\begin{equation}\n p_{k_t} = f_{resp}\\left(\\mathbf{MLP}_P\\left(r_{k_t}\\right)\\right) \n \\label{equation:prompt_embedding}\n\\end{equation}\nwhere $l$ and $d_{llm}$ are the length of the continuous prompt and the dimension of the LLM's word embedding, respectively. \nIn other words, $l$ is the number of Continuous Prompt Tokens (CPTs) leveraged for LLM inference.\n$f_{resp}$ is the reshape operation that maps the vector into a matrix with shape $l\\times d_{llm}$.\nFinally, the knowledge retrieval repository is updated from $\\mathcal{K}_{t-1}$ to $\\mathcal{K}_{t}$:\n$\\mathcal{K}_t = \\mathcal{K}_{t-1} \\cup \\{(r_{k_t}, p_{k_t})\\}$\nwhere $(r_{k_t}, p_{k_t})$ is the key-value pair for knowledge retrieval.\n", "namespace": "editors.recipe.recipe.RECIPE.edit_batch", "type": "method", "signature_position": [ 184, 184 ], "body_position": [ 185, 199 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Constructs knowledge statements from request data by combining 'prompt' and 'target_new'.\n# Prepares \\( k_t \\) for each request as a new knowledge statement.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nrs = []\nfor r in requests:\n rs.append(r['prompt'] + r['target_new'])\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Extends the natural language knowledge base with new statements.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nself.knowledge_base_nl.extend(rs)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Generates knowledge representations using the encoder and MLP.\n# Implements \\( r_{k_t} = \\mathbf{MLP}_K(f_{rm}(k_t)) \\) from Eq. \\ref{equation:knowledge_representation},\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nnew_reps = self.knowl_rep_model(rs, knowl_or_query = 'k')\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Generates continuous prompts from the knowledge representations.\n# Corresponds to \\( p_{k_t} = f_{resp}(\\mathbf{MLP}_P(r_{k_t})) \\) from Eq. \\ref{equation:prompt_embedding}.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nnew_prompts = self.prompt_transformer(new_reps)\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Updates the knowledge retrieval repository with new representations and prompts.\n# Reflecting \\( \\mathcal{K}_t = \\mathcal{K}_{t-1} \\cup \\{(r_{k_t}, p_{k_t})\\} \\).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nself.knowledge_base = torch.cat([self.knowledge_base, new_reps], 0)\nself.prompts_base = torch.cat([self.prompts_base, new_prompts], 0)\n# [End Snippet 5]\n\n# ---------------------------------------------------------------------------\n# Snippet 6: Returns the updated repository components.\n# Provides access to the updated state, a utility not specified in LaTeX, likely for inspection or downstream use.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 6]\nreturn self.knowledge_base_nl, self.knowledge_base, self.prompts_base\n# [End Snippet 6]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The LaTeX description does not specify the preprocessing step of constructing a complete knowledge statement from separate textual inputs (e.g., a query and an update). In the reference code, these two pieces of text are concatenated to form the knowledge statement before any encoding takes place.\n - There is no mention in the LaTeX code of maintaining a separate repository of the original natural language knowledge statements. The reference code keeps an updated list of these statements for inspection or further use.\n - LaTeX describes updating the repository with a single \\( k_t \\) per timestep, but the Python code handles a batch of requests simultaneously.\n\n - Mismatched Details:\n - None\n", "Missing_details": [ "\n- The LaTeX description does not specify the preprocessing step of constructing a complete knowledge statement from separate textual inputs (e.g., a query and an update). In the reference code, these two pieces of text are concatenated to form the knowledge statement before any encoding takes place.\n", "\n- There is no mention in the LaTeX code of maintaining a separate repository of the original natural language knowledge statements. The reference code keeps an updated list of these statements for inspection or further use.\n", "\n- LaTeX describes updating the repository with a single \\( k_t \\) per timestep, but the Python code handles a batch of requests simultaneously.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - self (RECIPE): Instance of the RECIPE class, containing the knowledge repository and transformation models.\n - requests (List[Dict]): List of dictionaries, each containing:\n - 'prompt' (str): The input query or context for editing.\n - 'subject' (str): The entity being edited (unused in this implementation).\n - 'target_new' (str): The new target information to incorporate into the knowledge base.\n", "Arguments_list": [ { "name": "self", "string": "\n- self (RECIPE): Instance of the RECIPE class, containing the knowledge repository and transformation models.\n", "dependency": null }, { "name": "requests", "string": "\n- requests (List[Dict]): List of dictionaries, each containing:\n - 'prompt' (str): The input query or context for editing.\n - 'subject' (str): The entity being edited (unused in this implementation).\n - 'target_new' (str): The new target information to incorporate into the knowledge base.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-File Dependencies:\n - RECIPE.knowl_rep_model\n - RECIPE.prompt_transformer\n\n - Cross-File Dependencies:\n - None\n", "intra_file": [ "RECIPE.knowl_rep_model", "RECIPE.prompt_transformer" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.cat\n", "list": [ "torch.cat" ] }, "Return": { "Return_String": "\nOutput Variables:\n - self.knowledge_base_nl (List[str]): Updated list of natural language knowledge statements.\n - self.knowledge_base (torch.Tensor): Updated tensor of knowledge representations.\n - self.prompts_base (torch.Tensor): Updated tensor of continuous prompts.\n", "Return_list": [ { "name": "self.knowledge_base_nl", "string": "\n- self.knowledge_base_nl (List[str]): Updated list of natural language knowledge statements.\n", "dependency": null }, { "name": "self.knowledge_base", "string": "\n- self.knowledge_base (torch.Tensor): Updated tensor of knowledge representations.\n", "dependency": null }, { "name": "self.prompts_base", "string": "\n- self.prompts_base (torch.Tensor): Updated tensor of continuous prompts.\n", "dependency": null } ] }, "ori_python_file": "from editors.editor import BaseEditor, EditorConfig\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nfrom typing import Dict, List, Tuple \nfrom dataclasses import dataclass, asdict\nimport numpy as np\nfrom copy import deepcopy\nimport torch, os, yaml\nfrom torch.utils.tensorboard import SummaryWriter \nfrom torch.optim import Adam\nfrom .models import KnowledgeRepModel, PromptTransformer\nfrom utils.data import ParallelDataset\nfrom datetime import datetime\nfrom tqdm import tqdm\nimport random\nos.environ['PYTHONHASHSEED'] = str(42)\nos.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\nnp.random.seed(42)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\ntorch.use_deterministic_algorithms(True)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nrandom.seed(42)\ntorch.cuda.synchronize()\n\n@dataclass\nclass RECIPEConfig(EditorConfig):\n @dataclass\n class TrainingConfig():\n krm_lr: float\n pt_lr: float\n relia_lambda: float\n gen_lambda: float\n loc_lambda: float\n contra_lambda: float\n query_knowledge_t: float\n query_prototype_t: float\n constra_hinge_scale: float # w/hinge >= 1, w/o hinge== 999999 \n edit_hinge_scale: float # w/hinge >= 1, w/o hinge== 999999 \n # set in train_init\n batch_size:int = None\n sample_count:int = None\n random_seed:int = None\n eps:float = 1e-8\n \n prompt_token_n: int\n edit_model_name: str\n knowledge_rep_dim: int\n knowl_rep_prot_token_n: int\n model_hidden_size: int\n begin_layer_path:str\n lm_head_path:str\n training: TrainingConfig\n\n @classmethod\n def from_yaml(self, fpath):\n with open(fpath, \"r\") as f:\n data = yaml.safe_load(f)\n data['training'] = self.TrainingConfig(**data['training'])\n return self(**data)\n @classmethod\n def from_json(self, fpath):\n raise\n \nclass RECIPE(BaseEditor):\n def __init__(self, \n model: AutoModelForCausalLM,\n tokenizer: AutoTokenizer,\n config: RECIPEConfig,\n device = 'cuda',\n krm_base_path = 'models/roberta-base',\n retr_top_k = 1,\n retr_min_sim = -999,\n auto_retrieve = True, \n ckpt_path = None \n ):\n super().__init__(model, tokenizer, device)\n self.cfg = config\n # initialize model & parameters\n self.knowl_rep_model = KnowledgeRepModel(config.knowledge_rep_dim, \n config.knowl_rep_prot_token_n, self.device, krm_base_path)\n self.prompt_transformer = PromptTransformer(config.knowledge_rep_dim, \n config.model_hidden_size, config.prompt_token_n, self.device)\n # initialize hooks\n self.begin_layer = find_module(self.model, self.cfg.begin_layer_path)\n self.lm_head = find_module(self.model, self.cfg.lm_head_path)\n self.model.forward = self.register_model_forward_hook(self.model, \n self.model.forward, self.begin_layer, self.lm_head)\n self.begin_layer_hook = self.register_editing_hook(self.begin_layer, self.lm_head)\n # initialize editing prompts\n self.restore_to_original_model()\n self.auto_retrieve = auto_retrieve \n self.retr_top_k = retr_top_k\n self.retr_min_sim = retr_min_sim\n self.set_train(False) \n if ckpt_path != None:\n self.load_ckpt(ckpt_path, load_opt = False)\n \n ############################################################################\n ############################# Initialize ###################################\n ############################################################################\n def register_editing_hook(self, begin_layer, lm_head_layer):\n def forward_pre_hook(module, args):\n # If do not has past_key_values, add editing prompts before reps.\n if not module.has_past_kv:\n args = args[0]\n args = torch.stack([\n torch.cat([p, inp[:-len(p) if len(p) != 0 else None]], 0)\n for inp, p in zip(args, self.adopted_prompts)], 0)\n return (args, )\n def forward_hook(module, args, output):\n if not module.has_past_kv:\n max_n = max([len(p) for p in self.adopted_prompts])\n output = torch.stack([\n ot[len(p):len(p)-max_n if len(p)-max_n != 0 else None]\n for ot, p in zip(output, self.adopted_prompts)], 0)\n return output\n begin_layer_hook = begin_layer.register_forward_pre_hook(forward_pre_hook)\n lm_head_layer_hook = lm_head_layer.register_forward_hook(forward_hook)\n return [begin_layer_hook, lm_head_layer_hook]\n\n def register_model_forward_hook(self, model, model_forward, begin_layer, lm_head):\n if hasattr(model, 'recipe_hooked'):\n return model_forward\n model.recipe_hooked = True\n def forward_recipe(**kargs):\n if 'past_key_values' in kargs and kargs['past_key_values'] != None:\n begin_layer.has_past_kv = True\n lm_head.has_past_kv = True\n else:\n begin_layer.has_past_kv = False\n lm_head.has_past_kv = False\n b, l = kargs['input_ids'].shape\n inp_sents = [self.tokenizer.decode(i, skip_special_tokens=True) \n for i in kargs['input_ids']]\n if self.auto_retrieve: \n retrieved_ids = self.retrieve_and_get_ids_sim(inp_sents)[0]\n # print(retrieved_ids)\n self.adopted_prompts = [self.prompts_base[i].reshape(\n len(i)*self.cfg.prompt_token_n, self.cfg.model_hidden_size) \n for i in retrieved_ids]\n if len(self.adopted_prompts) != b:\n print(len(self.adopted_prompts), b) \n raise ValueError\n pad = torch.ones([b, max([len(i) for i in self.adopted_prompts])], \n dtype = torch.long).to(self.device)\n if 'attention_mask' in kargs and kargs['attention_mask'] != None:\n kargs['attention_mask'] = torch.cat([kargs['attention_mask'], pad], 1)\n kargs['input_ids'] = torch.cat([kargs['input_ids'], pad * self.tokenizer.pad_token_id], 1)\n return model_forward(**kargs)\n return forward_recipe\n\n ############################################################################\n ############################# RECIPE Edit Related ############################\n ############################################################################\n def retrieve_and_get_ids_sim(self, input_queries:List[str]):\n query_reps = self.knowl_rep_model(input_queries, knowl_or_query = 'q') # [n, knowledge_rep_dim] \n sim_matrx = (query_reps @ self.knowledge_base.T) / self.cfg.knowledge_rep_dim**0.5 # cross_cos_sim(query_reps, self.knowledge_base) # [n, edit_n]\n sim_with_prototype = sim_matrx[:, :1] \n sorted_sim, order = torch.sort(sim_matrx, 1, True) # [n, edit_n]\n mask = sorted_sim[:, :self.retr_top_k] > self.retr_min_sim\n mask &= sorted_sim[:, :self.retr_top_k] > sim_with_prototype\n retrieved_ids = torch.masked_select(order[:, :self.retr_top_k], mask)\n retrieved_ids = torch.split(retrieved_ids, mask.sum(1).tolist()) # retrieved indexes\n return retrieved_ids, sorted_sim, order # [retr_ids_1, retr_ids_2, ..., retr_ids_n]\n\n ############################################################################\n ############################# Editor Basic Functions #######################\n ############################################################################\n def name_of_editor_and_model(self)->Tuple[str, str]:\n return 'recipe', self.cfg.edit_model_name\n\n def if_can_batch_edit(self):\n return True\n \n def restore_to_original_model(self):\n self.knowledge_base_nl = [''] # [edit_n, knowledge_rep_dim]\n self.knowledge_base = self.knowl_rep_model.get_knowl_rep_prot() # [edit_n, knowledge_rep_dim]\n self.prompts_base = torch.zeros([1, self.cfg.prompt_token_n, self.cfg.model_hidden_size], \n device = self.device) # [edit_n, prompt_token_n, model_hidden_size]\n self.adopted_prompts = [] # List[torch.Tensor], len(List) = btach_size, Tensor.size = [retr_n * prompt_token_n, model_hidden_size]\n\n def edit_batch(self, requests: List[Dict]):\n '''requests = [\n {'prompt':str, 'subject':str, 'target_new':str}\n {'prompt':str, 'subject':str, 'target_new':str}, ...\n ]\n '''\n rs = []\n for r in requests:\n rs.append(r['prompt'] + r['target_new'])\n self.knowledge_base_nl.extend(rs)\n new_reps = self.knowl_rep_model(rs, knowl_or_query = 'k')\n new_prompts = self.prompt_transformer(new_reps)\n self.knowledge_base = torch.cat([self.knowledge_base, new_reps], 0)\n self.prompts_base = torch.cat([self.prompts_base, new_prompts], 0)\n\n return self.knowledge_base_nl, self.knowledge_base, self.prompts_base\n\n def edit_one_piece(self, request: Dict) -> None:\n \"\"\"\n request = {'prompt':str, 'subject':str, 'target_new':str}\n \"\"\"\n requests = [request]\n for r in range(len(requests)):\n requests[r]['prompt'] = requests[r]['prompt'].strip() + \" \"\n requests[r]['target_new'] = requests[r]['target_new'].strip()\n knowledge_base_nl, knowledge_base, prompts_base= self.edit_batch([request])\n\n ############################################################################\n ############################# RECIPE Training ################################\n ############################################################################\n def set_train(self, if_train = False):\n self.model.train(False)\n self.model.requires_grad_(False)\n self.knowl_rep_model.train(if_train)\n self.knowl_rep_model.requires_grad_(if_train)\n self.prompt_transformer.train(if_train)\n self.prompt_transformer.requires_grad_(if_train)\n self.auto_retrieve = not if_train\n\n def train_init(self, sample_count, get_data_by_ids, batch_size, \n records_dir:str = 'train_records', train_name_prefix = None, \n train_name:str = None, load_ckpt_path:str = None, \n save_ckpt_per_i = 3000, log_per_i = 10, random_seed = None): \n '''\n Used to initialize `ParallelDataset`:\n sample_count: count of used data in dataset.\n get_data_by_ids: function getting data by ids, assume data structure: (\n batch_knowledge: List[str], len = batch_size\n contra_q: List[str], len = batch_size * 3\n contra_sim_m: torch.Tensor[batch_size, batch_size * 3]\n batch_relia_xym: (input_ids, label_ids, masks), \n batch_gen_xym: {\n loss_name_1: (input_ids, label_ids, masks),\n loss_name_2: (input_ids, label_ids, masks), ...\n },\n batch_loc_xym: {\n loss_name_1: (input_ids, masks)\n loss_name_2: (input_ids, masks), ...\n } \n ), where `input_ids`, `label_ids`, and `label_ids` are with shape \n [batch_size, length]\n '''\n # initialize data generator\n self.rng = np.random.default_rng(random_seed)\n self.data_generator = ParallelDataset(sample_count, get_data_by_ids, \n batch_size, True, 16, False, random_seed)\n # initialize checkpoint/log directory and writer\n t = datetime.now().strftime('%Y.%m.%d-%H.%M.%S')\n train_name = (train_name_prefix + '-' if train_name_prefix else \"\") + \\\n (train_name if train_name else t)\n records_dir = os.path.join(records_dir, *self.name_of_editor_and_model(), train_name)\n self.save_ckpt_dir = os.path.join(records_dir, 'checkpoints')\n if not os.path.exists(self.save_ckpt_dir):\n os.makedirs(self.save_ckpt_dir)\n logs_path = os.path.join(records_dir, 'logs')\n if not os.path.exists(logs_path):\n os.makedirs(logs_path)\n with open(os.path.join(records_dir, 'config.yaml'), 'w') as f:\n self.cfg.training.batch_size = batch_size\n self.cfg.training.sample_count = sample_count\n self.cfg.training.random_seed = random_seed\n yaml.dump(asdict(self.cfg), f)\n self.log_writer = SummaryWriter(logs_path)\n self.save_ckpt_per_i = save_ckpt_per_i\n self.log_per_i = log_per_i\n # initialize optimizer and load checkpoints\n self.opt = Adam([\n {'params': self.knowl_rep_model.parameters(), 'lr': self.cfg.training.krm_lr},\n {'params': self.prompt_transformer.parameters(), 'lr': self.cfg.training.krm_lr}])\n if load_ckpt_path and os.path.isfile(load_ckpt_path):\n self.ema_loss = self.load_ckpt(load_ckpt_path, True) \n else:\n self.train_i, self.train_epoch = 1, 1\n self.ema_loss = 1\n\n def train(self, epochs):\n if self.log_writer == None:\n raise \"Call `self.train_init()` to initialize training first!\"\n print('Checkpoints dir: ', self.save_ckpt_dir)\n start_epoch = self.train_epoch\n self.set_train(True) \n for self.train_epoch in range(start_epoch, epochs + 1): \n progress_bar = tqdm(total = self.data_generator.sample_count, \n position = 0, leave = True, desc = \"Epoch %d\"%self.train_epoch, dynamic_ncols = True)\n for contra_data, edit_data in self.data_generator:\n # train after edit\n log_dict = self.__train_a_batch__(*contra_data, *edit_data)\n # log\n log_dict['Epoch'] = self.train_epoch\n if self.train_i % self.log_per_i == 0:\n self.write_logs(self.train_i, log_dict)\n # if self.train_i % self.save_ckpt_per_i == 0:\n # self.save_ckpt(self.train_i, self.train_epoch, log_dict['Loss'])\n self.train_i += 1 \n progress_bar.update(len(contra_data[0]))\n progress_bar.close() \n self.set_train(False)\n\n def compute_contrastive_losses(self, knowl_rep_model, contra_knowl, contra_q_rel, contra_q_gen, contra_q_loc, \n query_knowledge_t, query_prototype_t, constra_hinge_scale, rep_dim, eps=1e-8):\n bsz = len(contra_knowl)\n device = next(knowl_rep_model.parameters()).device\n rng = np.random.RandomState(42) # For reproducibility\n cc = rng.choice([0, 1], bsz)\n \n q1 = [[contra_q_rel, contra_q_gen][c][i] for i, c in enumerate(cc)]\n q2 = [[contra_q_rel, contra_q_gen][c][i] for i, c in enumerate(1-cc)]\n\n q1_reps = knowl_rep_model(q1, knowl_or_query='q') # [bsz, rep_dim]\n q2_reps = knowl_rep_model(q2, knowl_or_query='q') # [bsz, rep_dim]\n knowledge_reps = knowl_rep_model(contra_knowl, knowl_or_query='k') # [bsz, rep_dim]\n knowl_rep_prot = knowl_rep_model.get_knowl_rep_prot() # Prototype representation\n\n knowl_reps_with_proto = torch.cat([knowledge_reps, knowl_rep_prot])\n scale_factor = 1 / rep_dim**0.5 # Scaling factor for dot product\n\n sim_q1 = (q1_reps @ knowl_reps_with_proto.T) * scale_factor # [bsz, bsz+1]\n sim_q1 = torch.softmax(sim_q1 * query_knowledge_t, 1)\n loss_contra_q1 = - torch.log(torch.diag(sim_q1) + eps).mean(0)\n\n sim_q2 = (q2_reps @ knowledge_reps.T) * scale_factor # [bsz, bsz]\n sim_q2 = sim_q2 * (1 - torch.eye(bsz, device=device)) # Zero out self-similarity\n sim_q2 = sim_q2 + torch.diag((q2_reps @ knowl_rep_prot.T)[:, 0] * scale_factor)\n sim_q2 = torch.softmax(sim_q2 * query_prototype_t, 1)\n second_sim_q2 = torch.topk(sim_q2, 2, 1).values[:, 1]\n sim_q2_diag = torch.diag(sim_q2)\n sim_q2_filtered = torch.masked_select(sim_q2_diag, sim_q2_diag < second_sim_q2 * constra_hinge_scale)\n if len(sim_q2_filtered) == 0:\n loss_contra_q2 = 0\n else:\n loss_contra_q2 = - torch.log(sim_q2_filtered + eps).mean(0)\n\n losses_contra_q3 = {}\n loss_contra_q3 = 0\n for k, cql in contra_q_loc.items():\n q3_reps = knowl_rep_model(cql, knowl_or_query='q') # [bsz, rep_dim]\n sim_q3 = (q3_reps @ knowl_reps_with_proto.T) * scale_factor # [bsz, bsz+1]\n sim_q3 = torch.softmax(sim_q3 * query_prototype_t, 1)\n second_sim_q3 = torch.topk(sim_q3, 2, 1).values[:, 1]\n sim_q3_proto = sim_q3[:, -1]\n sim_q3_filtered = torch.masked_select(sim_q3_proto, sim_q3_proto < second_sim_q3 * constra_hinge_scale)\n if len(sim_q3_filtered) == 0:\n l = 0\n else:\n l = - torch.log(sim_q3_filtered + eps).mean(0)\n losses_contra_q3[k] = l\n loss_contra_q3 += l\n\n loss_contra = loss_contra_q1 + loss_contra_q2 + loss_contra_q3\n return loss_contra_q1, loss_contra_q2, loss_contra_q3, losses_contra_q3, loss_contra\n\n\n def __train_a_batch__(self, contra_knowl, contra_q_rel, contra_q_gen, contra_q_loc,\n batch_relia_xym, batch_gen_xym, batch_loc_xym):\n # prediction before edit for locality loss\n with torch.no_grad():\n for loss_name, sp in batch_loc_xym.items():\n input_ids, _, masks = sp\n self.adopted_prompts = [torch.zeros([0, self.cfg.model_hidden_size], device = self.device)] * len(input_ids)\n pre_logits = self.model(input_ids = input_ids).logits\n batch_loc_xym[loss_name] = ((input_ids, masks), pre_logits)\n loss = 0 \n bsz = len(contra_knowl)\n eps = self.cfg.training.eps\n ehs = self.cfg.training.edit_hinge_scale\n \n # Compute contrastive losses using the refactored function\n loss_contra_q1, loss_contra_q2, loss_contra_q3, losses_contra_q3, loss_contra = self.compute_contrastive_losses(\n self.knowl_rep_model, \n contra_knowl, \n contra_q_rel, \n contra_q_gen, \n contra_q_loc,\n self.cfg.training.query_knowledge_t,\n self.cfg.training.query_prototype_t,\n self.cfg.training.constra_hinge_scale,\n self.cfg.knowledge_rep_dim,\n eps\n )\n loss += loss_contra * self.cfg.training.contra_lambda\n # edit loss\n knowledge_reps = self.knowl_rep_model(contra_knowl, knowl_or_query = 'k')\n self.adopted_prompts = [i for i in self.prompt_transformer(knowledge_reps)]\n # compute reliability loss\n (input_ids, label_ids, masks) = batch_relia_xym\n relia_loss = hinge_label_loss(self.model, input_ids, label_ids, masks, True, eps, ehs)\n loss += relia_loss * self.cfg.training.relia_lambda\n # compute generality loss\n gen_losses = {}\n for loss_name, sp in batch_gen_xym.items():\n input_ids, label_ids, masks = sp\n gen_loss = hinge_label_loss(self.model, input_ids, label_ids, masks, True, eps, ehs)\n gen_losses[loss_name] = gen_loss\n loss += gen_loss * self.cfg.training.gen_lambda\n # compute locality loss\n loc_losses = {}\n for loss_name, sp in batch_loc_xym.items():\n (input_ids, masks), pre_logits = sp\n post_logits = self.model(input_ids = input_ids).logits\n loc_loss = logit_KL_loss(pre_logits, post_logits, masks)\n loc_losses[loss_name] = loc_loss\n loss += loc_loss * self.cfg.training.loc_lambda\n # update\n loss.backward()\n self.opt.step()\n self.opt.zero_grad()\n self.ema_loss = self.ema_loss + (loss.detach() - self.ema_loss) / self.log_per_i\n log_dict = {\n 'Loss': loss,\n 'EMA Loss': self.ema_loss, \n 'Contrastive loss': loss_contra,\n 'Contrastive loss q2k': loss_contra_q1,\n 'Contrastive loss q2prot': loss_contra_q2 + loss_contra_q3,\n 'Contrastive loss q2prot-rg': loss_contra_q2,\n 'Contrastive loss q2prot-loc': losses_contra_q3,\n 'Reliability loss': relia_loss,\n 'Generality loss': gen_losses,\n 'Locality loss': loc_losses\n }\n return log_dict\n\n def write_logs(self, i, logs:dict):\n for log_name, log in logs.items():\n if type(log) == dict:\n logs1 = {}\n for n, l in log.items():\n logs1[log_name + '-' + n] = l\n self.write_logs(i, logs1)\n else: \n self.log_writer.add_scalar(log_name, log, i)\n\n def save_ckpt(self, i:int, epoch:int, loss:float):\n ckpt_name = 'epoch-%d-i-%d-ema_loss-%.4f'%(epoch, i, self.ema_loss)\n ckpt_path = os.path.join(self.save_ckpt_dir, ckpt_name)\n ckpt = {\n 'i': i,\n 'epoch': epoch,\n 'loss': loss,\n 'knowl_rep_model': self.knowl_rep_model.state_dict(),\n 'prompt_transformer': self.prompt_transformer.state_dict(),\n 'opt': self.opt.state_dict()\n }\n torch.save(ckpt, ckpt_path)\n\n def load_ckpt(self, ckpt_path, restrict = True, load_opt = True):\n ckpt = torch.load(ckpt_path, 'cpu')\n self.train_i = ckpt['i']\n self.train_epoch = ckpt['epoch']\n self.knowl_rep_model.load_state_dict(ckpt['knowl_rep_model'], restrict)\n self.prompt_transformer.load_state_dict(ckpt['prompt_transformer'], restrict)\n if load_opt:\n self.opt.load_state_dict(ckpt['opt'])\n print('Load RECIPE checkpoints from', ckpt_path)\n return ckpt['loss']\n\ndef hinge_label_loss(model, input_ids:torch.Tensor, label_ids:torch.Tensor, \n masks:torch.Tensor, average = True, eps = 1e-8, hinge_scale = 1.1):\n # input_ids/label_ids/masks: [batch, max_len]\n logits = model(input_ids = input_ids).logits # [batch, max_len, voc_size]\n pre_p = torch.softmax(logits, 2) # [batch, max_len, voc_size]\n second_pre_p = torch.topk(pre_p, 2, -1).values[:, :, 1] # [batch, max_len]\n pre_p = pre_p.gather(-1, label_ids.unsqueeze(-1)).squeeze(-1) # [batch, max_len]\n masks = masks * (pre_p < second_pre_p * hinge_scale)\n pre_p = torch.masked_select(pre_p, masks.to(bool))\n loss = - torch.log(pre_p + eps).sum() # [batch, max_len] \n if average:\n sm = masks.sum() \n if sm != 0:\n loss = loss / sm\n return loss\n\ndef label_loss(model, input_ids:torch.Tensor, label_ids:torch.Tensor, masks:torch.Tensor, average = True):\n # input_ids/label_ids/masks: [batch, max_len]\n logits = model(input_ids = input_ids).logits\n log_pre_p = torch.log_softmax(logits, 2) # [batch, max_len, voc_size]\n log_pre_p = log_pre_p.gather(-1, label_ids.unsqueeze(-1)).squeeze(-1) # [batch, max_len]\n loss = -(log_pre_p * masks).sum()\n if average:\n loss = loss / masks.sum() \n return loss\n\ndef logit_KL_loss(logits1:torch.Tensor, logits2:torch.Tensor, masks:torch.Tensor, average = True):\n # logits1/logits2: [batch, max_len, voc_size], masks: [batch, max_len]\n log_p1 = torch.log_softmax(logits1, 2)\n log_p2 = torch.log_softmax(logits2, 2)\n p1 = torch.softmax(logits1, 2)\n kl_loss = (p1 * (log_p1 - log_p2)).sum(2) # [batch, max_len]\n loss = (kl_loss * masks).sum()\n if average:\n loss = loss / masks.sum() \n return loss\n\ndef find_module(module, module_path:str):\n for comp in module_path.split('.'):\n if hasattr(module, comp):\n module = getattr(module, comp)\n elif comp.isdigit():\n module = module[int(comp)]\n else:\n raise RuntimeError(f\"Couldn't find child module {comp}\")\n return module\n\ndef cross_cos_sim(a, b):\n # compute cos similarly: [n, d], [m, d] -> [n, m]\n a = torch.nn.functional.normalize(a, 2, 1)\n b = torch.nn.functional.normalize(b, 2, 1)\n return a @ b.T\n\ndef get_mask_matrix(v, max_n = None):\n max_n = max_n if max_n != None else torch.max(v)\n return torch.arange(1, max_n + 1).unsqueeze(0) <= v.unsqueeze(1)\n" }, { "task_id": 1, "indent": 2, "script": "\npython test_recipe.py -en 'recipe' -mn 'llama-7b' -et 'sequential' -dn 'zsre' -edn 1000 \n", "latex_code": "\n\\subsection{Dynamic Prompt Retrieval with Knowledge Sentinel}\n\\label{subsection:MERKS}\nThe existence of a query-related prompt in the repository is usually determined by using a manually set similarity threshold \\cite{RASE}. However, using a fixed threshold does not account for the fact that the sensitivity to similarity with related knowledge varies among different queries due to semantic differences.\nThe Knowledge Sentinel (KS) serves as an intermediary leveraged to dynamically compute similarity thresholds for various queries. To be specific, KS $\\Theta\\in\\mathcal{R}$ is a trainable word embedding of $f_{rm}$ with token length $c$. It is transformed into the knowledge representation space as: \n$r_{\\Theta}= \\mathbf{MLP}_{K}(f_{rm}(\\Theta))$.\nGiven a query $q$ and the knowledge retrieval repository $\\mathcal{K}_t=\\{(r_{k_\\tau}, p_{k_\\tau})\\}_{\\tau=1}^t$, the prompt retrieval process is as follows:\n\\begin{equation}\n \\label{equation:query_representation}\n \\tilde{r}_{q} = \\mathbf{MLP}_Q(f_{rm}(q))\n\\end{equation}\n\\begin{equation}\n\\begin{split}\n\\mathbf{KS}(q) = \n\\begin{cases}\n p_{k_j} & \\tilde{r}_{q}^T \\cdot r_{k_{j}} > \\tilde{r}_{q}^T \\cdot r_{\\Theta}\\\\\n \\emptyset & \\text{otherwise}\n\\end{cases}\n\\end{split}\n\\end{equation}\nwhere $j = {\\mathrm{argmax}}_{\\tau=1,\\ldots,t}\\ \\tilde{r}_{q}^T \\cdot r_{k_\\tau}$,\nwhich can be efficiently searched via modern vector databases or search engines (e.g.,~\\citet{DBLP:conf/nips/ChenZWLLLYW21}). $\\mathbf{MLP}_Q$ is the MLP that maps the query representation to the knowledge representation space. If the retrieved continuous prompt is not sufficiently similar to the query compared to KS, an empty set is returned. Hence, the inference of LLMs is not modified.\n", "completion_path": "./editors/recipe/recipe.py", "namespace": "editors.recipe.recipe.RECIPE.retrieve_and_get_ids_sim", "type": "method", "signature_position": [ 157, 157 ], "body_position": [ 158, 166 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Generate query representations using the knowledge representation model.\n# This corresponds to Eq. \\ref{equation:query_representation} where \\tilde{r}_{q} = \\mathbf{MLP}_Q(f_{rm}(q)).\n# Transform input queries into the same representation space as the knowledge repository.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nquery_reps = self.knowl_rep_model(input_queries, knowl_or_query = 'q') # [n, knowledge_rep_dim] \n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Compute similarity between query representations and knowledge base.\n# Implements \\tilde{r}_{q}^T \\cdot r_{k_\\tau} from the LaTeX, with a scaling factor for stability.\n# Measure relevance of each knowledge entry to the query using dot product similarity.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nsim_matrx = (query_reps @ self.knowledge_base.T) / self.cfg.knowledge_rep_dim**0.5 # [n, edit_n]\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Extract similarity with the Knowledge Sentinel (prototype).\n# Corresponds to \\tilde{r}_{q}^T \\cdot r_{\\Theta} in the LaTeX, where r_{\\Theta} is the KS representation.\n# Use KS as a dynamic threshold for retrieval decisions.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nsim_with_prototype = sim_matrx[:, :1] \n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Sort similarities to identify top matches.\n# Implements j = {\\mathrm{argmax}}_{\\tau=1,\\ldots,t}\\ \\tilde{r}_{q}^T \\cdot r_{k_\\tau} from the LaTeX.\n# Rank knowledge entries by relevance to select the most similar ones.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nsorted_sim, order = torch.sort(sim_matrx, 1, True) # [n, edit_n]\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Apply filtering conditions for retrieval.\n# Implements the condition \\tilde{r}_{q}^T \\cdot r_{k_{j}} > \\tilde{r}_{q}^T \\cdot r_{\\Theta} from the LaTeX,\n# with an additional minimum similarity constraint not in the paper.\n# Ensure retrieved prompts exceed both the KS threshold and a predefined minimum.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nmask = sorted_sim[:, :self.retr_top_k] > self.retr_min_sim\nmask &= sorted_sim[:, :self.retr_top_k] > sim_with_prototype\n# [End Snippet 5]\n\n# ---------------------------------------------------------------------------\n# Snippet 6: Extract and organize retrieved indices.\n# This finalizes the \\mathbf{KS}(q) function by returning relevant prompt indices or an empty set.\n# Provide a structured output of retrieved prompt IDs per query.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 6]\nretrieved_ids = torch.masked_select(order[:, :self.retr_top_k], mask)\nretrieved_ids = torch.split(retrieved_ids, mask.sum(1).tolist()) # retrieved indexes\n\nreturn retrieved_ids, sorted_sim, order # [retr_ids_1, retr_ids_2, ..., retr_ids_n]\n# [End Snippet 6]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - Scaling Factor in Similarity Calculation: The reference implementation includes a step where the similarity scores between the query representation and the knowledge base are scaled by dividing them by the square root of the dimensionality of the knowledge representations. This scaling stabilizes the similarity values, particularly in high-dimensional spaces, and ensures that the magnitude of the scores is consistent for comparison. Without this step in the LaTeX description, the workflow lacks a critical adjustment that influences the threshold comparisons and retrieval decisions, potentially leading to inconsistent results.\n - Dual-Condition Filtering for Multiple Prompts: The reference implementation allows for the retrieval of multiple knowledge entries per query by evaluating each candidate against two conditions: exceeding a minimum similarity threshold and surpassing the similarity to the knowledge sentinel. This process involves sorting the similarities, applying these criteria to the top candidates, and retrieving those that satisfy both conditions, resulting in a flexible number of retrieved prompts. The LaTeX description does not mention this dual-condition evaluation or the possibility of retrieving multiple prompts, limiting the workflow to a single prompt retrieval scenario and omitting a key aspect of the method\u2019s flexibility.\n\n - Mismatched Details:\n - None\n", "Missing_details": [ "\n- Scaling Factor in Similarity Calculation: The reference implementation includes a step where the similarity scores between the query representation and the knowledge base are scaled by dividing them by the square root of the dimensionality of the knowledge representations. This scaling stabilizes the similarity values, particularly in high-dimensional spaces, and ensures that the magnitude of the scores is consistent for comparison. Without this step in the LaTeX description, the workflow lacks a critical adjustment that influences the threshold comparisons and retrieval decisions, potentially leading to inconsistent results.\n", "\n- Dual-Condition Filtering for Multiple Prompts: The reference implementation allows for the retrieval of multiple knowledge entries per query by evaluating each candidate against two conditions: exceeding a minimum similarity threshold and surpassing the similarity to the knowledge sentinel. This process involves sorting the similarities, applying these criteria to the top candidates, and retrieving those that satisfy both conditions, resulting in a flexible number of retrieved prompts. The LaTeX description does not mention this dual-condition evaluation or the possibility of retrieving multiple prompts, limiting the workflow to a single prompt retrieval scenario and omitting a key aspect of the method\u2019s flexibility.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - self (RECIPE): Instance of the RECIPE class containing model configuration and state.\n - input_queries (List[str]): List of query strings to retrieve relevant prompts for.\n The method also relies on the following variables defined in the RECIPE class:\n - self.knowl_rep_model (KnowledgeRepModel): KnowledgeRepModel instance for encoding queries.\n - self.knowledge_base (Torch.Tensor, shape=[1, hidden size]): Tensor storing knowledge representations.\n - self.cfg (RECIPEConfig): RECIPEConfig instance containing knowledge_rep_dim and retr_top_k.\n - self.retr_min_sim (int): Minimum similarity threshold for retrieval.\n - self.retr_top_k (int): Number of top similar prompts to retrieve.\n", "Arguments_list": [ { "name": "self", "string": "\n- self (RECIPE): Instance of the RECIPE class containing model configuration and state.\n", "dependency": null }, { "name": "input_queries", "string": "\n- input_queries (List[str]): List of query strings to retrieve relevant prompts for.\n", "dependency": null }, { "name": "self.knowl_rep_model", "string": "\n- self.knowl_rep_model (KnowledgeRepModel): KnowledgeRepModel instance for encoding queries.\n", "dependency": null }, { "name": "self.knowledge_base", "string": "\n- self.knowledge_base (Torch.Tensor, shape=[1, hidden size]): Tensor storing knowledge representations.\n", "dependency": null }, { "name": "self.cfg", "string": "\n- self.cfg (RECIPEConfig): RECIPEConfig instance containing knowledge_rep_dim and retr_top_k.\n", "dependency": null }, { "name": "self.retr_min_sim", "string": "\n- self.retr_min_sim (int): Minimum similarity threshold for retrieval.\n", "dependency": null }, { "name": "self.retr_top_k", "string": "\n- self.retr_top_k (int): Number of top similar prompts to retrieve.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-File Dependencies: \n None\n\n - Cross-File Dependencies:\n None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.sort\n - torch.masked_select\n - torch.split\n", "list": [ "torch.sort", "torch.masked_select", "torch.split" ] }, "Return": { "Return_String": "\nOutput Variables:\n - retrieved_ids (List[torch.Tensor]): Indices of retrieved knowledge entries per query.\n - sorted_sim (torch.Tensor, shape=[n, edit_n]): Sorted similarity scores for each query against all knowledge entries.\n - order (torch.Tensor, shape=[n, edit_n]): Indices of knowledge entries in descending order of similarity.\n", "Return_list": [ { "name": "retrieved_ids", "string": "\n- retrieved_ids (List[torch.Tensor]): Indices of retrieved knowledge entries per query.\n", "dependency": null }, { "name": "sorted_sim", "string": "\n- sorted_sim (torch.Tensor, shape=[n, edit_n]): Sorted similarity scores for each query against all knowledge entries.\n", "dependency": null }, { "name": "order", "string": "\n- order (torch.Tensor, shape=[n, edit_n]): Indices of knowledge entries in descending order of similarity.\n", "dependency": null } ] }, "ori_python_file": "from editors.editor import BaseEditor, EditorConfig\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nfrom typing import Dict, List, Tuple \nfrom dataclasses import dataclass, asdict\nimport numpy as np\nfrom copy import deepcopy\nimport torch, os, yaml\nfrom torch.utils.tensorboard import SummaryWriter \nfrom torch.optim import Adam\nfrom .models import KnowledgeRepModel, PromptTransformer\nfrom utils.data import ParallelDataset\nfrom datetime import datetime\nfrom tqdm import tqdm\nimport random\nos.environ['PYTHONHASHSEED'] = str(42)\nos.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\nnp.random.seed(42)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\ntorch.use_deterministic_algorithms(True)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nrandom.seed(42)\ntorch.cuda.synchronize()\n\n@dataclass\nclass RECIPEConfig(EditorConfig):\n @dataclass\n class TrainingConfig():\n krm_lr: float\n pt_lr: float\n relia_lambda: float\n gen_lambda: float\n loc_lambda: float\n contra_lambda: float\n query_knowledge_t: float\n query_prototype_t: float\n constra_hinge_scale: float # w/hinge >= 1, w/o hinge== 999999 \n edit_hinge_scale: float # w/hinge >= 1, w/o hinge== 999999 \n # set in train_init\n batch_size:int = None\n sample_count:int = None\n random_seed:int = None\n eps:float = 1e-8\n \n prompt_token_n: int\n edit_model_name: str\n knowledge_rep_dim: int\n knowl_rep_prot_token_n: int\n model_hidden_size: int\n begin_layer_path:str\n lm_head_path:str\n training: TrainingConfig\n\n @classmethod\n def from_yaml(self, fpath):\n with open(fpath, \"r\") as f:\n data = yaml.safe_load(f)\n data['training'] = self.TrainingConfig(**data['training'])\n return self(**data)\n @classmethod\n def from_json(self, fpath):\n raise\n \nclass RECIPE(BaseEditor):\n def __init__(self, \n model: AutoModelForCausalLM,\n tokenizer: AutoTokenizer,\n config: RECIPEConfig,\n device = 'cuda',\n krm_base_path = 'models/roberta-base',\n retr_top_k = 1,\n retr_min_sim = -999,\n auto_retrieve = True, \n ckpt_path = None \n ):\n super().__init__(model, tokenizer, device)\n self.cfg = config\n # initialize model & parameters\n self.knowl_rep_model = KnowledgeRepModel(config.knowledge_rep_dim, \n config.knowl_rep_prot_token_n, self.device, krm_base_path)\n self.prompt_transformer = PromptTransformer(config.knowledge_rep_dim, \n config.model_hidden_size, config.prompt_token_n, self.device)\n # initialize hooks\n self.begin_layer = find_module(self.model, self.cfg.begin_layer_path)\n self.lm_head = find_module(self.model, self.cfg.lm_head_path)\n self.model.forward = self.register_model_forward_hook(self.model, \n self.model.forward, self.begin_layer, self.lm_head)\n self.begin_layer_hook = self.register_editing_hook(self.begin_layer, self.lm_head)\n # initialize editing prompts\n self.restore_to_original_model()\n self.auto_retrieve = auto_retrieve \n self.retr_top_k = retr_top_k\n self.retr_min_sim = retr_min_sim\n self.set_train(False) \n if ckpt_path != None:\n self.load_ckpt(ckpt_path, load_opt = False)\n \n ############################################################################\n ############################# Initialize ###################################\n ############################################################################\n def register_editing_hook(self, begin_layer, lm_head_layer):\n def forward_pre_hook(module, args):\n # If do not has past_key_values, add editing prompts before reps.\n if not module.has_past_kv:\n args = args[0]\n args = torch.stack([\n torch.cat([p, inp[:-len(p) if len(p) != 0 else None]], 0)\n for inp, p in zip(args, self.adopted_prompts)], 0)\n return (args, )\n def forward_hook(module, args, output):\n if not module.has_past_kv:\n max_n = max([len(p) for p in self.adopted_prompts])\n output = torch.stack([\n ot[len(p):len(p)-max_n if len(p)-max_n != 0 else None]\n for ot, p in zip(output, self.adopted_prompts)], 0)\n return output\n begin_layer_hook = begin_layer.register_forward_pre_hook(forward_pre_hook)\n lm_head_layer_hook = lm_head_layer.register_forward_hook(forward_hook)\n return [begin_layer_hook, lm_head_layer_hook]\n\n def register_model_forward_hook(self, model, model_forward, begin_layer, lm_head):\n if hasattr(model, 'recipe_hooked'):\n return model_forward\n model.recipe_hooked = True\n def forward_recipe(**kargs):\n if 'past_key_values' in kargs and kargs['past_key_values'] != None:\n begin_layer.has_past_kv = True\n lm_head.has_past_kv = True\n else:\n begin_layer.has_past_kv = False\n lm_head.has_past_kv = False\n b, l = kargs['input_ids'].shape\n inp_sents = [self.tokenizer.decode(i, skip_special_tokens=True) \n for i in kargs['input_ids']]\n if self.auto_retrieve: \n retrieved_ids = self.retrieve_and_get_ids_sim(inp_sents)[0]\n # print(retrieved_ids)\n self.adopted_prompts = [self.prompts_base[i].reshape(\n len(i)*self.cfg.prompt_token_n, self.cfg.model_hidden_size) \n for i in retrieved_ids]\n if len(self.adopted_prompts) != b:\n print(len(self.adopted_prompts), b) \n raise ValueError\n pad = torch.ones([b, max([len(i) for i in self.adopted_prompts])], \n dtype = torch.long).to(self.device)\n if 'attention_mask' in kargs and kargs['attention_mask'] != None:\n kargs['attention_mask'] = torch.cat([kargs['attention_mask'], pad], 1)\n kargs['input_ids'] = torch.cat([kargs['input_ids'], pad * self.tokenizer.pad_token_id], 1)\n return model_forward(**kargs)\n return forward_recipe\n\n ############################################################################\n ############################# RECIPE Edit Related ############################\n ############################################################################\n def retrieve_and_get_ids_sim(self, input_queries:List[str]):\n query_reps = self.knowl_rep_model(input_queries, knowl_or_query = 'q') # [n, knowledge_rep_dim] \n sim_matrx = (query_reps @ self.knowledge_base.T) / self.cfg.knowledge_rep_dim**0.5 # cross_cos_sim(query_reps, self.knowledge_base) # [n, edit_n]\n sim_with_prototype = sim_matrx[:, :1] \n sorted_sim, order = torch.sort(sim_matrx, 1, True) # [n, edit_n]\n mask = sorted_sim[:, :self.retr_top_k] > self.retr_min_sim\n mask &= sorted_sim[:, :self.retr_top_k] > sim_with_prototype\n retrieved_ids = torch.masked_select(order[:, :self.retr_top_k], mask)\n retrieved_ids = torch.split(retrieved_ids, mask.sum(1).tolist()) # retrieved indexes\n return retrieved_ids, sorted_sim, order # [retr_ids_1, retr_ids_2, ..., retr_ids_n]\n\n ############################################################################\n ############################# Editor Basic Functions #######################\n ############################################################################\n def name_of_editor_and_model(self)->Tuple[str, str]:\n return 'recipe', self.cfg.edit_model_name\n\n def if_can_batch_edit(self):\n return True\n \n def restore_to_original_model(self):\n self.knowledge_base_nl = [''] # [edit_n, knowledge_rep_dim]\n self.knowledge_base = self.knowl_rep_model.get_knowl_rep_prot() # [edit_n, knowledge_rep_dim]\n self.prompts_base = torch.zeros([1, self.cfg.prompt_token_n, self.cfg.model_hidden_size], \n device = self.device) # [edit_n, prompt_token_n, model_hidden_size]\n self.adopted_prompts = [] # List[torch.Tensor], len(List) = btach_size, Tensor.size = [retr_n * prompt_token_n, model_hidden_size]\n\n def edit_batch(self, requests: List[Dict]):\n '''requests = [\n {'prompt':str, 'subject':str, 'target_new':str}\n {'prompt':str, 'subject':str, 'target_new':str}, ...\n ]\n '''\n rs = []\n for r in requests:\n rs.append(r['prompt'] + r['target_new'])\n self.knowledge_base_nl.extend(rs)\n new_reps = self.knowl_rep_model(rs, knowl_or_query = 'k')\n new_prompts = self.prompt_transformer(new_reps)\n self.knowledge_base = torch.cat([self.knowledge_base, new_reps], 0)\n self.prompts_base = torch.cat([self.prompts_base, new_prompts], 0)\n\n return self.knowledge_base_nl, self.knowledge_base, self.prompts_base\n\n def edit_one_piece(self, request: Dict) -> None:\n \"\"\"\n request = {'prompt':str, 'subject':str, 'target_new':str}\n \"\"\"\n requests = [request]\n for r in range(len(requests)):\n requests[r]['prompt'] = requests[r]['prompt'].strip() + \" \"\n requests[r]['target_new'] = requests[r]['target_new'].strip()\n knowledge_base_nl, knowledge_base, prompts_base= self.edit_batch([request])\n\n ############################################################################\n ############################# RECIPE Training ################################\n ############################################################################\n def set_train(self, if_train = False):\n self.model.train(False)\n self.model.requires_grad_(False)\n self.knowl_rep_model.train(if_train)\n self.knowl_rep_model.requires_grad_(if_train)\n self.prompt_transformer.train(if_train)\n self.prompt_transformer.requires_grad_(if_train)\n self.auto_retrieve = not if_train\n\n def train_init(self, sample_count, get_data_by_ids, batch_size, \n records_dir:str = 'train_records', train_name_prefix = None, \n train_name:str = None, load_ckpt_path:str = None, \n save_ckpt_per_i = 3000, log_per_i = 10, random_seed = None): \n '''\n Used to initialize `ParallelDataset`:\n sample_count: count of used data in dataset.\n get_data_by_ids: function getting data by ids, assume data structure: (\n batch_knowledge: List[str], len = batch_size\n contra_q: List[str], len = batch_size * 3\n contra_sim_m: torch.Tensor[batch_size, batch_size * 3]\n batch_relia_xym: (input_ids, label_ids, masks), \n batch_gen_xym: {\n loss_name_1: (input_ids, label_ids, masks),\n loss_name_2: (input_ids, label_ids, masks), ...\n },\n batch_loc_xym: {\n loss_name_1: (input_ids, masks)\n loss_name_2: (input_ids, masks), ...\n } \n ), where `input_ids`, `label_ids`, and `label_ids` are with shape \n [batch_size, length]\n '''\n # initialize data generator\n self.rng = np.random.default_rng(random_seed)\n self.data_generator = ParallelDataset(sample_count, get_data_by_ids, \n batch_size, True, 16, False, random_seed)\n # initialize checkpoint/log directory and writer\n t = datetime.now().strftime('%Y.%m.%d-%H.%M.%S')\n train_name = (train_name_prefix + '-' if train_name_prefix else \"\") + \\\n (train_name if train_name else t)\n records_dir = os.path.join(records_dir, *self.name_of_editor_and_model(), train_name)\n self.save_ckpt_dir = os.path.join(records_dir, 'checkpoints')\n if not os.path.exists(self.save_ckpt_dir):\n os.makedirs(self.save_ckpt_dir)\n logs_path = os.path.join(records_dir, 'logs')\n if not os.path.exists(logs_path):\n os.makedirs(logs_path)\n with open(os.path.join(records_dir, 'config.yaml'), 'w') as f:\n self.cfg.training.batch_size = batch_size\n self.cfg.training.sample_count = sample_count\n self.cfg.training.random_seed = random_seed\n yaml.dump(asdict(self.cfg), f)\n self.log_writer = SummaryWriter(logs_path)\n self.save_ckpt_per_i = save_ckpt_per_i\n self.log_per_i = log_per_i\n # initialize optimizer and load checkpoints\n self.opt = Adam([\n {'params': self.knowl_rep_model.parameters(), 'lr': self.cfg.training.krm_lr},\n {'params': self.prompt_transformer.parameters(), 'lr': self.cfg.training.krm_lr}])\n if load_ckpt_path and os.path.isfile(load_ckpt_path):\n self.ema_loss = self.load_ckpt(load_ckpt_path, True) \n else:\n self.train_i, self.train_epoch = 1, 1\n self.ema_loss = 1\n\n def train(self, epochs):\n if self.log_writer == None:\n raise \"Call `self.train_init()` to initialize training first!\"\n print('Checkpoints dir: ', self.save_ckpt_dir)\n start_epoch = self.train_epoch\n self.set_train(True) \n for self.train_epoch in range(start_epoch, epochs + 1): \n progress_bar = tqdm(total = self.data_generator.sample_count, \n position = 0, leave = True, desc = \"Epoch %d\"%self.train_epoch, dynamic_ncols = True)\n for contra_data, edit_data in self.data_generator:\n # train after edit\n log_dict = self.__train_a_batch__(*contra_data, *edit_data)\n # log\n log_dict['Epoch'] = self.train_epoch\n if self.train_i % self.log_per_i == 0:\n self.write_logs(self.train_i, log_dict)\n # if self.train_i % self.save_ckpt_per_i == 0:\n # self.save_ckpt(self.train_i, self.train_epoch, log_dict['Loss'])\n self.train_i += 1 \n progress_bar.update(len(contra_data[0]))\n progress_bar.close() \n self.set_train(False)\n\n def compute_contrastive_losses(self, knowl_rep_model, contra_knowl, contra_q_rel, contra_q_gen, contra_q_loc, \n query_knowledge_t, query_prototype_t, constra_hinge_scale, rep_dim, eps=1e-8):\n bsz = len(contra_knowl)\n device = next(knowl_rep_model.parameters()).device\n rng = np.random.RandomState(42) # For reproducibility\n cc = rng.choice([0, 1], bsz)\n \n q1 = [[contra_q_rel, contra_q_gen][c][i] for i, c in enumerate(cc)]\n q2 = [[contra_q_rel, contra_q_gen][c][i] for i, c in enumerate(1-cc)]\n\n q1_reps = knowl_rep_model(q1, knowl_or_query='q') # [bsz, rep_dim]\n q2_reps = knowl_rep_model(q2, knowl_or_query='q') # [bsz, rep_dim]\n knowledge_reps = knowl_rep_model(contra_knowl, knowl_or_query='k') # [bsz, rep_dim]\n knowl_rep_prot = knowl_rep_model.get_knowl_rep_prot() # Prototype representation\n\n knowl_reps_with_proto = torch.cat([knowledge_reps, knowl_rep_prot])\n scale_factor = 1 / rep_dim**0.5 # Scaling factor for dot product\n\n sim_q1 = (q1_reps @ knowl_reps_with_proto.T) * scale_factor # [bsz, bsz+1]\n sim_q1 = torch.softmax(sim_q1 * query_knowledge_t, 1)\n loss_contra_q1 = - torch.log(torch.diag(sim_q1) + eps).mean(0)\n\n sim_q2 = (q2_reps @ knowledge_reps.T) * scale_factor # [bsz, bsz]\n sim_q2 = sim_q2 * (1 - torch.eye(bsz, device=device)) # Zero out self-similarity\n sim_q2 = sim_q2 + torch.diag((q2_reps @ knowl_rep_prot.T)[:, 0] * scale_factor)\n sim_q2 = torch.softmax(sim_q2 * query_prototype_t, 1)\n second_sim_q2 = torch.topk(sim_q2, 2, 1).values[:, 1]\n sim_q2_diag = torch.diag(sim_q2)\n sim_q2_filtered = torch.masked_select(sim_q2_diag, sim_q2_diag < second_sim_q2 * constra_hinge_scale)\n if len(sim_q2_filtered) == 0:\n loss_contra_q2 = 0\n else:\n loss_contra_q2 = - torch.log(sim_q2_filtered + eps).mean(0)\n\n losses_contra_q3 = {}\n loss_contra_q3 = 0\n for k, cql in contra_q_loc.items():\n q3_reps = knowl_rep_model(cql, knowl_or_query='q') # [bsz, rep_dim]\n sim_q3 = (q3_reps @ knowl_reps_with_proto.T) * scale_factor # [bsz, bsz+1]\n sim_q3 = torch.softmax(sim_q3 * query_prototype_t, 1)\n second_sim_q3 = torch.topk(sim_q3, 2, 1).values[:, 1]\n sim_q3_proto = sim_q3[:, -1]\n sim_q3_filtered = torch.masked_select(sim_q3_proto, sim_q3_proto < second_sim_q3 * constra_hinge_scale)\n if len(sim_q3_filtered) == 0:\n l = 0\n else:\n l = - torch.log(sim_q3_filtered + eps).mean(0)\n losses_contra_q3[k] = l\n loss_contra_q3 += l\n\n loss_contra = loss_contra_q1 + loss_contra_q2 + loss_contra_q3\n return loss_contra_q1, loss_contra_q2, loss_contra_q3, losses_contra_q3, loss_contra\n\n\n def __train_a_batch__(self, contra_knowl, contra_q_rel, contra_q_gen, contra_q_loc,\n batch_relia_xym, batch_gen_xym, batch_loc_xym):\n # prediction before edit for locality loss\n with torch.no_grad():\n for loss_name, sp in batch_loc_xym.items():\n input_ids, _, masks = sp\n self.adopted_prompts = [torch.zeros([0, self.cfg.model_hidden_size], device = self.device)] * len(input_ids)\n pre_logits = self.model(input_ids = input_ids).logits\n batch_loc_xym[loss_name] = ((input_ids, masks), pre_logits)\n loss = 0 \n bsz = len(contra_knowl)\n eps = self.cfg.training.eps\n ehs = self.cfg.training.edit_hinge_scale\n \n # Compute contrastive losses using the refactored function\n loss_contra_q1, loss_contra_q2, loss_contra_q3, losses_contra_q3, loss_contra = self.compute_contrastive_losses(\n self.knowl_rep_model, \n contra_knowl, \n contra_q_rel, \n contra_q_gen, \n contra_q_loc,\n self.cfg.training.query_knowledge_t,\n self.cfg.training.query_prototype_t,\n self.cfg.training.constra_hinge_scale,\n self.cfg.knowledge_rep_dim,\n eps\n )\n loss += loss_contra * self.cfg.training.contra_lambda\n # edit loss\n knowledge_reps = self.knowl_rep_model(contra_knowl, knowl_or_query = 'k')\n self.adopted_prompts = [i for i in self.prompt_transformer(knowledge_reps)]\n # compute reliability loss\n (input_ids, label_ids, masks) = batch_relia_xym\n relia_loss = hinge_label_loss(self.model, input_ids, label_ids, masks, True, eps, ehs)\n loss += relia_loss * self.cfg.training.relia_lambda\n # compute generality loss\n gen_losses = {}\n for loss_name, sp in batch_gen_xym.items():\n input_ids, label_ids, masks = sp\n gen_loss = hinge_label_loss(self.model, input_ids, label_ids, masks, True, eps, ehs)\n gen_losses[loss_name] = gen_loss\n loss += gen_loss * self.cfg.training.gen_lambda\n # compute locality loss\n loc_losses = {}\n for loss_name, sp in batch_loc_xym.items():\n (input_ids, masks), pre_logits = sp\n post_logits = self.model(input_ids = input_ids).logits\n loc_loss = logit_KL_loss(pre_logits, post_logits, masks)\n loc_losses[loss_name] = loc_loss\n loss += loc_loss * self.cfg.training.loc_lambda\n # update\n loss.backward()\n self.opt.step()\n self.opt.zero_grad()\n self.ema_loss = self.ema_loss + (loss.detach() - self.ema_loss) / self.log_per_i\n log_dict = {\n 'Loss': loss,\n 'EMA Loss': self.ema_loss, \n 'Contrastive loss': loss_contra,\n 'Contrastive loss q2k': loss_contra_q1,\n 'Contrastive loss q2prot': loss_contra_q2 + loss_contra_q3,\n 'Contrastive loss q2prot-rg': loss_contra_q2,\n 'Contrastive loss q2prot-loc': losses_contra_q3,\n 'Reliability loss': relia_loss,\n 'Generality loss': gen_losses,\n 'Locality loss': loc_losses\n }\n return log_dict\n\n def write_logs(self, i, logs:dict):\n for log_name, log in logs.items():\n if type(log) == dict:\n logs1 = {}\n for n, l in log.items():\n logs1[log_name + '-' + n] = l\n self.write_logs(i, logs1)\n else: \n self.log_writer.add_scalar(log_name, log, i)\n\n def save_ckpt(self, i:int, epoch:int, loss:float):\n ckpt_name = 'epoch-%d-i-%d-ema_loss-%.4f'%(epoch, i, self.ema_loss)\n ckpt_path = os.path.join(self.save_ckpt_dir, ckpt_name)\n ckpt = {\n 'i': i,\n 'epoch': epoch,\n 'loss': loss,\n 'knowl_rep_model': self.knowl_rep_model.state_dict(),\n 'prompt_transformer': self.prompt_transformer.state_dict(),\n 'opt': self.opt.state_dict()\n }\n torch.save(ckpt, ckpt_path)\n\n def load_ckpt(self, ckpt_path, restrict = True, load_opt = True):\n ckpt = torch.load(ckpt_path, 'cpu')\n self.train_i = ckpt['i']\n self.train_epoch = ckpt['epoch']\n self.knowl_rep_model.load_state_dict(ckpt['knowl_rep_model'], restrict)\n self.prompt_transformer.load_state_dict(ckpt['prompt_transformer'], restrict)\n if load_opt:\n self.opt.load_state_dict(ckpt['opt'])\n print('Load RECIPE checkpoints from', ckpt_path)\n return ckpt['loss']\n\ndef hinge_label_loss(model, input_ids:torch.Tensor, label_ids:torch.Tensor, \n masks:torch.Tensor, average = True, eps = 1e-8, hinge_scale = 1.1):\n # input_ids/label_ids/masks: [batch, max_len]\n logits = model(input_ids = input_ids).logits # [batch, max_len, voc_size]\n pre_p = torch.softmax(logits, 2) # [batch, max_len, voc_size]\n second_pre_p = torch.topk(pre_p, 2, -1).values[:, :, 1] # [batch, max_len]\n pre_p = pre_p.gather(-1, label_ids.unsqueeze(-1)).squeeze(-1) # [batch, max_len]\n masks = masks * (pre_p < second_pre_p * hinge_scale)\n pre_p = torch.masked_select(pre_p, masks.to(bool))\n loss = - torch.log(pre_p + eps).sum() # [batch, max_len] \n if average:\n sm = masks.sum() \n if sm != 0:\n loss = loss / sm\n return loss\n\ndef label_loss(model, input_ids:torch.Tensor, label_ids:torch.Tensor, masks:torch.Tensor, average = True):\n # input_ids/label_ids/masks: [batch, max_len]\n logits = model(input_ids = input_ids).logits\n log_pre_p = torch.log_softmax(logits, 2) # [batch, max_len, voc_size]\n log_pre_p = log_pre_p.gather(-1, label_ids.unsqueeze(-1)).squeeze(-1) # [batch, max_len]\n loss = -(log_pre_p * masks).sum()\n if average:\n loss = loss / masks.sum() \n return loss\n\ndef logit_KL_loss(logits1:torch.Tensor, logits2:torch.Tensor, masks:torch.Tensor, average = True):\n # logits1/logits2: [batch, max_len, voc_size], masks: [batch, max_len]\n log_p1 = torch.log_softmax(logits1, 2)\n log_p2 = torch.log_softmax(logits2, 2)\n p1 = torch.softmax(logits1, 2)\n kl_loss = (p1 * (log_p1 - log_p2)).sum(2) # [batch, max_len]\n loss = (kl_loss * masks).sum()\n if average:\n loss = loss / masks.sum() \n return loss\n\ndef find_module(module, module_path:str):\n for comp in module_path.split('.'):\n if hasattr(module, comp):\n module = getattr(module, comp)\n elif comp.isdigit():\n module = module[int(comp)]\n else:\n raise RuntimeError(f\"Couldn't find child module {comp}\")\n return module\n\ndef cross_cos_sim(a, b):\n # compute cos similarly: [n, d], [m, d] -> [n, m]\n a = torch.nn.functional.normalize(a, 2, 1)\n b = torch.nn.functional.normalize(b, 2, 1)\n return a @ b.T\n\ndef get_mask_matrix(v, max_n = None):\n max_n = max_n if max_n != None else torch.max(v)\n return torch.arange(1, max_n + 1).unsqueeze(0) <= v.unsqueeze(1)\n" }, { "task_id": 3, "indent": 1, "completion_path": "./editors/recipe/recipe.py", "script": "\npython train_recipe.py -mn 'llama-7b' -dn 'zsre' \n", "latex_code": "\n\\noindent\\textbf{Editing:} The editing loss aims to ensure that the generated continuous prompt guides the LLM to follow the properties of reliability and generality \\cite{ZJUEditSurvey2023}. \nBased on the pairs $(q_{e_i}, a_{e_i})$, the sample-wise losses corresponding to these two properties are defined as follows:\n\\begin{gather}\n \\mathcal{L}^{(i)}_{rel} = -\\log \\hat{f}_{llm}\\left(a_{e_i}\\left|p_{k_i}\\oplus f_{emb}(q_{e_i})\\right.\\right)\\label{eq_editing_loss_rel}\\\\\n \\mathcal{L}^{(i)}_{gen} = -\\log \\hat{f}_{llm}\\left(a_{g_i}\\left|p_{k_i}\\oplus f_{emb}(q_{g_i})\\right.\\right)\\label{eq_editing_loss_gen}\\\\\n \\label{eq_editing_loss_loc}\n\\end{gather}\nwhere $p_{k_i}$ is the continuous prompt transformed through Eq. \\ref{equation:knowledge_representation} and Eq. \\ref{equation:prompt_embedding} using knowledge $k_i$ that is the concatenation of $q_{e_i}$ and $a_{e_i}$. \n", "namespace": "editors.recipe.recipe.RECIPE.hinge_label_loss", "type": "function", "signature_position": [ 459, 460 ], "body_position": [ 461, 473 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Compute model predictions and convert to probabilities\n# Implements the core probability calculation from Eq. \\ref{eq_editing_loss_rel} but adds numerical stability considerations not mentioned in paper\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nlogits = model(input_ids = input_ids).logits # [batch, max_len, voc_size]\npre_p = torch.softmax(logits, 2) # [batch, max_len, voc_size]\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Calculate adaptive thresholds using second-best predictions\n# Introduces hinge mechanism absent in LaTeX equations to dynamically adjust reliability thresholds based on model's confidence distribution\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nsecond_pre_p = torch.topk(pre_p, 2, -1).values[:, :, 1] # [batch, max_len]\npre_p = pre_p.gather(-1, label_ids.unsqueeze(-1)).squeeze(-1) # [batch, max_len]\nmasks = masks * (pre_p < second_pre_p * hinge_scale)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Compute negative log-likelihood for valid positions\n# Corresponds to the core reliability loss calculation from Eq. \\ref{eq_editing_loss_rel} with added masking based on hinge condition\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\npre_p = torch.masked_select(pre_p, masks.to(bool))\nloss = - torch.log(pre_p + eps).sum() # [batch, max_len] \n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Normalize loss by number of valid positions and return the loss\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nif average:\n sm = masks.sum() \n if sm != 0:\n loss = loss / sm\nreturn loss\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - Dynamic threshold masking mechanism based on second-best predictions. The LaTeX description does not mention that loss calculation is restricted to positions where the target token probability falls below a threshold defined as (second-best probability \u00d7 hinge_scale).\n - The loss averaging process accounts only for the positions identified in the above condition, rather than all positions. In the reference implementation, after determining which positions contribute to the loss based on the reliability threshold, the total loss is computed as the sum of the negative log-likelihoods for those specific positions. This sum is then divided by the number of such positions to obtain the average loss, affecting how the loss is normalized.\n - The LaTeX description does not specify that the loss is computed only for positions where the probability of the target token is less than the probability of the second-most likely token multiplied by a scaling factor. In the reference implementation, the workflow involves an additional step: it first evaluates the model's predicted probability for the target token and compares it to the probability of the second-most likely token adjusted by a scaling factor. The loss is then calculated only for those positions where the target token's probability falls below this threshold. This selective computation enforces a reliability condition by penalizing the model specifically when its confidence in the correct token is insufficient relative to the next best alternative, a nuance not captured in the LaTeX formulation.\n\n - Mismatched Details:\n - None\n", "Missing_details": [ "\n- Dynamic threshold masking mechanism based on second-best predictions. The LaTeX description does not mention that loss calculation is restricted to positions where the target token probability falls below a threshold defined as (second-best probability \u00d7 hinge_scale).\n", "\n- The loss averaging process accounts only for the positions identified in the above condition, rather than all positions. In the reference implementation, after determining which positions contribute to the loss based on the reliability threshold, the total loss is computed as the sum of the negative log-likelihoods for those specific positions. This sum is then divided by the number of such positions to obtain the average loss, affecting how the loss is normalized.\n", "\n- The LaTeX description does not specify that the loss is computed only for positions where the probability of the target token is less than the probability of the second-most likely token multiplied by a scaling factor. In the reference implementation, the workflow involves an additional step: it first evaluates the model's predicted probability for the target token and compares it to the probability of the second-most likely token adjusted by a scaling factor. The loss is then calculated only for those positions where the target token's probability falls below this threshold. This selective computation enforces a reliability condition by penalizing the model specifically when its confidence in the correct token is insufficient relative to the next best alternative, a nuance not captured in the LaTeX formulation.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - model (LLamaForCausalLM): Language model being edited.\n - input_ids (torch.Tensor, shape=[batch_size, seq_len]): Tokenized input sequences.\n - label_ids (torch.Tensor, shape=[batch_size, seq_len]): Target token IDs.\n - masks (torch.Tensor, shape=[batch_size, seq_len]): Mask indicating valid positions for loss calculation.\n - average (bool): Flag to enable loss averaging over valid positions.\n - eps (float): Numerical stability constant.\n - hinge_scale (float): Multiplier for second-best probability threshold.\n", "Arguments_list": [ { "name": "model", "string": "- model (LLamaForCausalLM): Language model being edited.", "dependency": null }, { "name": "input_ids", "string": "- input_ids (torch.Tensor, shape=[batch_size, seq_len]): Tokenized input sequences.", "dependency": null }, { "name": "label_ids", "string": "- label_ids (torch.Tensor, shape=[batch_size, seq_len]): Target token IDs.", "dependency": null }, { "name": "masks", "string": "- masks (torch.Tensor, shape=[batch_size, seq_len]): Mask indicating valid positions for loss calculation.", "dependency": null }, { "name": "average", "string": "- average (bool): Flag to enable loss averaging over valid positions.", "dependency": null }, { "name": "eps", "string": "- eps (float): Numerical stability constant.", "dependency": null }, { "name": "hinge_scale", "string": "- hinge_scale (float): Multiplier for second-best probability threshold.", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra File Dependencies: \n - None\n\n Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.softmax\n - torch.topk\n - torch.masked_select\n - torch.log\n", "list": [ "torch.softmax", "torch.topk", "torch.masked_select", "torch.log" ] }, "Return": { "Return_String": "\nOutput Variables:\n - loss (torch.Tensor): Computed hinge loss value, shape=[1]\n", "Return_list": [ { "name": "loss", "string": "- loss (torch.Tensor): Computed hinge loss value, shape=[1]", "dependency": null } ] }, "ori_python_file": "from editors.editor import BaseEditor, EditorConfig\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nfrom typing import Dict, List, Tuple \nfrom dataclasses import dataclass, asdict\nimport numpy as np\nfrom copy import deepcopy\nimport torch, os, yaml\nfrom torch.utils.tensorboard import SummaryWriter \nfrom torch.optim import Adam\nfrom .models import KnowledgeRepModel, PromptTransformer\nfrom utils.data import ParallelDataset\nfrom datetime import datetime\nfrom tqdm import tqdm\nimport random\nos.environ['PYTHONHASHSEED'] = str(42)\nos.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\nnp.random.seed(42)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\ntorch.use_deterministic_algorithms(True)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nrandom.seed(42)\ntorch.cuda.synchronize()\n\n@dataclass\nclass RECIPEConfig(EditorConfig):\n @dataclass\n class TrainingConfig():\n krm_lr: float\n pt_lr: float\n relia_lambda: float\n gen_lambda: float\n loc_lambda: float\n contra_lambda: float\n query_knowledge_t: float\n query_prototype_t: float\n constra_hinge_scale: float # w/hinge >= 1, w/o hinge== 999999 \n edit_hinge_scale: float # w/hinge >= 1, w/o hinge== 999999 \n # set in train_init\n batch_size:int = None\n sample_count:int = None\n random_seed:int = None\n eps:float = 1e-8\n \n prompt_token_n: int\n edit_model_name: str\n knowledge_rep_dim: int\n knowl_rep_prot_token_n: int\n model_hidden_size: int\n begin_layer_path:str\n lm_head_path:str\n training: TrainingConfig\n\n @classmethod\n def from_yaml(self, fpath):\n with open(fpath, \"r\") as f:\n data = yaml.safe_load(f)\n data['training'] = self.TrainingConfig(**data['training'])\n return self(**data)\n @classmethod\n def from_json(self, fpath):\n raise\n \nclass RECIPE(BaseEditor):\n def __init__(self, \n model: AutoModelForCausalLM,\n tokenizer: AutoTokenizer,\n config: RECIPEConfig,\n device = 'cuda',\n krm_base_path = 'models/roberta-base',\n retr_top_k = 1,\n retr_min_sim = -999,\n auto_retrieve = True, \n ckpt_path = None \n ):\n super().__init__(model, tokenizer, device)\n self.cfg = config\n # initialize model & parameters\n self.knowl_rep_model = KnowledgeRepModel(config.knowledge_rep_dim, \n config.knowl_rep_prot_token_n, self.device, krm_base_path)\n self.prompt_transformer = PromptTransformer(config.knowledge_rep_dim, \n config.model_hidden_size, config.prompt_token_n, self.device)\n # initialize hooks\n self.begin_layer = find_module(self.model, self.cfg.begin_layer_path)\n self.lm_head = find_module(self.model, self.cfg.lm_head_path)\n self.model.forward = self.register_model_forward_hook(self.model, \n self.model.forward, self.begin_layer, self.lm_head)\n self.begin_layer_hook = self.register_editing_hook(self.begin_layer, self.lm_head)\n # initialize editing prompts\n self.restore_to_original_model()\n self.auto_retrieve = auto_retrieve \n self.retr_top_k = retr_top_k\n self.retr_min_sim = retr_min_sim\n self.set_train(False) \n if ckpt_path != None:\n self.load_ckpt(ckpt_path, load_opt = False)\n \n ############################################################################\n ############################# Initialize ###################################\n ############################################################################\n def register_editing_hook(self, begin_layer, lm_head_layer):\n def forward_pre_hook(module, args):\n # If do not has past_key_values, add editing prompts before reps.\n if not module.has_past_kv:\n args = args[0]\n args = torch.stack([\n torch.cat([p, inp[:-len(p) if len(p) != 0 else None]], 0)\n for inp, p in zip(args, self.adopted_prompts)], 0)\n return (args, )\n def forward_hook(module, args, output):\n if not module.has_past_kv:\n max_n = max([len(p) for p in self.adopted_prompts])\n output = torch.stack([\n ot[len(p):len(p)-max_n if len(p)-max_n != 0 else None]\n for ot, p in zip(output, self.adopted_prompts)], 0)\n return output\n begin_layer_hook = begin_layer.register_forward_pre_hook(forward_pre_hook)\n lm_head_layer_hook = lm_head_layer.register_forward_hook(forward_hook)\n return [begin_layer_hook, lm_head_layer_hook]\n\n def register_model_forward_hook(self, model, model_forward, begin_layer, lm_head):\n if hasattr(model, 'recipe_hooked'):\n return model_forward\n model.recipe_hooked = True\n def forward_recipe(**kargs):\n if 'past_key_values' in kargs and kargs['past_key_values'] != None:\n begin_layer.has_past_kv = True\n lm_head.has_past_kv = True\n else:\n begin_layer.has_past_kv = False\n lm_head.has_past_kv = False\n b, l = kargs['input_ids'].shape\n inp_sents = [self.tokenizer.decode(i, skip_special_tokens=True) \n for i in kargs['input_ids']]\n if self.auto_retrieve: \n retrieved_ids = self.retrieve_and_get_ids_sim(inp_sents)[0]\n # print(retrieved_ids)\n self.adopted_prompts = [self.prompts_base[i].reshape(\n len(i)*self.cfg.prompt_token_n, self.cfg.model_hidden_size) \n for i in retrieved_ids]\n if len(self.adopted_prompts) != b:\n print(len(self.adopted_prompts), b) \n raise ValueError\n pad = torch.ones([b, max([len(i) for i in self.adopted_prompts])], \n dtype = torch.long).to(self.device)\n if 'attention_mask' in kargs and kargs['attention_mask'] != None:\n kargs['attention_mask'] = torch.cat([kargs['attention_mask'], pad], 1)\n kargs['input_ids'] = torch.cat([kargs['input_ids'], pad * self.tokenizer.pad_token_id], 1)\n return model_forward(**kargs)\n return forward_recipe\n\n ############################################################################\n ############################# RECIPE Edit Related ############################\n ############################################################################\n def retrieve_and_get_ids_sim(self, input_queries:List[str]):\n query_reps = self.knowl_rep_model(input_queries, knowl_or_query = 'q') # [n, knowledge_rep_dim] \n sim_matrx = (query_reps @ self.knowledge_base.T) / self.cfg.knowledge_rep_dim**0.5 # cross_cos_sim(query_reps, self.knowledge_base) # [n, edit_n]\n sim_with_prototype = sim_matrx[:, :1] \n sorted_sim, order = torch.sort(sim_matrx, 1, True) # [n, edit_n]\n mask = sorted_sim[:, :self.retr_top_k] > self.retr_min_sim\n mask &= sorted_sim[:, :self.retr_top_k] > sim_with_prototype\n retrieved_ids = torch.masked_select(order[:, :self.retr_top_k], mask)\n retrieved_ids = torch.split(retrieved_ids, mask.sum(1).tolist()) # retrieved indexes\n return retrieved_ids, sorted_sim, order # [retr_ids_1, retr_ids_2, ..., retr_ids_n]\n\n ############################################################################\n ############################# Editor Basic Functions #######################\n ############################################################################\n def name_of_editor_and_model(self)->Tuple[str, str]:\n return 'recipe', self.cfg.edit_model_name\n\n def if_can_batch_edit(self):\n return True\n \n def restore_to_original_model(self):\n self.knowledge_base_nl = [''] # [edit_n, knowledge_rep_dim]\n self.knowledge_base = self.knowl_rep_model.get_knowl_rep_prot() # [edit_n, knowledge_rep_dim]\n self.prompts_base = torch.zeros([1, self.cfg.prompt_token_n, self.cfg.model_hidden_size], \n device = self.device) # [edit_n, prompt_token_n, model_hidden_size]\n self.adopted_prompts = [] # List[torch.Tensor], len(List) = btach_size, Tensor.size = [retr_n * prompt_token_n, model_hidden_size]\n\n def edit_batch(self, requests: List[Dict]):\n '''requests = [\n {'prompt':str, 'subject':str, 'target_new':str}\n {'prompt':str, 'subject':str, 'target_new':str}, ...\n ]\n '''\n rs = []\n for r in requests:\n rs.append(r['prompt'] + r['target_new'])\n self.knowledge_base_nl.extend(rs)\n new_reps = self.knowl_rep_model(rs, knowl_or_query = 'k')\n new_prompts = self.prompt_transformer(new_reps)\n self.knowledge_base = torch.cat([self.knowledge_base, new_reps], 0)\n self.prompts_base = torch.cat([self.prompts_base, new_prompts], 0)\n\n return self.knowledge_base_nl, self.knowledge_base, self.prompts_base\n\n def edit_one_piece(self, request: Dict) -> None:\n \"\"\"\n request = {'prompt':str, 'subject':str, 'target_new':str}\n \"\"\"\n requests = [request]\n for r in range(len(requests)):\n requests[r]['prompt'] = requests[r]['prompt'].strip() + \" \"\n requests[r]['target_new'] = requests[r]['target_new'].strip()\n knowledge_base_nl, knowledge_base, prompts_base= self.edit_batch([request])\n\n ############################################################################\n ############################# RECIPE Training ################################\n ############################################################################\n def set_train(self, if_train = False):\n self.model.train(False)\n self.model.requires_grad_(False)\n self.knowl_rep_model.train(if_train)\n self.knowl_rep_model.requires_grad_(if_train)\n self.prompt_transformer.train(if_train)\n self.prompt_transformer.requires_grad_(if_train)\n self.auto_retrieve = not if_train\n\n def train_init(self, sample_count, get_data_by_ids, batch_size, \n records_dir:str = 'train_records', train_name_prefix = None, \n train_name:str = None, load_ckpt_path:str = None, \n save_ckpt_per_i = 3000, log_per_i = 10, random_seed = None): \n '''\n Used to initialize `ParallelDataset`:\n sample_count: count of used data in dataset.\n get_data_by_ids: function getting data by ids, assume data structure: (\n batch_knowledge: List[str], len = batch_size\n contra_q: List[str], len = batch_size * 3\n contra_sim_m: torch.Tensor[batch_size, batch_size * 3]\n batch_relia_xym: (input_ids, label_ids, masks), \n batch_gen_xym: {\n loss_name_1: (input_ids, label_ids, masks),\n loss_name_2: (input_ids, label_ids, masks), ...\n },\n batch_loc_xym: {\n loss_name_1: (input_ids, masks)\n loss_name_2: (input_ids, masks), ...\n } \n ), where `input_ids`, `label_ids`, and `label_ids` are with shape \n [batch_size, length]\n '''\n # initialize data generator\n self.rng = np.random.default_rng(random_seed)\n self.data_generator = ParallelDataset(sample_count, get_data_by_ids, \n batch_size, True, 16, False, random_seed)\n # initialize checkpoint/log directory and writer\n t = datetime.now().strftime('%Y.%m.%d-%H.%M.%S')\n train_name = (train_name_prefix + '-' if train_name_prefix else \"\") + \\\n (train_name if train_name else t)\n records_dir = os.path.join(records_dir, *self.name_of_editor_and_model(), train_name)\n self.save_ckpt_dir = os.path.join(records_dir, 'checkpoints')\n if not os.path.exists(self.save_ckpt_dir):\n os.makedirs(self.save_ckpt_dir)\n logs_path = os.path.join(records_dir, 'logs')\n if not os.path.exists(logs_path):\n os.makedirs(logs_path)\n with open(os.path.join(records_dir, 'config.yaml'), 'w') as f:\n self.cfg.training.batch_size = batch_size\n self.cfg.training.sample_count = sample_count\n self.cfg.training.random_seed = random_seed\n yaml.dump(asdict(self.cfg), f)\n self.log_writer = SummaryWriter(logs_path)\n self.save_ckpt_per_i = save_ckpt_per_i\n self.log_per_i = log_per_i\n # initialize optimizer and load checkpoints\n self.opt = Adam([\n {'params': self.knowl_rep_model.parameters(), 'lr': self.cfg.training.krm_lr},\n {'params': self.prompt_transformer.parameters(), 'lr': self.cfg.training.krm_lr}])\n if load_ckpt_path and os.path.isfile(load_ckpt_path):\n self.ema_loss = self.load_ckpt(load_ckpt_path, True) \n else:\n self.train_i, self.train_epoch = 1, 1\n self.ema_loss = 1\n\n def train(self, epochs):\n if self.log_writer == None:\n raise \"Call `self.train_init()` to initialize training first!\"\n print('Checkpoints dir: ', self.save_ckpt_dir)\n start_epoch = self.train_epoch\n self.set_train(True) \n for self.train_epoch in range(start_epoch, epochs + 1): \n progress_bar = tqdm(total = self.data_generator.sample_count, \n position = 0, leave = True, desc = \"Epoch %d\"%self.train_epoch, dynamic_ncols = True)\n for contra_data, edit_data in self.data_generator:\n # train after edit\n log_dict = self.__train_a_batch__(*contra_data, *edit_data)\n # log\n log_dict['Epoch'] = self.train_epoch\n if self.train_i % self.log_per_i == 0:\n self.write_logs(self.train_i, log_dict)\n # if self.train_i % self.save_ckpt_per_i == 0:\n # self.save_ckpt(self.train_i, self.train_epoch, log_dict['Loss'])\n self.train_i += 1 \n progress_bar.update(len(contra_data[0]))\n progress_bar.close() \n self.set_train(False)\n\n def compute_contrastive_losses(self, knowl_rep_model, contra_knowl, contra_q_rel, contra_q_gen, contra_q_loc, \n query_knowledge_t, query_prototype_t, constra_hinge_scale, rep_dim, eps=1e-8):\n bsz = len(contra_knowl)\n device = next(knowl_rep_model.parameters()).device\n rng = np.random.RandomState(42) # For reproducibility\n cc = rng.choice([0, 1], bsz)\n \n q1 = [[contra_q_rel, contra_q_gen][c][i] for i, c in enumerate(cc)]\n q2 = [[contra_q_rel, contra_q_gen][c][i] for i, c in enumerate(1-cc)]\n\n q1_reps = knowl_rep_model(q1, knowl_or_query='q') # [bsz, rep_dim]\n q2_reps = knowl_rep_model(q2, knowl_or_query='q') # [bsz, rep_dim]\n knowledge_reps = knowl_rep_model(contra_knowl, knowl_or_query='k') # [bsz, rep_dim]\n knowl_rep_prot = knowl_rep_model.get_knowl_rep_prot() # Prototype representation\n\n knowl_reps_with_proto = torch.cat([knowledge_reps, knowl_rep_prot])\n scale_factor = 1 / rep_dim**0.5 # Scaling factor for dot product\n\n sim_q1 = (q1_reps @ knowl_reps_with_proto.T) * scale_factor # [bsz, bsz+1]\n sim_q1 = torch.softmax(sim_q1 * query_knowledge_t, 1)\n loss_contra_q1 = - torch.log(torch.diag(sim_q1) + eps).mean(0)\n\n sim_q2 = (q2_reps @ knowledge_reps.T) * scale_factor # [bsz, bsz]\n sim_q2 = sim_q2 * (1 - torch.eye(bsz, device=device)) # Zero out self-similarity\n sim_q2 = sim_q2 + torch.diag((q2_reps @ knowl_rep_prot.T)[:, 0] * scale_factor)\n sim_q2 = torch.softmax(sim_q2 * query_prototype_t, 1)\n second_sim_q2 = torch.topk(sim_q2, 2, 1).values[:, 1]\n sim_q2_diag = torch.diag(sim_q2)\n sim_q2_filtered = torch.masked_select(sim_q2_diag, sim_q2_diag < second_sim_q2 * constra_hinge_scale)\n if len(sim_q2_filtered) == 0:\n loss_contra_q2 = 0\n else:\n loss_contra_q2 = - torch.log(sim_q2_filtered + eps).mean(0)\n\n losses_contra_q3 = {}\n loss_contra_q3 = 0\n for k, cql in contra_q_loc.items():\n q3_reps = knowl_rep_model(cql, knowl_or_query='q') # [bsz, rep_dim]\n sim_q3 = (q3_reps @ knowl_reps_with_proto.T) * scale_factor # [bsz, bsz+1]\n sim_q3 = torch.softmax(sim_q3 * query_prototype_t, 1)\n second_sim_q3 = torch.topk(sim_q3, 2, 1).values[:, 1]\n sim_q3_proto = sim_q3[:, -1]\n sim_q3_filtered = torch.masked_select(sim_q3_proto, sim_q3_proto < second_sim_q3 * constra_hinge_scale)\n if len(sim_q3_filtered) == 0:\n l = 0\n else:\n l = - torch.log(sim_q3_filtered + eps).mean(0)\n losses_contra_q3[k] = l\n loss_contra_q3 += l\n\n loss_contra = loss_contra_q1 + loss_contra_q2 + loss_contra_q3\n return loss_contra_q1, loss_contra_q2, loss_contra_q3, losses_contra_q3, loss_contra\n\n\n def __train_a_batch__(self, contra_knowl, contra_q_rel, contra_q_gen, contra_q_loc,\n batch_relia_xym, batch_gen_xym, batch_loc_xym):\n # prediction before edit for locality loss\n with torch.no_grad():\n for loss_name, sp in batch_loc_xym.items():\n input_ids, _, masks = sp\n self.adopted_prompts = [torch.zeros([0, self.cfg.model_hidden_size], device = self.device)] * len(input_ids)\n pre_logits = self.model(input_ids = input_ids).logits\n batch_loc_xym[loss_name] = ((input_ids, masks), pre_logits)\n loss = 0 \n bsz = len(contra_knowl)\n eps = self.cfg.training.eps\n ehs = self.cfg.training.edit_hinge_scale\n \n # Compute contrastive losses using the refactored function\n loss_contra_q1, loss_contra_q2, loss_contra_q3, losses_contra_q3, loss_contra = self.compute_contrastive_losses(\n self.knowl_rep_model, \n contra_knowl, \n contra_q_rel, \n contra_q_gen, \n contra_q_loc,\n self.cfg.training.query_knowledge_t,\n self.cfg.training.query_prototype_t,\n self.cfg.training.constra_hinge_scale,\n self.cfg.knowledge_rep_dim,\n eps\n )\n loss += loss_contra * self.cfg.training.contra_lambda\n # edit loss\n knowledge_reps = self.knowl_rep_model(contra_knowl, knowl_or_query = 'k')\n self.adopted_prompts = [i for i in self.prompt_transformer(knowledge_reps)]\n # compute reliability loss\n (input_ids, label_ids, masks) = batch_relia_xym\n relia_loss = hinge_label_loss(self.model, input_ids, label_ids, masks, True, eps, ehs)\n loss += relia_loss * self.cfg.training.relia_lambda\n # compute generality loss\n gen_losses = {}\n for loss_name, sp in batch_gen_xym.items():\n input_ids, label_ids, masks = sp\n gen_loss = hinge_label_loss(self.model, input_ids, label_ids, masks, True, eps, ehs)\n gen_losses[loss_name] = gen_loss\n loss += gen_loss * self.cfg.training.gen_lambda\n # compute locality loss\n loc_losses = {}\n for loss_name, sp in batch_loc_xym.items():\n (input_ids, masks), pre_logits = sp\n post_logits = self.model(input_ids = input_ids).logits\n loc_loss = logit_KL_loss(pre_logits, post_logits, masks)\n loc_losses[loss_name] = loc_loss\n loss += loc_loss * self.cfg.training.loc_lambda\n # update\n loss.backward()\n self.opt.step()\n self.opt.zero_grad()\n self.ema_loss = self.ema_loss + (loss.detach() - self.ema_loss) / self.log_per_i\n log_dict = {\n 'Loss': loss,\n 'EMA Loss': self.ema_loss, \n 'Contrastive loss': loss_contra,\n 'Contrastive loss q2k': loss_contra_q1,\n 'Contrastive loss q2prot': loss_contra_q2 + loss_contra_q3,\n 'Contrastive loss q2prot-rg': loss_contra_q2,\n 'Contrastive loss q2prot-loc': losses_contra_q3,\n 'Reliability loss': relia_loss,\n 'Generality loss': gen_losses,\n 'Locality loss': loc_losses\n }\n return log_dict\n\n def write_logs(self, i, logs:dict):\n for log_name, log in logs.items():\n if type(log) == dict:\n logs1 = {}\n for n, l in log.items():\n logs1[log_name + '-' + n] = l\n self.write_logs(i, logs1)\n else: \n self.log_writer.add_scalar(log_name, log, i)\n\n def save_ckpt(self, i:int, epoch:int, loss:float):\n ckpt_name = 'epoch-%d-i-%d-ema_loss-%.4f'%(epoch, i, self.ema_loss)\n ckpt_path = os.path.join(self.save_ckpt_dir, ckpt_name)\n ckpt = {\n 'i': i,\n 'epoch': epoch,\n 'loss': loss,\n 'knowl_rep_model': self.knowl_rep_model.state_dict(),\n 'prompt_transformer': self.prompt_transformer.state_dict(),\n 'opt': self.opt.state_dict()\n }\n torch.save(ckpt, ckpt_path)\n\n def load_ckpt(self, ckpt_path, restrict = True, load_opt = True):\n ckpt = torch.load(ckpt_path, 'cpu')\n self.train_i = ckpt['i']\n self.train_epoch = ckpt['epoch']\n self.knowl_rep_model.load_state_dict(ckpt['knowl_rep_model'], restrict)\n self.prompt_transformer.load_state_dict(ckpt['prompt_transformer'], restrict)\n if load_opt:\n self.opt.load_state_dict(ckpt['opt'])\n print('Load RECIPE checkpoints from', ckpt_path)\n return ckpt['loss']\n\ndef hinge_label_loss(model, input_ids:torch.Tensor, label_ids:torch.Tensor, \n masks:torch.Tensor, average = True, eps = 1e-8, hinge_scale = 1.1):\n # input_ids/label_ids/masks: [batch, max_len]\n logits = model(input_ids = input_ids).logits # [batch, max_len, voc_size]\n pre_p = torch.softmax(logits, 2) # [batch, max_len, voc_size]\n second_pre_p = torch.topk(pre_p, 2, -1).values[:, :, 1] # [batch, max_len]\n pre_p = pre_p.gather(-1, label_ids.unsqueeze(-1)).squeeze(-1) # [batch, max_len]\n masks = masks * (pre_p < second_pre_p * hinge_scale)\n pre_p = torch.masked_select(pre_p, masks.to(bool))\n loss = - torch.log(pre_p + eps).sum() # [batch, max_len] \n if average:\n sm = masks.sum() \n if sm != 0:\n loss = loss / sm\n return loss\n\ndef label_loss(model, input_ids:torch.Tensor, label_ids:torch.Tensor, masks:torch.Tensor, average = True):\n # input_ids/label_ids/masks: [batch, max_len]\n logits = model(input_ids = input_ids).logits\n log_pre_p = torch.log_softmax(logits, 2) # [batch, max_len, voc_size]\n log_pre_p = log_pre_p.gather(-1, label_ids.unsqueeze(-1)).squeeze(-1) # [batch, max_len]\n loss = -(log_pre_p * masks).sum()\n if average:\n loss = loss / masks.sum() \n return loss\n\ndef logit_KL_loss(logits1:torch.Tensor, logits2:torch.Tensor, masks:torch.Tensor, average = True):\n # logits1/logits2: [batch, max_len, voc_size], masks: [batch, max_len]\n log_p1 = torch.log_softmax(logits1, 2)\n log_p2 = torch.log_softmax(logits2, 2)\n p1 = torch.softmax(logits1, 2)\n kl_loss = (p1 * (log_p1 - log_p2)).sum(2) # [batch, max_len]\n loss = (kl_loss * masks).sum()\n if average:\n loss = loss / masks.sum() \n return loss\n\ndef find_module(module, module_path:str):\n for comp in module_path.split('.'):\n if hasattr(module, comp):\n module = getattr(module, comp)\n elif comp.isdigit():\n module = module[int(comp)]\n else:\n raise RuntimeError(f\"Couldn't find child module {comp}\")\n return module\n\ndef cross_cos_sim(a, b):\n # compute cos similarly: [n, d], [m, d] -> [n, m]\n a = torch.nn.functional.normalize(a, 2, 1)\n b = torch.nn.functional.normalize(b, 2, 1)\n return a @ b.T\n\ndef get_mask_matrix(v, max_n = None):\n max_n = max_n if max_n != None else torch.max(v)\n return torch.arange(1, max_n + 1).unsqueeze(0) <= v.unsqueeze(1)\n" }, { "task_id": 4, "indent": 1, "completion_path": "./editors/recipe/recipe.py", "script": "\npython train_recipe.py -mn 'llama-7b' -dn 'zsre' \n", "latex_code": "\n\\noindent\\textbf{Editing:} The editing loss aims to ensure that the generated continuous prompt guides the LLM to follow the properties of locality \\cite{ZJUEditSurvey2023}. \nBased on the pairs $(q_{e_i}, a_{e_i})$, the sample-wise losses corresponding to the property is defined as follows:\n\\begin{gather}\n \\mathcal{L}^{(i)}_{loc} = \\mathrm{KL}\\left(f_{llm}\\left(q_{l_i}\\right) || \\hat{f}_{llm}\\left(p_{k_i}\\oplus f_{emb}(q_{l_i})\\right)\\right)\n \\label{eq_editing_loss_loc}\n\\end{gather}\nwhere $p_{k_i}$ is the continuous prompt transformed through Eq. \\ref{equation:knowledge_representation} and Eq. \\ref{equation:prompt_embedding} using knowledge $k_i$ that is the concatenation of $q_{e_i}$ and $a_{e_i}$. \nThe $\\mathrm{KL}$ denotes the Kullback-Leibler divergence, \nwhich is chosen to better fit the LLM's original prediction distribution on the locality data.\n", "namespace": "editors.recipe.recipe.RECIPE.logit_KL_loss", "type": "function", "signature_position": [ 485, 485 ], "body_position": [ 486, 494 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Convert logits to probability distributions using softmax.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nlog_p1 = torch.log_softmax(logits1, 2)\nlog_p2 = torch.log_softmax(logits2, 2)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Calculates the KL divergence for each token.\n# This implements the core KL divergence formula: KL(P || Q) = sum(P * log(P/Q)) which expands to p1 * (log_p1 - log_p2). The .sum(2) then sums these values across the vocabulary dimension.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\np1 = torch.softmax(logits1, 2)\nkl_loss = (p1 * (log_p1 - log_p2)).sum(2) # [batch, max_len]\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Applies the mask and sums the KL divergence values.\n# The mask is used to only consider relevant tokens (e.g., excluding padding).\n# The result is the total KL divergence loss for the batch, before potential averaging.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nloss = (kl_loss * masks).sum()\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Averages the loss if 'average' is True.\n# This step normalizes the loss by the number of valid (masked) tokens.\n# Return the loss\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nif average:\n loss = loss / masks.sum()\n\nreturn loss\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The LaTeX does not explicitly mention applying a token-level mask for selective KL calculation. This code uses a 'masks' tensor to include/exclude specific tokens.\n - Averaging option not specified in LaTeX (added for batch normalization)\n \n - Mismatched Details:\n - None\n", "Missing_details": [ "\n- The LaTeX does not explicitly mention applying a token-level mask for selective KL calculation. This code uses a 'masks' tensor to include/exclude specific tokens.\n", "\n- Averaging option not specified in LaTeX (added for batch normalization)\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - logits1 (torch.Tensor, shape=[batch_size, seq_len, vocab_size]):\n Original model's unnormalized predictions for locality queries\n - logits2 (torch.Tensor, shape=[batch_size, seq_len, vocab_size]):\n Edited model's predictions with continuous prompts\n - masks (torch.Tensor, shape=[batch_size, seq_len]):\n Boolean mask indicating which tokens to include in loss calculation\n - average (bool):\n Whether to normalize loss by number of active mask positions\n", "Arguments_list": [ { "name": "logits1", "string": "\n- logits1 (torch.Tensor, shape=[batch_size, seq_len, vocab_size]):\n Original model's unnormalized predictions for locality queries\n", "dependency": null }, { "name": "logits2", "string": "\n- logits2 (torch.Tensor, shape=[batch_size, seq_len, vocab_size]):\n Edited model's predictions with continuous prompts\n", "dependency": null }, { "name": "masks", "string": "\n- masks (torch.Tensor, shape=[batch_size, seq_len]):\n Boolean mask indicating which tokens to include in loss calculation\n", "dependency": null }, { "name": "average", "string": "\n- average (bool):\n Whether to normalize loss by number of active mask positions\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra File Dependencies: \n None\n\n - Cross File Dependencies: \n None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.log_softmax\n - torch.softmax\n", "list": [ "torch.log_softmax", "torch.softmax" ] }, "Return": { "Return_String": "\nOutput Variables:\n - loss (torch.Tensor):\n KL divergence loss value (scalar) measuring distribution discrepancy\n", "Return_list": [ { "name": "loss", "string": "\n- loss (torch.Tensor):\n KL divergence loss value (scalar) measuring distribution discrepancy\n", "dependency": null } ] }, "ori_python_file": "from editors.editor import BaseEditor, EditorConfig\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nfrom typing import Dict, List, Tuple \nfrom dataclasses import dataclass, asdict\nimport numpy as np\nfrom copy import deepcopy\nimport torch, os, yaml\nfrom torch.utils.tensorboard import SummaryWriter \nfrom torch.optim import Adam\nfrom .models import KnowledgeRepModel, PromptTransformer\nfrom utils.data import ParallelDataset\nfrom datetime import datetime\nfrom tqdm import tqdm\nimport random\nos.environ['PYTHONHASHSEED'] = str(42)\nos.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\nnp.random.seed(42)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\ntorch.use_deterministic_algorithms(True)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nrandom.seed(42)\ntorch.cuda.synchronize()\n\n@dataclass\nclass RECIPEConfig(EditorConfig):\n @dataclass\n class TrainingConfig():\n krm_lr: float\n pt_lr: float\n relia_lambda: float\n gen_lambda: float\n loc_lambda: float\n contra_lambda: float\n query_knowledge_t: float\n query_prototype_t: float\n constra_hinge_scale: float # w/hinge >= 1, w/o hinge== 999999 \n edit_hinge_scale: float # w/hinge >= 1, w/o hinge== 999999 \n # set in train_init\n batch_size:int = None\n sample_count:int = None\n random_seed:int = None\n eps:float = 1e-8\n \n prompt_token_n: int\n edit_model_name: str\n knowledge_rep_dim: int\n knowl_rep_prot_token_n: int\n model_hidden_size: int\n begin_layer_path:str\n lm_head_path:str\n training: TrainingConfig\n\n @classmethod\n def from_yaml(self, fpath):\n with open(fpath, \"r\") as f:\n data = yaml.safe_load(f)\n data['training'] = self.TrainingConfig(**data['training'])\n return self(**data)\n @classmethod\n def from_json(self, fpath):\n raise\n \nclass RECIPE(BaseEditor):\n def __init__(self, \n model: AutoModelForCausalLM,\n tokenizer: AutoTokenizer,\n config: RECIPEConfig,\n device = 'cuda',\n krm_base_path = 'models/roberta-base',\n retr_top_k = 1,\n retr_min_sim = -999,\n auto_retrieve = True, \n ckpt_path = None \n ):\n super().__init__(model, tokenizer, device)\n self.cfg = config\n # initialize model & parameters\n self.knowl_rep_model = KnowledgeRepModel(config.knowledge_rep_dim, \n config.knowl_rep_prot_token_n, self.device, krm_base_path)\n self.prompt_transformer = PromptTransformer(config.knowledge_rep_dim, \n config.model_hidden_size, config.prompt_token_n, self.device)\n # initialize hooks\n self.begin_layer = find_module(self.model, self.cfg.begin_layer_path)\n self.lm_head = find_module(self.model, self.cfg.lm_head_path)\n self.model.forward = self.register_model_forward_hook(self.model, \n self.model.forward, self.begin_layer, self.lm_head)\n self.begin_layer_hook = self.register_editing_hook(self.begin_layer, self.lm_head)\n # initialize editing prompts\n self.restore_to_original_model()\n self.auto_retrieve = auto_retrieve \n self.retr_top_k = retr_top_k\n self.retr_min_sim = retr_min_sim\n self.set_train(False) \n if ckpt_path != None:\n self.load_ckpt(ckpt_path, load_opt = False)\n \n ############################################################################\n ############################# Initialize ###################################\n ############################################################################\n def register_editing_hook(self, begin_layer, lm_head_layer):\n def forward_pre_hook(module, args):\n # If do not has past_key_values, add editing prompts before reps.\n if not module.has_past_kv:\n args = args[0]\n args = torch.stack([\n torch.cat([p, inp[:-len(p) if len(p) != 0 else None]], 0)\n for inp, p in zip(args, self.adopted_prompts)], 0)\n return (args, )\n def forward_hook(module, args, output):\n if not module.has_past_kv:\n max_n = max([len(p) for p in self.adopted_prompts])\n output = torch.stack([\n ot[len(p):len(p)-max_n if len(p)-max_n != 0 else None]\n for ot, p in zip(output, self.adopted_prompts)], 0)\n return output\n begin_layer_hook = begin_layer.register_forward_pre_hook(forward_pre_hook)\n lm_head_layer_hook = lm_head_layer.register_forward_hook(forward_hook)\n return [begin_layer_hook, lm_head_layer_hook]\n\n def register_model_forward_hook(self, model, model_forward, begin_layer, lm_head):\n if hasattr(model, 'recipe_hooked'):\n return model_forward\n model.recipe_hooked = True\n def forward_recipe(**kargs):\n if 'past_key_values' in kargs and kargs['past_key_values'] != None:\n begin_layer.has_past_kv = True\n lm_head.has_past_kv = True\n else:\n begin_layer.has_past_kv = False\n lm_head.has_past_kv = False\n b, l = kargs['input_ids'].shape\n inp_sents = [self.tokenizer.decode(i, skip_special_tokens=True) \n for i in kargs['input_ids']]\n if self.auto_retrieve: \n retrieved_ids = self.retrieve_and_get_ids_sim(inp_sents)[0]\n # print(retrieved_ids)\n self.adopted_prompts = [self.prompts_base[i].reshape(\n len(i)*self.cfg.prompt_token_n, self.cfg.model_hidden_size) \n for i in retrieved_ids]\n if len(self.adopted_prompts) != b:\n print(len(self.adopted_prompts), b) \n raise ValueError\n pad = torch.ones([b, max([len(i) for i in self.adopted_prompts])], \n dtype = torch.long).to(self.device)\n if 'attention_mask' in kargs and kargs['attention_mask'] != None:\n kargs['attention_mask'] = torch.cat([kargs['attention_mask'], pad], 1)\n kargs['input_ids'] = torch.cat([kargs['input_ids'], pad * self.tokenizer.pad_token_id], 1)\n return model_forward(**kargs)\n return forward_recipe\n\n ############################################################################\n ############################# RECIPE Edit Related ############################\n ############################################################################\n def retrieve_and_get_ids_sim(self, input_queries:List[str]):\n query_reps = self.knowl_rep_model(input_queries, knowl_or_query = 'q') # [n, knowledge_rep_dim] \n sim_matrx = (query_reps @ self.knowledge_base.T) / self.cfg.knowledge_rep_dim**0.5 # cross_cos_sim(query_reps, self.knowledge_base) # [n, edit_n]\n sim_with_prototype = sim_matrx[:, :1] \n sorted_sim, order = torch.sort(sim_matrx, 1, True) # [n, edit_n]\n mask = sorted_sim[:, :self.retr_top_k] > self.retr_min_sim\n mask &= sorted_sim[:, :self.retr_top_k] > sim_with_prototype\n retrieved_ids = torch.masked_select(order[:, :self.retr_top_k], mask)\n retrieved_ids = torch.split(retrieved_ids, mask.sum(1).tolist()) # retrieved indexes\n return retrieved_ids, sorted_sim, order # [retr_ids_1, retr_ids_2, ..., retr_ids_n]\n\n ############################################################################\n ############################# Editor Basic Functions #######################\n ############################################################################\n def name_of_editor_and_model(self)->Tuple[str, str]:\n return 'recipe', self.cfg.edit_model_name\n\n def if_can_batch_edit(self):\n return True\n \n def restore_to_original_model(self):\n self.knowledge_base_nl = [''] # [edit_n, knowledge_rep_dim]\n self.knowledge_base = self.knowl_rep_model.get_knowl_rep_prot() # [edit_n, knowledge_rep_dim]\n self.prompts_base = torch.zeros([1, self.cfg.prompt_token_n, self.cfg.model_hidden_size], \n device = self.device) # [edit_n, prompt_token_n, model_hidden_size]\n self.adopted_prompts = [] # List[torch.Tensor], len(List) = btach_size, Tensor.size = [retr_n * prompt_token_n, model_hidden_size]\n\n def edit_batch(self, requests: List[Dict]):\n '''requests = [\n {'prompt':str, 'subject':str, 'target_new':str}\n {'prompt':str, 'subject':str, 'target_new':str}, ...\n ]\n '''\n rs = []\n for r in requests:\n rs.append(r['prompt'] + r['target_new'])\n self.knowledge_base_nl.extend(rs)\n new_reps = self.knowl_rep_model(rs, knowl_or_query = 'k')\n new_prompts = self.prompt_transformer(new_reps)\n self.knowledge_base = torch.cat([self.knowledge_base, new_reps], 0)\n self.prompts_base = torch.cat([self.prompts_base, new_prompts], 0)\n\n return self.knowledge_base_nl, self.knowledge_base, self.prompts_base\n\n def edit_one_piece(self, request: Dict) -> None:\n \"\"\"\n request = {'prompt':str, 'subject':str, 'target_new':str}\n \"\"\"\n requests = [request]\n for r in range(len(requests)):\n requests[r]['prompt'] = requests[r]['prompt'].strip() + \" \"\n requests[r]['target_new'] = requests[r]['target_new'].strip()\n knowledge_base_nl, knowledge_base, prompts_base= self.edit_batch([request])\n\n ############################################################################\n ############################# RECIPE Training ################################\n ############################################################################\n def set_train(self, if_train = False):\n self.model.train(False)\n self.model.requires_grad_(False)\n self.knowl_rep_model.train(if_train)\n self.knowl_rep_model.requires_grad_(if_train)\n self.prompt_transformer.train(if_train)\n self.prompt_transformer.requires_grad_(if_train)\n self.auto_retrieve = not if_train\n\n def train_init(self, sample_count, get_data_by_ids, batch_size, \n records_dir:str = 'train_records', train_name_prefix = None, \n train_name:str = None, load_ckpt_path:str = None, \n save_ckpt_per_i = 3000, log_per_i = 10, random_seed = None): \n '''\n Used to initialize `ParallelDataset`:\n sample_count: count of used data in dataset.\n get_data_by_ids: function getting data by ids, assume data structure: (\n batch_knowledge: List[str], len = batch_size\n contra_q: List[str], len = batch_size * 3\n contra_sim_m: torch.Tensor[batch_size, batch_size * 3]\n batch_relia_xym: (input_ids, label_ids, masks), \n batch_gen_xym: {\n loss_name_1: (input_ids, label_ids, masks),\n loss_name_2: (input_ids, label_ids, masks), ...\n },\n batch_loc_xym: {\n loss_name_1: (input_ids, masks)\n loss_name_2: (input_ids, masks), ...\n } \n ), where `input_ids`, `label_ids`, and `label_ids` are with shape \n [batch_size, length]\n '''\n # initialize data generator\n self.rng = np.random.default_rng(random_seed)\n self.data_generator = ParallelDataset(sample_count, get_data_by_ids, \n batch_size, True, 16, False, random_seed)\n # initialize checkpoint/log directory and writer\n t = datetime.now().strftime('%Y.%m.%d-%H.%M.%S')\n train_name = (train_name_prefix + '-' if train_name_prefix else \"\") + \\\n (train_name if train_name else t)\n records_dir = os.path.join(records_dir, *self.name_of_editor_and_model(), train_name)\n self.save_ckpt_dir = os.path.join(records_dir, 'checkpoints')\n if not os.path.exists(self.save_ckpt_dir):\n os.makedirs(self.save_ckpt_dir)\n logs_path = os.path.join(records_dir, 'logs')\n if not os.path.exists(logs_path):\n os.makedirs(logs_path)\n with open(os.path.join(records_dir, 'config.yaml'), 'w') as f:\n self.cfg.training.batch_size = batch_size\n self.cfg.training.sample_count = sample_count\n self.cfg.training.random_seed = random_seed\n yaml.dump(asdict(self.cfg), f)\n self.log_writer = SummaryWriter(logs_path)\n self.save_ckpt_per_i = save_ckpt_per_i\n self.log_per_i = log_per_i\n # initialize optimizer and load checkpoints\n self.opt = Adam([\n {'params': self.knowl_rep_model.parameters(), 'lr': self.cfg.training.krm_lr},\n {'params': self.prompt_transformer.parameters(), 'lr': self.cfg.training.krm_lr}])\n if load_ckpt_path and os.path.isfile(load_ckpt_path):\n self.ema_loss = self.load_ckpt(load_ckpt_path, True) \n else:\n self.train_i, self.train_epoch = 1, 1\n self.ema_loss = 1\n\n def train(self, epochs):\n if self.log_writer == None:\n raise \"Call `self.train_init()` to initialize training first!\"\n print('Checkpoints dir: ', self.save_ckpt_dir)\n start_epoch = self.train_epoch\n self.set_train(True) \n for self.train_epoch in range(start_epoch, epochs + 1): \n progress_bar = tqdm(total = self.data_generator.sample_count, \n position = 0, leave = True, desc = \"Epoch %d\"%self.train_epoch, dynamic_ncols = True)\n for contra_data, edit_data in self.data_generator:\n # train after edit\n log_dict = self.__train_a_batch__(*contra_data, *edit_data)\n # log\n log_dict['Epoch'] = self.train_epoch\n if self.train_i % self.log_per_i == 0:\n self.write_logs(self.train_i, log_dict)\n # if self.train_i % self.save_ckpt_per_i == 0:\n # self.save_ckpt(self.train_i, self.train_epoch, log_dict['Loss'])\n self.train_i += 1 \n progress_bar.update(len(contra_data[0]))\n progress_bar.close() \n self.set_train(False)\n\n def compute_contrastive_losses(self, knowl_rep_model, contra_knowl, contra_q_rel, contra_q_gen, contra_q_loc, \n query_knowledge_t, query_prototype_t, constra_hinge_scale, rep_dim, eps=1e-8):\n bsz = len(contra_knowl)\n device = next(knowl_rep_model.parameters()).device\n rng = np.random.RandomState(42) # For reproducibility\n cc = rng.choice([0, 1], bsz)\n \n q1 = [[contra_q_rel, contra_q_gen][c][i] for i, c in enumerate(cc)]\n q2 = [[contra_q_rel, contra_q_gen][c][i] for i, c in enumerate(1-cc)]\n\n q1_reps = knowl_rep_model(q1, knowl_or_query='q') # [bsz, rep_dim]\n q2_reps = knowl_rep_model(q2, knowl_or_query='q') # [bsz, rep_dim]\n knowledge_reps = knowl_rep_model(contra_knowl, knowl_or_query='k') # [bsz, rep_dim]\n knowl_rep_prot = knowl_rep_model.get_knowl_rep_prot() # Prototype representation\n\n knowl_reps_with_proto = torch.cat([knowledge_reps, knowl_rep_prot])\n scale_factor = 1 / rep_dim**0.5 # Scaling factor for dot product\n\n sim_q1 = (q1_reps @ knowl_reps_with_proto.T) * scale_factor # [bsz, bsz+1]\n sim_q1 = torch.softmax(sim_q1 * query_knowledge_t, 1)\n loss_contra_q1 = - torch.log(torch.diag(sim_q1) + eps).mean(0)\n\n sim_q2 = (q2_reps @ knowledge_reps.T) * scale_factor # [bsz, bsz]\n sim_q2 = sim_q2 * (1 - torch.eye(bsz, device=device)) # Zero out self-similarity\n sim_q2 = sim_q2 + torch.diag((q2_reps @ knowl_rep_prot.T)[:, 0] * scale_factor)\n sim_q2 = torch.softmax(sim_q2 * query_prototype_t, 1)\n second_sim_q2 = torch.topk(sim_q2, 2, 1).values[:, 1]\n sim_q2_diag = torch.diag(sim_q2)\n sim_q2_filtered = torch.masked_select(sim_q2_diag, sim_q2_diag < second_sim_q2 * constra_hinge_scale)\n if len(sim_q2_filtered) == 0:\n loss_contra_q2 = 0\n else:\n loss_contra_q2 = - torch.log(sim_q2_filtered + eps).mean(0)\n\n losses_contra_q3 = {}\n loss_contra_q3 = 0\n for k, cql in contra_q_loc.items():\n q3_reps = knowl_rep_model(cql, knowl_or_query='q') # [bsz, rep_dim]\n sim_q3 = (q3_reps @ knowl_reps_with_proto.T) * scale_factor # [bsz, bsz+1]\n sim_q3 = torch.softmax(sim_q3 * query_prototype_t, 1)\n second_sim_q3 = torch.topk(sim_q3, 2, 1).values[:, 1]\n sim_q3_proto = sim_q3[:, -1]\n sim_q3_filtered = torch.masked_select(sim_q3_proto, sim_q3_proto < second_sim_q3 * constra_hinge_scale)\n if len(sim_q3_filtered) == 0:\n l = 0\n else:\n l = - torch.log(sim_q3_filtered + eps).mean(0)\n losses_contra_q3[k] = l\n loss_contra_q3 += l\n\n loss_contra = loss_contra_q1 + loss_contra_q2 + loss_contra_q3\n return loss_contra_q1, loss_contra_q2, loss_contra_q3, losses_contra_q3, loss_contra\n\n\n def __train_a_batch__(self, contra_knowl, contra_q_rel, contra_q_gen, contra_q_loc,\n batch_relia_xym, batch_gen_xym, batch_loc_xym):\n # prediction before edit for locality loss\n with torch.no_grad():\n for loss_name, sp in batch_loc_xym.items():\n input_ids, _, masks = sp\n self.adopted_prompts = [torch.zeros([0, self.cfg.model_hidden_size], device = self.device)] * len(input_ids)\n pre_logits = self.model(input_ids = input_ids).logits\n batch_loc_xym[loss_name] = ((input_ids, masks), pre_logits)\n loss = 0 \n bsz = len(contra_knowl)\n eps = self.cfg.training.eps\n ehs = self.cfg.training.edit_hinge_scale\n \n # Compute contrastive losses using the refactored function\n loss_contra_q1, loss_contra_q2, loss_contra_q3, losses_contra_q3, loss_contra = self.compute_contrastive_losses(\n self.knowl_rep_model, \n contra_knowl, \n contra_q_rel, \n contra_q_gen, \n contra_q_loc,\n self.cfg.training.query_knowledge_t,\n self.cfg.training.query_prototype_t,\n self.cfg.training.constra_hinge_scale,\n self.cfg.knowledge_rep_dim,\n eps\n )\n loss += loss_contra * self.cfg.training.contra_lambda\n # edit loss\n knowledge_reps = self.knowl_rep_model(contra_knowl, knowl_or_query = 'k')\n self.adopted_prompts = [i for i in self.prompt_transformer(knowledge_reps)]\n # compute reliability loss\n (input_ids, label_ids, masks) = batch_relia_xym\n relia_loss = hinge_label_loss(self.model, input_ids, label_ids, masks, True, eps, ehs)\n loss += relia_loss * self.cfg.training.relia_lambda\n # compute generality loss\n gen_losses = {}\n for loss_name, sp in batch_gen_xym.items():\n input_ids, label_ids, masks = sp\n gen_loss = hinge_label_loss(self.model, input_ids, label_ids, masks, True, eps, ehs)\n gen_losses[loss_name] = gen_loss\n loss += gen_loss * self.cfg.training.gen_lambda\n # compute locality loss\n loc_losses = {}\n for loss_name, sp in batch_loc_xym.items():\n (input_ids, masks), pre_logits = sp\n post_logits = self.model(input_ids = input_ids).logits\n loc_loss = logit_KL_loss(pre_logits, post_logits, masks)\n loc_losses[loss_name] = loc_loss\n loss += loc_loss * self.cfg.training.loc_lambda\n # update\n loss.backward()\n self.opt.step()\n self.opt.zero_grad()\n self.ema_loss = self.ema_loss + (loss.detach() - self.ema_loss) / self.log_per_i\n log_dict = {\n 'Loss': loss,\n 'EMA Loss': self.ema_loss, \n 'Contrastive loss': loss_contra,\n 'Contrastive loss q2k': loss_contra_q1,\n 'Contrastive loss q2prot': loss_contra_q2 + loss_contra_q3,\n 'Contrastive loss q2prot-rg': loss_contra_q2,\n 'Contrastive loss q2prot-loc': losses_contra_q3,\n 'Reliability loss': relia_loss,\n 'Generality loss': gen_losses,\n 'Locality loss': loc_losses\n }\n return log_dict\n\n def write_logs(self, i, logs:dict):\n for log_name, log in logs.items():\n if type(log) == dict:\n logs1 = {}\n for n, l in log.items():\n logs1[log_name + '-' + n] = l\n self.write_logs(i, logs1)\n else: \n self.log_writer.add_scalar(log_name, log, i)\n\n def save_ckpt(self, i:int, epoch:int, loss:float):\n ckpt_name = 'epoch-%d-i-%d-ema_loss-%.4f'%(epoch, i, self.ema_loss)\n ckpt_path = os.path.join(self.save_ckpt_dir, ckpt_name)\n ckpt = {\n 'i': i,\n 'epoch': epoch,\n 'loss': loss,\n 'knowl_rep_model': self.knowl_rep_model.state_dict(),\n 'prompt_transformer': self.prompt_transformer.state_dict(),\n 'opt': self.opt.state_dict()\n }\n torch.save(ckpt, ckpt_path)\n\n def load_ckpt(self, ckpt_path, restrict = True, load_opt = True):\n ckpt = torch.load(ckpt_path, 'cpu')\n self.train_i = ckpt['i']\n self.train_epoch = ckpt['epoch']\n self.knowl_rep_model.load_state_dict(ckpt['knowl_rep_model'], restrict)\n self.prompt_transformer.load_state_dict(ckpt['prompt_transformer'], restrict)\n if load_opt:\n self.opt.load_state_dict(ckpt['opt'])\n print('Load RECIPE checkpoints from', ckpt_path)\n return ckpt['loss']\n\ndef hinge_label_loss(model, input_ids:torch.Tensor, label_ids:torch.Tensor, \n masks:torch.Tensor, average = True, eps = 1e-8, hinge_scale = 1.1):\n # input_ids/label_ids/masks: [batch, max_len]\n logits = model(input_ids = input_ids).logits # [batch, max_len, voc_size]\n pre_p = torch.softmax(logits, 2) # [batch, max_len, voc_size]\n second_pre_p = torch.topk(pre_p, 2, -1).values[:, :, 1] # [batch, max_len]\n pre_p = pre_p.gather(-1, label_ids.unsqueeze(-1)).squeeze(-1) # [batch, max_len]\n masks = masks * (pre_p < second_pre_p * hinge_scale)\n pre_p = torch.masked_select(pre_p, masks.to(bool))\n loss = - torch.log(pre_p + eps).sum() # [batch, max_len] \n if average:\n sm = masks.sum() \n if sm != 0:\n loss = loss / sm\n return loss\n\ndef label_loss(model, input_ids:torch.Tensor, label_ids:torch.Tensor, masks:torch.Tensor, average = True):\n # input_ids/label_ids/masks: [batch, max_len]\n logits = model(input_ids = input_ids).logits\n log_pre_p = torch.log_softmax(logits, 2) # [batch, max_len, voc_size]\n log_pre_p = log_pre_p.gather(-1, label_ids.unsqueeze(-1)).squeeze(-1) # [batch, max_len]\n loss = -(log_pre_p * masks).sum()\n if average:\n loss = loss / masks.sum() \n return loss\n\ndef logit_KL_loss(logits1:torch.Tensor, logits2:torch.Tensor, masks:torch.Tensor, average = True):\n # logits1/logits2: [batch, max_len, voc_size], masks: [batch, max_len]\n log_p1 = torch.log_softmax(logits1, 2)\n log_p2 = torch.log_softmax(logits2, 2)\n p1 = torch.softmax(logits1, 2)\n kl_loss = (p1 * (log_p1 - log_p2)).sum(2) # [batch, max_len]\n loss = (kl_loss * masks).sum()\n if average:\n loss = loss / masks.sum() \n return loss\n\ndef find_module(module, module_path:str):\n for comp in module_path.split('.'):\n if hasattr(module, comp):\n module = getattr(module, comp)\n elif comp.isdigit():\n module = module[int(comp)]\n else:\n raise RuntimeError(f\"Couldn't find child module {comp}\")\n return module\n\ndef cross_cos_sim(a, b):\n # compute cos similarly: [n, d], [m, d] -> [n, m]\n a = torch.nn.functional.normalize(a, 2, 1)\n b = torch.nn.functional.normalize(b, 2, 1)\n return a @ b.T\n\ndef get_mask_matrix(v, max_n = None):\n max_n = max_n if max_n != None else torch.max(v)\n return torch.arange(1, max_n + 1).unsqueeze(0) <= v.unsqueeze(1)\n" }, { "task_id": 5, "indent": 2, "completion_path": "./editors/recipe/recipe.py", "script": "\npython train_recipe.py -mn 'llama-7b' -dn 'zsre' \n", "latex_code": "\n\\noindent\\textbf{Prompt Learning:}\nThe training losses for prompt learning are based on contrastive learning \\cite{DBLP:journals/corr/abs-1807-03748, DBLP:conf/cvpr/He0WXG20} and are aligned with the properties of reliability, generality, and locality \\cite{ZJUEditSurvey2023}. For a batch of samples, the loss functions for learning continuous prompts are formulated as follows:\n\\begin{equation}\n\\mathcal{L}^{(i)}_{no} = \\delta(\\tilde{r}_{q_{e_i}}, r_{k_i}, R) \n + \\delta(\\tilde{r}_{q_{g_i}}, r_{k_i}, R),\n \\label{eq_retrieval_loss_no}\n\\end{equation}\n\\begin{equation}\n\\begin{split}\n\\mathcal{L}^{(i)}_{so} = & \\delta(\\tilde{r}_{q_{l_i}}, r_{\\Theta},R)\n + \\delta(\\tilde{r}_{q_{e_i}},r_{\\Theta}, R_{\\backslash k_i})\\\\\n& + \\delta(\\tilde{r}_{q_{g_i}}, r_{\\Theta}, R_{\\backslash k_i}), \n \\label{eq_retrieval_loss_so}\n\\end{split}\n\\end{equation}\n\\begin{equation}\n\\mathcal{L}_{pl} = \\frac{1}{b}\\sum_{i=1}^b (\\mathcal{L}^{(i)}_{no} + \\mathcal{L}^{(i)}_{so}),\n \\label{eq_loss_pl}\n\\end{equation}\nwhere $R = \\{r_{k_i}\\}_{i=1}^b \\cup \\{r_{\\Theta}\\}$ and $R_{\\backslash k_i} = R \\setminus \\{r_{k_i}\\}$. $r_{k_i}$ is the representation of the editing knowledge $k_i$ transformed through Eq. \\ref{equation:knowledge_representation}. The query representations $\\tilde{r}_{q_{e_i}}, \\tilde{r}_{q_{g_i}}, \\tilde{r}_{q_{l_i}}$ for $q_{e_i}, q_{g_i}, q_{l_i}$ are attained via Eq. \\ref{equation:query_representation}, respectively. $\\delta$ is the InfoNCE loss \\cite{DBLP:journals/corr/abs-1807-03748}, formulated as:\n\\begin{equation}\n \\delta(q, k_+,\\{k_i\\}_{i=1}^n) = -\\log \\frac{\\exp(q \\cdot k_+ / \\tau)}{\\sum_{i=1}^n \\exp(q \\cdot k_i / \\tau)},\n\\end{equation}\nwhere $\\tau$ is the temperature, typically set to 1 by default.\nIn our work, the \\emph{neighbor-oriented} loss $\\mathcal{L}^{(i)}_{no}$ encourages higher similarity between the editing knowledge and the corresponding reliability or generality queries. The \\emph{sentinel-oriented} loss $\\mathcal{L}^{(i)}_{so}$ ensures that input queries yield the highest similarity with the KS in cases where the retrieval repository lacks relevant knowledge.\n", "namespace": "editors.recipe.recipe.RECIPE.compute_contrastive_losses", "type": "method", "signature_position": [ 302, 303 ], "body_position": [ 304, 353 ], "ReferenceCode_With_Comments": "\nbsz = len(contra_knowl)\ndevice = next(knowl_rep_model.parameters()).device\nrng = np.random.RandomState(42) # For reproducibility\ncc = rng.choice([0, 1], bsz)\n\nq1 = [[contra_q_rel, contra_q_gen][c][i] for i, c in enumerate(cc)]\nq2 = [[contra_q_rel, contra_q_gen][c][i] for i, c in enumerate(1-cc)]\n\n# ---------------------------------------------------------------------------\n# Snippet 1: Encode all representations using the knowledge representation model\n# Maps queries and knowledge to representation space (via Eq. \\ref{equation:query_representation} and \\ref{equation:knowledge_representation}),\n# preparing for similarity computations in subsequent steps.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nq1_reps = knowl_rep_model(q1, knowl_or_query='q') # [bsz, rep_dim]\nq2_reps = knowl_rep_model(q2, knowl_or_query='q') # [bsz, rep_dim]\nknowledge_reps = knowl_rep_model(contra_knowl, knowl_or_query='k') # [bsz, rep_dim]\nknowl_rep_prot = knowl_rep_model.get_knowl_rep_prot() # Prototype representation\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Prepare combined knowledge representations and scaling factor\n# Combines knowledge representations with the sentinel prototype (R in LaTeX) and defines\n# a scaling factor for similarity, a detail omitted in the LaTeX description.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nknowl_reps_with_proto = torch.cat([knowledge_reps, knowl_rep_prot])\nscale_factor = 1 / rep_dim**0.5 # Scaling factor for dot product\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Compute neighbor-oriented loss for reliability/generality\n# Implements \u03b4(tilde_r_q_e_i, r_k_i, R) + \u03b4(tilde_r_q_g_i, r_k_i, R) from Eq. \\ref{eq_retrieval_loss_no},\n# encouraging high similarity between queries and their corresponding knowledge.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nsim_q1 = (q1_reps @ knowl_reps_with_proto.T) * scale_factor # [bsz, bsz+1]\nsim_q1 = torch.softmax(sim_q1 * query_knowledge_t, 1)\nloss_contra_q1 = - torch.log(torch.diag(sim_q1) + eps).mean(0)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Compute sentinel-oriented loss for reliability/generality\n# Implements \u03b4(tilde_r_q_e_i, r_\u0398, R_\\k_i) and \u03b4(tilde_r_q_g_i, r_\u0398, R_\\k_i) from Eq. \\ref{eq_retrieval_loss_so},\n# ensuring queries align with the sentinel when knowledge is irrelevant, with a hinge mechanism.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nsim_q2 = (q2_reps @ knowledge_reps.T) * scale_factor # [bsz, bsz]\nsim_q2 = sim_q2 * (1 - torch.eye(bsz, device=device)) # Zero out self-similarity\nsim_q2 = sim_q2 + torch.diag((q2_reps @ knowl_rep_prot.T)[:, 0] * scale_factor)\nsim_q2 = torch.softmax(sim_q2 * query_prototype_t, 1)\nsecond_sim_q2 = torch.topk(sim_q2, 2, 1).values[:, 1]\nsim_q2_diag = torch.diag(sim_q2)\nsim_q2_filtered = torch.masked_select(sim_q2_diag, sim_q2_diag < second_sim_q2 * constra_hinge_scale)\nif len(sim_q2_filtered) == 0:\n loss_contra_q2 = 0\nelse:\n loss_contra_q2 = - torch.log(sim_q2_filtered + eps).mean(0)\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Compute sentinel-oriented loss for locality\n# Implements \u03b4(tilde_r_q_l_i, r_\u0398, R) from Eq. \\ref{eq_retrieval_loss_so},\n# ensuring locality queries prefer the sentinel over irrelevant knowledge, with hinge filtering.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nlosses_contra_q3 = {}\nloss_contra_q3 = 0\nfor k, cql in contra_q_loc.items():\n q3_reps = knowl_rep_model(cql, knowl_or_query='q') # [bsz, rep_dim]\n sim_q3 = (q3_reps @ knowl_reps_with_proto.T) * scale_factor # [bsz, bsz+1]\n sim_q3 = torch.softmax(sim_q3 * query_prototype_t, 1)\n second_sim_q3 = torch.topk(sim_q3, 2, 1).values[:, 1]\n sim_q3_proto = sim_q3[:, -1]\n sim_q3_filtered = torch.masked_select(sim_q3_proto, sim_q3_proto < second_sim_q3 * constra_hinge_scale)\n if len(sim_q3_filtered) == 0:\n l = 0\n else:\n l = - torch.log(sim_q3_filtered + eps).mean(0)\n losses_contra_q3[k] = l\n loss_contra_q3 += l\n# [End Snippet 5]\n\n# ---------------------------------------------------------------------------\n# Snippet 6: Combine all contrastive losses\n# Combines neighbor-oriented and sentinel-oriented losses as per Eq. \\ref{eq_loss_pl},\n# though averaging over batch size (1/b) is handled externally in training loop.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 6]\nloss_contra = loss_contra_q1 + loss_contra_q2 + loss_contra_q3\nreturn loss_contra_q1, loss_contra_q2, loss_contra_q3, losses_contra_q3, loss_contra\n# [End Snippet 6]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - Scaling factor (1 / rep_dim**0.5) for similarity computation.\n - The LaTeX description does not include a mechanism for randomly selecting between reliability and generality queries when computing the contrastive losses for prompt learning. In the reference implementation, the process involves, for each sample in a batch, flipping a coin to decide which of the two query types (reliability or generality) is used to compute the neighbor-oriented loss, while the other is assigned to the sentinel-oriented loss. This random alternation introduces variability into the training process, ensuring that over multiple iterations, the model learns from both query perspectives in a balanced yet stochastic manner.\n - The LaTeX omits a critical step where an adaptive threshold is applied individually to each sample\u2019s contribution to the sentinel-oriented and locality losses. In the reference workflow, before averaging the losses across the batch, each sample\u2019s loss is evaluated against a condition: if the similarity between the query representation and its intended positive representation is not sufficiently higher than its similarity to other representations (based on a scaled comparison), that sample\u2019s loss is included; otherwise, it is excluded.\n\n - Mismatched Details:\n - LaTeX assumes a fixed temperature \u03c4=1, while Python allows configurable query_knowledge_t and query_prototype_t.\n", "Missing_details": [ "\n- Scaling factor (1 / rep_dim**0.5) for similarity computation.\n", "\n- The LaTeX description does not include a mechanism for randomly selecting between reliability and generality queries when computing the contrastive losses for prompt learning. In the reference implementation, the process involves, for each sample in a batch, flipping a coin to decide which of the two query types (reliability or generality) is used to compute the neighbor-oriented loss, while the other is assigned to the sentinel-oriented loss. This random alternation introduces variability into the training process, ensuring that over multiple iterations, the model learns from both query perspectives in a balanced yet stochastic manner.\n", "\n- The LaTeX omits a critical step where an adaptive threshold is applied individually to each sample\u2019s contribution to the sentinel-oriented and locality losses. In the reference workflow, before averaging the losses across the batch, each sample\u2019s loss is evaluated against a condition: if the similarity between the query representation and its intended positive representation is not sufficiently higher than its similarity to other representations (based on a scaled comparison), that sample\u2019s loss is included; otherwise, it is excluded.\n" ], "Mismatched_details": [ "\n- LaTeX assumes a fixed temperature \u03c4=1, while Python allows configurable query_knowledge_t and query_prototype_t." ] }, "Arguments": { "string": "\nInput Variables:\n - self (RECIPE): Instance of the RECIPE editor class, providing context and configuration.\n - knowl_rep_model (KnowledgeRepModel): Model to encode knowledge and query representations.\n - contra_knowl (List[str], length=bsz): List of knowledge statements for editing.\n - contra_q_rel (List[str], length=bsz): Reliability queries corresponding to editing knowledge.\n - contra_q_gen (List[str], length=bsz): Generality queries corresponding to editing knowledge.\n - contra_q_loc (Dict[str, List[str]]): Locality queries, mapping loss names to lists of length bsz.\n - query_knowledge_t (float): Temperature for neighbor-oriented loss softmax.\n - query_prototype_t (float): Temperature for sentinel-oriented loss softmax.\n - constra_hinge_scale (float): Hinge scaling factor for adaptive thresholding (\u22651 enables hinge).\n - rep_dim (int): Dimension of knowledge representation vectors.\n - eps (float, default=1e-8): Small constant for numerical stability in log calculations.\n", "Arguments_list": [ { "name": "self", "string": "\n- self (RECIPE): Instance of the RECIPE editor class, providing context and configuration.", "dependency": null }, { "name": "knowl_rep_model", "string": "\n- knowl_rep_model (KnowledgeRepModel): Model to encode knowledge and query representations.", "dependency": null }, { "name": "contra_knowl", "string": "\n- contra_knowl (List[str], length=bsz): List of knowledge statements for editing.", "dependency": null }, { "name": "contra_q_rel", "string": "\n- contra_q_rel (List[str], length=bsz): Reliability queries corresponding to editing knowledge.", "dependency": null }, { "name": "contra_q_gen", "string": "\n- contra_q_gen (List[str], length=bsz): Generality queries corresponding to editing knowledge.", "dependency": null }, { "name": "contra_q_loc", "string": "\n- contra_q_loc (Dict[str, List[str]]): Locality queries, mapping loss names to lists of length bsz.", "dependency": null }, { "name": "query_knowledge_t", "string": "\n- query_knowledge_t (float): Temperature for neighbor-oriented loss softmax.", "dependency": null }, { "name": "query_prototype_t", "string": "\n- query_prototype_t (float): Temperature for sentinel-oriented loss softmax.", "dependency": null }, { "name": "constra_hinge_scale", "string": "\n- constra_hinge_scale (float): Hinge scaling factor for adaptive thresholding (\u22651 enables hinge).", "dependency": null }, { "name": "rep_dim", "string": "\n- rep_dim (int): Dimension of knowledge representation vectors.", "dependency": null }, { "name": "eps", "string": "\n- eps (float, default=1e-8): Small constant for numerical stability in log calculations.", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-File: \n None\n\n - Cross-File: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.cat\n - torch.softmax\n - torch.log\n - torch.diag\n - torch.topk\n - torch.masked_select\n - torch.eye\n - numpy.random.RandomState\n", "list": [ "torch.cat", "torch.softmax", "torch.log", "torch.diag", "torch.topk", "torch.masked_select", "torch.eye", "numpy.random.RandomState" ] }, "Return": { "Return_String": "\nOutput Variables:\n - loss_contra_q1 (torch.Tensor): Neighbor-oriented loss for reliability/generality.\n - loss_contra_q2 (torch.Tensor): Sentinel-oriented loss for reliability/generality.\n - loss_contra_q3 (torch.Tensor): Total sentinel-oriented loss for locality.\n - losses_contra_q3 (Dict[str, torch.Tensor]): Per-locality-loss breakdown.\n - loss_contra (torch.Tensor): Combined contrastive loss (Eq. \\ref{eq_loss_pl}).\n", "Return_list": [ { "name": "loss_contra_q1", "string": "\n- loss_contra_q1 (torch.Tensor): Neighbor-oriented loss for reliability/generality.", "dependency": null }, { "name": "loss_contra_q2", "string": "\n- loss_contra_q2 (torch.Tensor): Sentinel-oriented loss for reliability/generality.", "dependency": null }, { "name": "loss_contra_q3", "string": "\n- loss_contra_q3 (torch.Tensor): Total sentinel-oriented loss for locality.", "dependency": null }, { "name": "losses_contra_q3", "string": "\n- losses_contra_q3 (Dict[str, torch.Tensor]): Per-locality-loss breakdown.", "dependency": null }, { "name": "loss_contra", "string": "\n- loss_contra (torch.Tensor): Combined contrastive loss (Eq. \\ref{eq_loss_pl}).", "dependency": null } ] }, "ori_python_file": "from editors.editor import BaseEditor, EditorConfig\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nfrom typing import Dict, List, Tuple \nfrom dataclasses import dataclass, asdict\nimport numpy as np\nfrom copy import deepcopy\nimport torch, os, yaml\nfrom torch.utils.tensorboard import SummaryWriter \nfrom torch.optim import Adam\nfrom .models import KnowledgeRepModel, PromptTransformer\nfrom utils.data import ParallelDataset\nfrom datetime import datetime\nfrom tqdm import tqdm\nimport random\nos.environ['PYTHONHASHSEED'] = str(42)\nos.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":4096:8\"\nnp.random.seed(42)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\ntorch.use_deterministic_algorithms(True)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nrandom.seed(42)\ntorch.cuda.synchronize()\n\n@dataclass\nclass RECIPEConfig(EditorConfig):\n @dataclass\n class TrainingConfig():\n krm_lr: float\n pt_lr: float\n relia_lambda: float\n gen_lambda: float\n loc_lambda: float\n contra_lambda: float\n query_knowledge_t: float\n query_prototype_t: float\n constra_hinge_scale: float # w/hinge >= 1, w/o hinge== 999999 \n edit_hinge_scale: float # w/hinge >= 1, w/o hinge== 999999 \n # set in train_init\n batch_size:int = None\n sample_count:int = None\n random_seed:int = None\n eps:float = 1e-8\n \n prompt_token_n: int\n edit_model_name: str\n knowledge_rep_dim: int\n knowl_rep_prot_token_n: int\n model_hidden_size: int\n begin_layer_path:str\n lm_head_path:str\n training: TrainingConfig\n\n @classmethod\n def from_yaml(self, fpath):\n with open(fpath, \"r\") as f:\n data = yaml.safe_load(f)\n data['training'] = self.TrainingConfig(**data['training'])\n return self(**data)\n @classmethod\n def from_json(self, fpath):\n raise\n \nclass RECIPE(BaseEditor):\n def __init__(self, \n model: AutoModelForCausalLM,\n tokenizer: AutoTokenizer,\n config: RECIPEConfig,\n device = 'cuda',\n krm_base_path = 'models/roberta-base',\n retr_top_k = 1,\n retr_min_sim = -999,\n auto_retrieve = True, \n ckpt_path = None \n ):\n super().__init__(model, tokenizer, device)\n self.cfg = config\n # initialize model & parameters\n self.knowl_rep_model = KnowledgeRepModel(config.knowledge_rep_dim, \n config.knowl_rep_prot_token_n, self.device, krm_base_path)\n self.prompt_transformer = PromptTransformer(config.knowledge_rep_dim, \n config.model_hidden_size, config.prompt_token_n, self.device)\n # initialize hooks\n self.begin_layer = find_module(self.model, self.cfg.begin_layer_path)\n self.lm_head = find_module(self.model, self.cfg.lm_head_path)\n self.model.forward = self.register_model_forward_hook(self.model, \n self.model.forward, self.begin_layer, self.lm_head)\n self.begin_layer_hook = self.register_editing_hook(self.begin_layer, self.lm_head)\n # initialize editing prompts\n self.restore_to_original_model()\n self.auto_retrieve = auto_retrieve \n self.retr_top_k = retr_top_k\n self.retr_min_sim = retr_min_sim\n self.set_train(False) \n if ckpt_path != None:\n self.load_ckpt(ckpt_path, load_opt = False)\n \n ############################################################################\n ############################# Initialize ###################################\n ############################################################################\n def register_editing_hook(self, begin_layer, lm_head_layer):\n def forward_pre_hook(module, args):\n # If do not has past_key_values, add editing prompts before reps.\n if not module.has_past_kv:\n args = args[0]\n args = torch.stack([\n torch.cat([p, inp[:-len(p) if len(p) != 0 else None]], 0)\n for inp, p in zip(args, self.adopted_prompts)], 0)\n return (args, )\n def forward_hook(module, args, output):\n if not module.has_past_kv:\n max_n = max([len(p) for p in self.adopted_prompts])\n output = torch.stack([\n ot[len(p):len(p)-max_n if len(p)-max_n != 0 else None]\n for ot, p in zip(output, self.adopted_prompts)], 0)\n return output\n begin_layer_hook = begin_layer.register_forward_pre_hook(forward_pre_hook)\n lm_head_layer_hook = lm_head_layer.register_forward_hook(forward_hook)\n return [begin_layer_hook, lm_head_layer_hook]\n\n def register_model_forward_hook(self, model, model_forward, begin_layer, lm_head):\n if hasattr(model, 'recipe_hooked'):\n return model_forward\n model.recipe_hooked = True\n def forward_recipe(**kargs):\n if 'past_key_values' in kargs and kargs['past_key_values'] != None:\n begin_layer.has_past_kv = True\n lm_head.has_past_kv = True\n else:\n begin_layer.has_past_kv = False\n lm_head.has_past_kv = False\n b, l = kargs['input_ids'].shape\n inp_sents = [self.tokenizer.decode(i, skip_special_tokens=True) \n for i in kargs['input_ids']]\n if self.auto_retrieve: \n retrieved_ids = self.retrieve_and_get_ids_sim(inp_sents)[0]\n # print(retrieved_ids)\n self.adopted_prompts = [self.prompts_base[i].reshape(\n len(i)*self.cfg.prompt_token_n, self.cfg.model_hidden_size) \n for i in retrieved_ids]\n if len(self.adopted_prompts) != b:\n print(len(self.adopted_prompts), b) \n raise ValueError\n pad = torch.ones([b, max([len(i) for i in self.adopted_prompts])], \n dtype = torch.long).to(self.device)\n if 'attention_mask' in kargs and kargs['attention_mask'] != None:\n kargs['attention_mask'] = torch.cat([kargs['attention_mask'], pad], 1)\n kargs['input_ids'] = torch.cat([kargs['input_ids'], pad * self.tokenizer.pad_token_id], 1)\n return model_forward(**kargs)\n return forward_recipe\n\n ############################################################################\n ############################# RECIPE Edit Related ############################\n ############################################################################\n def retrieve_and_get_ids_sim(self, input_queries:List[str]):\n query_reps = self.knowl_rep_model(input_queries, knowl_or_query = 'q') # [n, knowledge_rep_dim] \n sim_matrx = (query_reps @ self.knowledge_base.T) / self.cfg.knowledge_rep_dim**0.5 # cross_cos_sim(query_reps, self.knowledge_base) # [n, edit_n]\n sim_with_prototype = sim_matrx[:, :1] \n sorted_sim, order = torch.sort(sim_matrx, 1, True) # [n, edit_n]\n mask = sorted_sim[:, :self.retr_top_k] > self.retr_min_sim\n mask &= sorted_sim[:, :self.retr_top_k] > sim_with_prototype\n retrieved_ids = torch.masked_select(order[:, :self.retr_top_k], mask)\n retrieved_ids = torch.split(retrieved_ids, mask.sum(1).tolist()) # retrieved indexes\n return retrieved_ids, sorted_sim, order # [retr_ids_1, retr_ids_2, ..., retr_ids_n]\n\n ############################################################################\n ############################# Editor Basic Functions #######################\n ############################################################################\n def name_of_editor_and_model(self)->Tuple[str, str]:\n return 'recipe', self.cfg.edit_model_name\n\n def if_can_batch_edit(self):\n return True\n \n def restore_to_original_model(self):\n self.knowledge_base_nl = [''] # [edit_n, knowledge_rep_dim]\n self.knowledge_base = self.knowl_rep_model.get_knowl_rep_prot() # [edit_n, knowledge_rep_dim]\n self.prompts_base = torch.zeros([1, self.cfg.prompt_token_n, self.cfg.model_hidden_size], \n device = self.device) # [edit_n, prompt_token_n, model_hidden_size]\n self.adopted_prompts = [] # List[torch.Tensor], len(List) = btach_size, Tensor.size = [retr_n * prompt_token_n, model_hidden_size]\n\n def edit_batch(self, requests: List[Dict]):\n '''requests = [\n {'prompt':str, 'subject':str, 'target_new':str}\n {'prompt':str, 'subject':str, 'target_new':str}, ...\n ]\n '''\n rs = []\n for r in requests:\n rs.append(r['prompt'] + r['target_new'])\n self.knowledge_base_nl.extend(rs)\n new_reps = self.knowl_rep_model(rs, knowl_or_query = 'k')\n new_prompts = self.prompt_transformer(new_reps)\n self.knowledge_base = torch.cat([self.knowledge_base, new_reps], 0)\n self.prompts_base = torch.cat([self.prompts_base, new_prompts], 0)\n\n return self.knowledge_base_nl, self.knowledge_base, self.prompts_base\n\n def edit_one_piece(self, request: Dict) -> None:\n \"\"\"\n request = {'prompt':str, 'subject':str, 'target_new':str}\n \"\"\"\n requests = [request]\n for r in range(len(requests)):\n requests[r]['prompt'] = requests[r]['prompt'].strip() + \" \"\n requests[r]['target_new'] = requests[r]['target_new'].strip()\n knowledge_base_nl, knowledge_base, prompts_base= self.edit_batch([request])\n\n ############################################################################\n ############################# RECIPE Training ################################\n ############################################################################\n def set_train(self, if_train = False):\n self.model.train(False)\n self.model.requires_grad_(False)\n self.knowl_rep_model.train(if_train)\n self.knowl_rep_model.requires_grad_(if_train)\n self.prompt_transformer.train(if_train)\n self.prompt_transformer.requires_grad_(if_train)\n self.auto_retrieve = not if_train\n\n def train_init(self, sample_count, get_data_by_ids, batch_size, \n records_dir:str = 'train_records', train_name_prefix = None, \n train_name:str = None, load_ckpt_path:str = None, \n save_ckpt_per_i = 3000, log_per_i = 10, random_seed = None): \n '''\n Used to initialize `ParallelDataset`:\n sample_count: count of used data in dataset.\n get_data_by_ids: function getting data by ids, assume data structure: (\n batch_knowledge: List[str], len = batch_size\n contra_q: List[str], len = batch_size * 3\n contra_sim_m: torch.Tensor[batch_size, batch_size * 3]\n batch_relia_xym: (input_ids, label_ids, masks), \n batch_gen_xym: {\n loss_name_1: (input_ids, label_ids, masks),\n loss_name_2: (input_ids, label_ids, masks), ...\n },\n batch_loc_xym: {\n loss_name_1: (input_ids, masks)\n loss_name_2: (input_ids, masks), ...\n } \n ), where `input_ids`, `label_ids`, and `label_ids` are with shape \n [batch_size, length]\n '''\n # initialize data generator\n self.rng = np.random.default_rng(random_seed)\n self.data_generator = ParallelDataset(sample_count, get_data_by_ids, \n batch_size, True, 16, False, random_seed)\n # initialize checkpoint/log directory and writer\n t = datetime.now().strftime('%Y.%m.%d-%H.%M.%S')\n train_name = (train_name_prefix + '-' if train_name_prefix else \"\") + \\\n (train_name if train_name else t)\n records_dir = os.path.join(records_dir, *self.name_of_editor_and_model(), train_name)\n self.save_ckpt_dir = os.path.join(records_dir, 'checkpoints')\n if not os.path.exists(self.save_ckpt_dir):\n os.makedirs(self.save_ckpt_dir)\n logs_path = os.path.join(records_dir, 'logs')\n if not os.path.exists(logs_path):\n os.makedirs(logs_path)\n with open(os.path.join(records_dir, 'config.yaml'), 'w') as f:\n self.cfg.training.batch_size = batch_size\n self.cfg.training.sample_count = sample_count\n self.cfg.training.random_seed = random_seed\n yaml.dump(asdict(self.cfg), f)\n self.log_writer = SummaryWriter(logs_path)\n self.save_ckpt_per_i = save_ckpt_per_i\n self.log_per_i = log_per_i\n # initialize optimizer and load checkpoints\n self.opt = Adam([\n {'params': self.knowl_rep_model.parameters(), 'lr': self.cfg.training.krm_lr},\n {'params': self.prompt_transformer.parameters(), 'lr': self.cfg.training.krm_lr}])\n if load_ckpt_path and os.path.isfile(load_ckpt_path):\n self.ema_loss = self.load_ckpt(load_ckpt_path, True) \n else:\n self.train_i, self.train_epoch = 1, 1\n self.ema_loss = 1\n\n def train(self, epochs):\n if self.log_writer == None:\n raise \"Call `self.train_init()` to initialize training first!\"\n print('Checkpoints dir: ', self.save_ckpt_dir)\n start_epoch = self.train_epoch\n self.set_train(True) \n for self.train_epoch in range(start_epoch, epochs + 1): \n progress_bar = tqdm(total = self.data_generator.sample_count, \n position = 0, leave = True, desc = \"Epoch %d\"%self.train_epoch, dynamic_ncols = True)\n for contra_data, edit_data in self.data_generator:\n # train after edit\n log_dict = self.__train_a_batch__(*contra_data, *edit_data)\n # log\n log_dict['Epoch'] = self.train_epoch\n if self.train_i % self.log_per_i == 0:\n self.write_logs(self.train_i, log_dict)\n # if self.train_i % self.save_ckpt_per_i == 0:\n # self.save_ckpt(self.train_i, self.train_epoch, log_dict['Loss'])\n self.train_i += 1 \n progress_bar.update(len(contra_data[0]))\n progress_bar.close() \n self.set_train(False)\n\n def compute_contrastive_losses(self, knowl_rep_model, contra_knowl, contra_q_rel, contra_q_gen, contra_q_loc, \n query_knowledge_t, query_prototype_t, constra_hinge_scale, rep_dim, eps=1e-8):\n bsz = len(contra_knowl)\n device = next(knowl_rep_model.parameters()).device\n rng = np.random.RandomState(42) # For reproducibility\n cc = rng.choice([0, 1], bsz)\n \n q1 = [[contra_q_rel, contra_q_gen][c][i] for i, c in enumerate(cc)]\n q2 = [[contra_q_rel, contra_q_gen][c][i] for i, c in enumerate(1-cc)]\n\n q1_reps = knowl_rep_model(q1, knowl_or_query='q') # [bsz, rep_dim]\n q2_reps = knowl_rep_model(q2, knowl_or_query='q') # [bsz, rep_dim]\n knowledge_reps = knowl_rep_model(contra_knowl, knowl_or_query='k') # [bsz, rep_dim]\n knowl_rep_prot = knowl_rep_model.get_knowl_rep_prot() # Prototype representation\n\n knowl_reps_with_proto = torch.cat([knowledge_reps, knowl_rep_prot])\n scale_factor = 1 / rep_dim**0.5 # Scaling factor for dot product\n\n sim_q1 = (q1_reps @ knowl_reps_with_proto.T) * scale_factor # [bsz, bsz+1]\n sim_q1 = torch.softmax(sim_q1 * query_knowledge_t, 1)\n loss_contra_q1 = - torch.log(torch.diag(sim_q1) + eps).mean(0)\n\n sim_q2 = (q2_reps @ knowledge_reps.T) * scale_factor # [bsz, bsz]\n sim_q2 = sim_q2 * (1 - torch.eye(bsz, device=device)) # Zero out self-similarity\n sim_q2 = sim_q2 + torch.diag((q2_reps @ knowl_rep_prot.T)[:, 0] * scale_factor)\n sim_q2 = torch.softmax(sim_q2 * query_prototype_t, 1)\n second_sim_q2 = torch.topk(sim_q2, 2, 1).values[:, 1]\n sim_q2_diag = torch.diag(sim_q2)\n sim_q2_filtered = torch.masked_select(sim_q2_diag, sim_q2_diag < second_sim_q2 * constra_hinge_scale)\n if len(sim_q2_filtered) == 0:\n loss_contra_q2 = 0\n else:\n loss_contra_q2 = - torch.log(sim_q2_filtered + eps).mean(0)\n\n losses_contra_q3 = {}\n loss_contra_q3 = 0\n for k, cql in contra_q_loc.items():\n q3_reps = knowl_rep_model(cql, knowl_or_query='q') # [bsz, rep_dim]\n sim_q3 = (q3_reps @ knowl_reps_with_proto.T) * scale_factor # [bsz, bsz+1]\n sim_q3 = torch.softmax(sim_q3 * query_prototype_t, 1)\n second_sim_q3 = torch.topk(sim_q3, 2, 1).values[:, 1]\n sim_q3_proto = sim_q3[:, -1]\n sim_q3_filtered = torch.masked_select(sim_q3_proto, sim_q3_proto < second_sim_q3 * constra_hinge_scale)\n if len(sim_q3_filtered) == 0:\n l = 0\n else:\n l = - torch.log(sim_q3_filtered + eps).mean(0)\n losses_contra_q3[k] = l\n loss_contra_q3 += l\n\n loss_contra = loss_contra_q1 + loss_contra_q2 + loss_contra_q3\n return loss_contra_q1, loss_contra_q2, loss_contra_q3, losses_contra_q3, loss_contra\n\n\n def __train_a_batch__(self, contra_knowl, contra_q_rel, contra_q_gen, contra_q_loc,\n batch_relia_xym, batch_gen_xym, batch_loc_xym):\n # prediction before edit for locality loss\n with torch.no_grad():\n for loss_name, sp in batch_loc_xym.items():\n input_ids, _, masks = sp\n self.adopted_prompts = [torch.zeros([0, self.cfg.model_hidden_size], device = self.device)] * len(input_ids)\n pre_logits = self.model(input_ids = input_ids).logits\n batch_loc_xym[loss_name] = ((input_ids, masks), pre_logits)\n loss = 0 \n bsz = len(contra_knowl)\n eps = self.cfg.training.eps\n ehs = self.cfg.training.edit_hinge_scale\n \n # Compute contrastive losses using the refactored function\n loss_contra_q1, loss_contra_q2, loss_contra_q3, losses_contra_q3, loss_contra = self.compute_contrastive_losses(\n self.knowl_rep_model, \n contra_knowl, \n contra_q_rel, \n contra_q_gen, \n contra_q_loc,\n self.cfg.training.query_knowledge_t,\n self.cfg.training.query_prototype_t,\n self.cfg.training.constra_hinge_scale,\n self.cfg.knowledge_rep_dim,\n eps\n )\n loss += loss_contra * self.cfg.training.contra_lambda\n # edit loss\n knowledge_reps = self.knowl_rep_model(contra_knowl, knowl_or_query = 'k')\n self.adopted_prompts = [i for i in self.prompt_transformer(knowledge_reps)]\n # compute reliability loss\n (input_ids, label_ids, masks) = batch_relia_xym\n relia_loss = hinge_label_loss(self.model, input_ids, label_ids, masks, True, eps, ehs)\n loss += relia_loss * self.cfg.training.relia_lambda\n # compute generality loss\n gen_losses = {}\n for loss_name, sp in batch_gen_xym.items():\n input_ids, label_ids, masks = sp\n gen_loss = hinge_label_loss(self.model, input_ids, label_ids, masks, True, eps, ehs)\n gen_losses[loss_name] = gen_loss\n loss += gen_loss * self.cfg.training.gen_lambda\n # compute locality loss\n loc_losses = {}\n for loss_name, sp in batch_loc_xym.items():\n (input_ids, masks), pre_logits = sp\n post_logits = self.model(input_ids = input_ids).logits\n loc_loss = logit_KL_loss(pre_logits, post_logits, masks)\n loc_losses[loss_name] = loc_loss\n loss += loc_loss * self.cfg.training.loc_lambda\n # update\n loss.backward()\n self.opt.step()\n self.opt.zero_grad()\n self.ema_loss = self.ema_loss + (loss.detach() - self.ema_loss) / self.log_per_i\n log_dict = {\n 'Loss': loss,\n 'EMA Loss': self.ema_loss, \n 'Contrastive loss': loss_contra,\n 'Contrastive loss q2k': loss_contra_q1,\n 'Contrastive loss q2prot': loss_contra_q2 + loss_contra_q3,\n 'Contrastive loss q2prot-rg': loss_contra_q2,\n 'Contrastive loss q2prot-loc': losses_contra_q3,\n 'Reliability loss': relia_loss,\n 'Generality loss': gen_losses,\n 'Locality loss': loc_losses\n }\n return log_dict\n\n def write_logs(self, i, logs:dict):\n for log_name, log in logs.items():\n if type(log) == dict:\n logs1 = {}\n for n, l in log.items():\n logs1[log_name + '-' + n] = l\n self.write_logs(i, logs1)\n else: \n self.log_writer.add_scalar(log_name, log, i)\n\n def save_ckpt(self, i:int, epoch:int, loss:float):\n ckpt_name = 'epoch-%d-i-%d-ema_loss-%.4f'%(epoch, i, self.ema_loss)\n ckpt_path = os.path.join(self.save_ckpt_dir, ckpt_name)\n ckpt = {\n 'i': i,\n 'epoch': epoch,\n 'loss': loss,\n 'knowl_rep_model': self.knowl_rep_model.state_dict(),\n 'prompt_transformer': self.prompt_transformer.state_dict(),\n 'opt': self.opt.state_dict()\n }\n torch.save(ckpt, ckpt_path)\n\n def load_ckpt(self, ckpt_path, restrict = True, load_opt = True):\n ckpt = torch.load(ckpt_path, 'cpu')\n self.train_i = ckpt['i']\n self.train_epoch = ckpt['epoch']\n self.knowl_rep_model.load_state_dict(ckpt['knowl_rep_model'], restrict)\n self.prompt_transformer.load_state_dict(ckpt['prompt_transformer'], restrict)\n if load_opt:\n self.opt.load_state_dict(ckpt['opt'])\n print('Load RECIPE checkpoints from', ckpt_path)\n return ckpt['loss']\n\ndef hinge_label_loss(model, input_ids:torch.Tensor, label_ids:torch.Tensor, \n masks:torch.Tensor, average = True, eps = 1e-8, hinge_scale = 1.1):\n # input_ids/label_ids/masks: [batch, max_len]\n logits = model(input_ids = input_ids).logits # [batch, max_len, voc_size]\n pre_p = torch.softmax(logits, 2) # [batch, max_len, voc_size]\n second_pre_p = torch.topk(pre_p, 2, -1).values[:, :, 1] # [batch, max_len]\n pre_p = pre_p.gather(-1, label_ids.unsqueeze(-1)).squeeze(-1) # [batch, max_len]\n masks = masks * (pre_p < second_pre_p * hinge_scale)\n pre_p = torch.masked_select(pre_p, masks.to(bool))\n loss = - torch.log(pre_p + eps).sum() # [batch, max_len] \n if average:\n sm = masks.sum() \n if sm != 0:\n loss = loss / sm\n return loss\n\ndef label_loss(model, input_ids:torch.Tensor, label_ids:torch.Tensor, masks:torch.Tensor, average = True):\n # input_ids/label_ids/masks: [batch, max_len]\n logits = model(input_ids = input_ids).logits\n log_pre_p = torch.log_softmax(logits, 2) # [batch, max_len, voc_size]\n log_pre_p = log_pre_p.gather(-1, label_ids.unsqueeze(-1)).squeeze(-1) # [batch, max_len]\n loss = -(log_pre_p * masks).sum()\n if average:\n loss = loss / masks.sum() \n return loss\n\ndef logit_KL_loss(logits1:torch.Tensor, logits2:torch.Tensor, masks:torch.Tensor, average = True):\n # logits1/logits2: [batch, max_len, voc_size], masks: [batch, max_len]\n log_p1 = torch.log_softmax(logits1, 2)\n log_p2 = torch.log_softmax(logits2, 2)\n p1 = torch.softmax(logits1, 2)\n kl_loss = (p1 * (log_p1 - log_p2)).sum(2) # [batch, max_len]\n loss = (kl_loss * masks).sum()\n if average:\n loss = loss / masks.sum() \n return loss\n\ndef find_module(module, module_path:str):\n for comp in module_path.split('.'):\n if hasattr(module, comp):\n module = getattr(module, comp)\n elif comp.isdigit():\n module = module[int(comp)]\n else:\n raise RuntimeError(f\"Couldn't find child module {comp}\")\n return module\n\ndef cross_cos_sim(a, b):\n # compute cos similarly: [n, d], [m, d] -> [n, m]\n a = torch.nn.functional.normalize(a, 2, 1)\n b = torch.nn.functional.normalize(b, 2, 1)\n return a @ b.T\n\ndef get_mask_matrix(v, max_n = None):\n max_n = max_n if max_n != None else torch.max(v)\n return torch.arange(1, max_n + 1).unsqueeze(0) <= v.unsqueeze(1)\n" } ] }, { "paper_id": 27, "paper_details": { "title": "NeuroMax: Enhancing Neural Topic Modeling via Maximizing Mutual Information and Group Topic Regularization", "url": "https://arxiv.org/pdf/2409.19749" }, "repo_original_url": "https://github.com/Fsoft-AIC/NeuroMax", "project_path": "Benchmark/27-NeuroMax/NeuroMax-master", "enviorment_name": "neuromax", "file_organization": "\nNeuroMax-master/\n README.md\n LICENSE\n env.sh\n main.py\n basic_trainer.py\n datasethandler/\n basic_dataset_handler.py\n file_utils.py\n __init__.py\n datasets/\n YahooAnswers/\n test_bow.npz\n test_labels.txt\n test_texts.txt\n train_bow.npz\n train_labels.txt\n train_texts.txt\n vocab.txt\n with_bert/\n test_bert.npz\n train_bert.npz\n word_embeddings.npz\n evaluations/\n clustering.py\n topic_coherence.py\n topic_diversity.py\n __init__.py\n NeuroMax/\n ECR.py\n GR.py\n NeuroMax.py\n utils/\n config.py\n file_handling.py\n log.py\n miscellaneous.py\n seed.py\n static_utils.py\n __init__.py\n", "latex_code_path": "Benchmark/27-NeuroMax/arXiv-2409.19749v1", "task_details": [ { "task_id": 0, "indent": 2, "script": "\npython main.py --use_pretrainWE\n", "completion_path": "./NeuroMax/GR.py", "latex_code": "\n\\subsection{Group Topic Regularization} \\label{sec:method:gr}\nWe now introduce a new topic regularization based on optimal transport (OT) \\cite{peyr\u00e92020computationalOT} for the decoder. Specifically, we assume that each topic contains an equal amount of information and conduct a process where information is transferred between topics based on their relationships, ensuring the total amount remains unchanged. This process helps us learn the relationship between topics. To make it easier to relate to the mass redistribution problem in OT \\cite{peyr\u00e92020computationalOT}, we use the metaphor of $K$ topics as $K$ piles of soil, each with an equal mass of $\\frac{1}{K}$. After transportation, the mass of each pile of soil remains $\\frac{1}{K}$. The transportation cost between two topics is calculated based on the distance between them in the embedding space. The matrix $C$ represents the transportation costs for all pairs of topics. The optimal transport plan $Q$ reveals the relationships between topics.\n\nFormally, let $C \\in \\mathbb{R}^{K\\times K}$ be the cost matrix in Euclidean space for topic embeddings $\\{\\textbf{t}_1, \\textbf{t}_2, \\dots, \\textbf{t}_K\\}$. The transport plan $Q$ is the solution to the following optimization problem:\n\\begin{equation} \\label{eq:ot-gr}\n\\begin{split}\n\\text{minimize} & \\quad \\langle Q, C \\rangle - \\epsilon H(Q) \\\\\n\\text{subject to} & \\quad Q \\in \\mathbb{R}^{K \\times K}, \\\\\n& \\quad Q \\mathds{1}_K = Q^\\top \\mathds{1}_K = \\frac{1}{K} \\mathds{1}_K, \\\\\n& \\quad Q_{i,i} = 0 \\ \\forall i \\in \\llbracket K\\rrbracket. \\\\\n\\end{split}\n\\end{equation}\nThe regularization term $\\epsilon H(Q)$ encourages the matrix $Q$ to become dense, thereby facilitating the sharing of information across multiple topics \\cite{blondel2018denseplan}. To focus on the interrelationships between different topics, the constraint $Q_{i,i} = 0$ is imposed. In practice, we ensure that $Q_{i,i}$ remains sufficiently small by setting $C_{i,i}$ to a large value. Subsequently, the Sinkhorn algorithm is employed to solve the optimization problem \\cite{2013sinkhorn}. \n", "namespace": "NeuroMax.GR.compute_optimal_transport", "type": "method", "signature_position": [ 31, 31 ], "body_position": [ 32, 70 ], "ReferenceCode_With_Comments": "\ndevice = cost_matrix.device\n\n# ---------------------------------------------------------------------------\n# Snippet 1: Compute the row and column marginals a and b from the input matrix P. \n# These represent the target distributions for the rows and columns of the transport plan Q, \n# which are both uniform distributions [1/K, ..., 1/K] as specified in the constraints \n# Q 1_K = Q^T 1_K = 1/K 1_K in equation (eq:ot-gr).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\na = marginals.sum(axis=1).unsqueeze(1).to(device) # Row marginals\nb = marginals.sum(axis=0).unsqueeze(1).to(device) # Column marginals\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Initialize the scaling factor u for the Sinkhorn algorithm and compute the kernel matrix K = exp(-C * sinkhorn_alpha). \n# This relates to the entropy regularization term -\u03b5 H(Q) in equation (eq:ot-gr), where sinkhorn_alpha = 1/\u03b5 encourages a dense transport plan Q by transforming the cost matrix C into a kernel.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nu = (torch.ones_like(a) / a.size()[0]).to(device)\nK = torch.exp(-cost_matrix * self.sinkhorn_alpha)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Perform the Sinkhorn iterations to compute the scaling factors u and v. \n# This iterative process solves the optimization problem in equation (eq:ot-gr) by alternately updating the scaling factors to satisfy the marginal constraints, with periodic convergence checks as part of the Sinkhorn algorithm referenced in the LaTeX.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nerr = 1\ncpt = 0\nwhile err > self.stopThr and cpt < self.OT_max_iter:\n v = torch.div(b, torch.matmul(K.t(), u) + self.epsilon)\n u = torch.div(a, torch.matmul(K, v) + self.epsilon)\n cpt += 1\n if cpt % 50 == 1:\n bb = torch.mul(v, torch.matmul(K.t(), u))\n err = torch.norm(torch.sum(torch.abs(bb - b), dim=0), p=float('inf'))\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Compute the final transport plan Q using the scaling factors u and v, where Q = diag(u) K diag(v). \n# This provides the solution to the optimization problem in equation (eq:ot-gr), revealing topic relationships, with clamping to ensure numerical stability.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\ntransp = u * (K * v.T)\ntransp = transp.clamp(min=1e-6)\nreturn transp\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details: \n - The LaTeX description does not explicitly clarify that, in the practical implementation of the optimal transport computation, the diagonal elements of the resulting transport plan matrix are not forcibly set to zero after the optimization process. Instead, the workflow involves adjusting the cost matrix by assigning large values to its diagonal entries before the computation begins. This adjustment ensures that the diagonal elements of the transport plan become naturally small during the optimization, satisfying the algorithm's constraints without requiring an additional step to zero them out explicitly.\n - The LaTeX does not mention numerical stabilization steps (e.g., clamping the transport plan to avoid extremely small values) required for practical implementation. The reference code includes a clamp(min=1e-6) operation to ensure numerical stability.\n - There is no description in the LaTeX of the specific convergence checking mechanism used during the Sinkhorn iterations. The reference code periodically evaluates an error metric to decide when to stop iterating, which is a crucial part of the algorithm's workflow.\n \n - Mismatched Details: \n - None.\n", "Missing_details": [ "\n- The LaTeX description does not explicitly clarify that, in the practical implementation of the optimal transport computation, the diagonal elements of the resulting transport plan matrix are not forcibly set to zero after the optimization process. Instead, the workflow involves adjusting the cost matrix by assigning large values to its diagonal entries before the computation begins. This adjustment ensures that the diagonal elements of the transport plan become naturally small during the optimization, satisfying the algorithm's constraints without requiring an additional step to zero them out explicitly.\n", "\n- The LaTeX does not mention numerical stabilization steps (e.g., clamping the transport plan to avoid extremely small values) required for practical implementation. The reference code includes a clamp(min=1e-6) operation to ensure numerical stability.\n", "\n- There is no description in the LaTeX of the specific convergence checking mechanism used during the Sinkhorn iterations. The reference code periodically evaluates an error metric to decide when to stop iterating, which is a crucial part of the algorithm's workflow.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - cost_matrix (torch.Tensor, dtype=torch.float32, shape=[num_topics, num_topics]): The cost matrix C between num_topics topics, where each element represents the transportation cost based on the distance between topic embeddings in Euclidean space.\n - marginals (torch.Tensor, dtype=torch.float32, shape=[num_topics, num_topics]): The matrix P, predefined and normalized such that each row and column sums to 1/num_topics, representing the target marginal distributions for the transport plan.\n\n It also uses the following class attributes:\n - self.sinkhorn_alpha (float): The parameter for entropy regularization, corresponding to 1/\u03b5 in the Sinkhorn algorithm.\n - self.OT_max_iter (int): The maximum number of iterations for the Sinkhorn algorithm.\n - self.stopThr (float): The stopping threshold for Sinkhorn algorithm convergence.\n - self.epsilon (float): A small value to avoid division by zero in the Sinkhorn algorithm.\n", "Arguments_list": [ { "name": "cur_trainset", "string": "\n- cost_matrix (torch.Tensor, dtype=torch.float32, shape=[num_topics, num_topics]): The cost matrix C between num_topics topics, where each element represents the transportation cost based on the distance between topic embeddings in Euclidean space.\n", "dependency": null }, { "name": "in_scope_topic_features", "string": "\n- marginals (torch.Tensor, dtype=torch.float32, shape=[num_topics, num_topics]): The matrix P, predefined and normalized such that each row and column sums to 1/num_topics, representing the target marginal distributions for the transport plan.\n", "dependency": null }, { "name": "self.sinkhorn_alpha", "string": "\n- self.sinkhorn_alpha (float): The parameter for entropy regularization, corresponding to 1/\u03b5 in the Sinkhorn algorithm.\n", "dependency": null }, { "name": "self.OT_max_iter", "string": "\n- self.OT_max_iter (int): The maximum number of iterations for the Sinkhorn algorithm.\n", "dependency": null }, { "name": "self.stopThr", "string": "\n- self.stopThr (float): The stopping threshold for Sinkhorn algorithm convergence.\n", "dependency": null }, { "name": "self.epsilon", "string": "\n- self.epsilon (float): A small value to avoid division by zero in the Sinkhorn algorithm.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra File Dependencies: \n - None\n \n Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.sum\n - torch.ones_like\n - torch.exp\n - torch.div\n - torch.matmul\n - torch.mul\n - torch.abs\n - torch.norm \n", "list": [ "torch.sum", "torch.ones_like", "torch.exp", "torch.div", "torch.matmul", "torch.mul", "torch.abs", "torch.norm" ] }, "Return": { "Return_String": "\nOutput Variables:\n - transp (torch.Tensor, dtype=torch.float32, shape=[num_topics, num_topics]): The computed transport plan Q, which is the solution to the optimal transport problem, representing the relationships between topics.\n", "Return_list": [ { "name": "transp", "string": "\n- transp (torch.Tensor, dtype=torch.float32, shape=[num_topics, num_topics]): The computed transport plan Q, which is the solution to the optimal transport problem, representing the relationships between topics.\n", "dependency": null } ] }, "ori_python_file": "import torch\nfrom torch import nn\n\n\nclass GR(nn.Module):\n \"\"\"\n Group Topic Regularization module that aligns matrix Q with matrix P using KL divergence.\n \n This implements the optimal transport (OT) regularization described in the paper\n to enforce cluster structure on topics.\n \"\"\"\n def __init__(self, weight_loss_GR, sinkhorn_alpha, OT_max_iter=5000, stopThr=.5e-2):\n \"\"\"\n Initialize the Group Topic Regularization module.\n \n Args:\n weight_loss_GR: Weight for the GR loss term\n sinkhorn_alpha: Parameter for entropy regularization (1/entropic reg weight)\n OT_max_iter: Maximum iterations for Sinkhorn algorithm\n stopThr: Stopping threshold for Sinkhorn algorithm convergence\n \"\"\"\n super().__init__()\n \n self.sinkhorn_alpha = sinkhorn_alpha\n self.OT_max_iter = OT_max_iter\n self.weight_loss_GR = weight_loss_GR\n self.stopThr = stopThr\n self.epsilon = 1e-16\n self.transp = None\n\n def compute_optimal_transport(self, cost_matrix, marginals):\n \"\"\"\n Compute the optimal transport plan Q using Sinkhorn algorithm.\n \n Args:\n cost_matrix: KxK cost matrix C between topics\n marginals: Row and column marginals (a and b)\n \n Returns:\n Transport plan matrix Q\n \"\"\"\n device = cost_matrix.device\n \n a = marginals.sum(axis=1).unsqueeze(1).to(device) # Row marginals\n b = marginals.sum(axis=0).unsqueeze(1).to(device) # Column marginals\n \n # Initialize scaling factors\n u = (torch.ones_like(a) / a.size()[0]).to(device)\n \n # Kernel matrix K = exp(-C/lambda)\n K = torch.exp(-cost_matrix * self.sinkhorn_alpha)\n \n # Sinkhorn iterations\n err = 1\n cpt = 0\n while err > self.stopThr and cpt < self.OT_max_iter:\n v = torch.div(b, torch.matmul(K.t(), u) + self.epsilon)\n u = torch.div(a, torch.matmul(K, v) + self.epsilon)\n cpt += 1\n \n # Check convergence periodically\n if cpt % 50 == 1:\n bb = torch.mul(v, torch.matmul(K.t(), u))\n err = torch.norm(torch.sum(torch.abs(bb - b), dim=0), p=float('inf'))\n \n # Final transport plan Q = diag(u) K diag(v)\n transp = u * (K * v.T)\n transp = transp.clamp(min=1e-6)\n \n return transp\n\n def compute_kl_divergence(self, P, Q):\n \"\"\"\n Compute KL divergence KL(P||Q) between matrices P and Q.\n \n Args:\n P: Source distribution matrix\n Q: Target distribution matrix (transport plan)\n \n Returns:\n KL divergence value\n \"\"\"\n return (P * (P.log() - Q.log() - 1) + Q).sum()\n\n def forward(self, cost_matrix, P):\n \"\"\"\n Compute the Group Topic Regularization loss.\n \n Args:\n cost_matrix: KxK cost matrix between topics\n P: Predefined matrix encoding shared information between grouped topics\n \n Returns:\n GR loss value\n \"\"\"\n if self.weight_loss_GR <= 1e-6:\n return 0.\n \n # Move P to the same device as cost matrix\n P = P.to(cost_matrix.device)\n \n # Compute optimal transport plan Q\n Q = self.compute_optimal_transport(cost_matrix, P)\n self.transp = Q # Store for later inspection\n \n # Compute KL divergence between P and Q\n loss_GR = self.compute_kl_divergence(P, Q)\n \n # Apply weight to the loss\n loss_GR *= self.weight_loss_GR\n \n return loss_GR\n" }, { "task_id": 1, "indent": 2, "script": "\npython main.py --use_pretrainWE\n", "latex_code": "\nWe further define $\\mathcal{C}_k$, the set of all observations assigned to class $k$ as $\\mathcal{C}_k = \\{\\phi(x)|a(x)=k\\}$.\n\\textbf{Adaptation.} We now adapt each class embedding by considering both the initial class description and the assigned observations. Concretely, the adapted code for each class is the median of the set containing the embedding of the class descriptions and the embeddings of all assigned observations:\n\\begin{equation}\n z_k = median(\\{\\phi(c_k)\\} \\cup \\mathcal{C}_k)\n % \\vspace{-0.35em}\n\\end{equation}\nWe chose the median and not mean for contamination robustness. Note that this step will not modify the embedding of classes with no observations.\n", "completion_path": "./NeuroMax/NeuroMax.py", "namespace": "NeuroMax.NeuroMax.NeuroMax.create_group_connection_regularizer", "type": "method", "signature_position": [ 71, 71 ], "body_position": [ 72, 96 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: We employ the KMeans clustering method to partition the K topics into G clusters \n# based on their embeddings, leveraging the semantic information preserved from the initial \n# training phases.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nkmean_model = torch_kmeans.KMeans(\n n_clusters=self.num_groups, max_iter=1000, seed=0, verbose=False,\n normalize='unit')\ngroup_id = kmean_model.fit_predict(self.topic_embeddings.reshape(\n 1, self.topic_embeddings.shape[0], self.topic_embeddings.shape[1]))\ngroup_id = group_id.reshape(-1)\nself.group_topic = [[] for _ in range(self.num_groups)]\nfor i in range(self.num_topics):\n self.group_topic[group_id[i]].append(i)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: We establish the matrix \\hat{P} by setting \\hat{P}_{ij} = 1 if topics i and j are \n# in the same cluster, and \\hat{P}_{ij} = u otherwise, where u=1/5 is a fixed value in this \n# implementation.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nself.group_connection_regularizer = torch.ones(\n (self.num_topics, self.num_topics), device=self.topic_embeddings.device) / 5.\nfor i in range(self.num_topics):\n for j in range(self.num_topics):\n if group_id[i] == group_id[j]:\n self.group_connection_regularizer[i][j] = 1\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: We set the diagonal elements to 0 to exclude self-connections, aligning with the \n# constraint in the optimal transport plan Q, and clamp the values to ensure numerical stability.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nself.group_connection_regularizer.fill_diagonal_(0)\nself.group_connection_regularizer = self.group_connection_regularizer.clamp(min=1e-4)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: We perform iterative normalization by normalizing the rows to sum to \\frac{1}{K} and then symmetrizing the matrix by averaging with its transpose, to approximate the desired properties of the matrix P.\n# Return the group connection regularizer matrix P.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nfor _ in range(50):\n self.group_connection_regularizer = self.group_connection_regularizer / \\\n self.group_connection_regularizer.sum(axis=1, keepdim=True) / self.num_topics\n self.group_connection_regularizer = (self.group_connection_regularizer \\\n + self.group_connection_regularizer.T) / 2.\n\nreturn self.group_connection_regularizer\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The LaTeX description does not specify the initial setup of a matrix that captures relationships between topics based on their cluster assignments. In the workflow, after clustering topics into groups, a matrix is initialized where entries are set to a small positive value (e.g., 0.2) for topics not in the same cluster, and a higher value (e.g., 1) for those within the same cluster.\n - There is no mention in the LaTeX of setting the diagonal elements of the matrix to zero to exclude self-connections. In the workflow, after constructing the initial matrix based on cluster assignments, the diagonal entries are explicitly zeroed out to prevent a topic from influencing itself.\n - The LaTeX code lacks a description of the iterative process to refine the matrix after its initial construction. The workflow involves repeatedly normalizing the matrix rows to sum to a specific fraction (e.g., 1 divided by the total number of topics) and then averaging the matrix with its transpose to ensure symmetry. This iterative adjustment, performed over multiple rounds (e.g., 50 times), ensures the matrix meets specific sum constraints and symmetry properties, which are critical for the final result but not mentioned in the LaTeX.\n - Clamping to 1e-4 prevents numerical instability (not in LaTeX).\n\n - Mismatched Details:\n - The LaTeX describes computing an adapted embedding for each class as the median of a set combining the initial class description embedding and the embeddings of assigned observations. However, the reference Python code does not compute a median or directly adapt class embeddings in this way. Instead, it constructs a matrix encoding pairwise relationships between topics based on cluster membership, with values set to 1 for same-cluster topics and a smaller value otherwise, followed by normalization and symmetrization.\n - The LaTeX emphasizes using the median for contamination robustness, implying a focus on outlier resistance in adapting class embeddings. In contrast, the reference Python code achieves robustness differently by clamping matrix values to a small positive minimum and iteratively normalizing, without explicitly using a median operation.\n\n", "Missing_details": [ "\n- The LaTeX description does not specify the initial setup of a matrix that captures relationships between topics based on their cluster assignments. In the workflow, after clustering topics into groups, a matrix is initialized where entries are set to a small positive value (e.g., 0.2) for topics not in the same cluster, and a higher value (e.g., 1) for those within the same cluster.\n", "\n- There is no mention in the LaTeX of setting the diagonal elements of the matrix to zero to exclude self-connections. In the workflow, after constructing the initial matrix based on cluster assignments, the diagonal entries are explicitly zeroed out to prevent a topic from influencing itself.\n", "\n- The LaTeX code lacks a description of the iterative process to refine the matrix after its initial construction. The workflow involves repeatedly normalizing the matrix rows to sum to a specific fraction (e.g., 1 divided by the total number of topics) and then averaging the matrix with its transpose to ensure symmetry. This iterative adjustment, performed over multiple rounds (e.g., 50 times), ensures the matrix meets specific sum constraints and symmetry properties, which are critical for the final result but not mentioned in the LaTeX.\n", "\n- Clamping to 1e-4 prevents numerical instability (not in LaTeX).\n" ], "Mismatched_details": [ " \n- The LaTeX describes computing an adapted embedding for each class as the median of a set combining the initial class description embedding and the embeddings of assigned observations. However, the reference Python code does not compute a median or directly adapt class embeddings in this way. Instead, it constructs a matrix encoding pairwise relationships between topics based on cluster membership, with values set to 1 for same-cluster topics and a smaller value otherwise, followed by normalization and symmetrization.\n", "\n- The LaTeX emphasizes using the median for contamination robustness, implying a focus on outlier resistance in adapting class embeddings. In contrast, the reference Python code achieves robustness differently by clamping matrix values to a small positive minimum and iteratively normalizing, without explicitly using a median operation.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - self: The instance of the class containing the method.\n - self.topic_embeddings (torch.Tensor, shape=[num_topics, embedding_dim]): topic embeddings.\n - self.num_topics (int): total number of topics.\n - self.num_groups (int): total number of groups for clustering.\n", "Arguments_list": [ { "name": "self", "string": "\n- self: The instance of the class containing the method.\n", "dependency": null }, { "name": "self.topic_embeddings", "string": "\n- self.topic_embeddings (torch.Tensor, shape=[num_topics, embedding_dim]): topic embeddings.\n", "dependency": null }, { "name": "self.num_topics", "string": "\n- self.num_topics (int): total number of topics.\n", "dependency": null }, { "name": "self.num_groups", "string": "\n- self.num_groups (int): total number of groups for clustering.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra File Dependencies: \n - NeuroMax.group_connection_regularizer\n - NeuroMax.group_topic\n\n Cross File Dependencies: \n - None\n", "intra_file": [ "NeuroMax.group_connection_regularizer", "NeuroMax.group_topic" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch_kmeans.KMeans\n - torch.ones\n", "list": [ "torch_kmeans.KMeans", "torch.ones" ] }, "Return": { "Return_String": "\nOutput Variables:\n - group_connection_regularizer (torch.Tensor, shape=[num_topics, num_topics]): , representing the normalized matrix P that captures the relationships between topics based on their cluster assignments.\n", "Return_list": [ { "name": "group_connection_regularizer", "string": "\n- group_connection_regularizer (torch.Tensor, shape=[num_topics, num_topics]): , representing the normalized matrix P that captures the relationships between topics based on their cluster assignments.\n", "dependency": null } ] }, "ori_python_file": "import numpy as np\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom .ECR import ECR\nfrom .GR import GR\nimport torch_kmeans\nimport logging\nimport sentence_transformers\n\n\nclass NeuroMax(nn.Module):\n def __init__(self, vocab_size, num_topics=50, num_groups=10, en_units=200, dropout=0.,\n pretrained_WE=None, embed_size=200, beta_temp=0.2,\n weight_loss_ECR=250.0, weight_loss_GR=250.0,\n alpha_GR=20.0, alpha_ECR=20.0, sinkhorn_max_iter=1000,\n weight_loss_InfoNCE=10.0):\n super().__init__()\n\n self.num_topics = num_topics\n self.num_groups = num_groups\n self.beta_temp = beta_temp\n\n self.a = 1 * np.ones((1, num_topics)).astype(np.float32)\n self.mu2 = nn.Parameter(torch.as_tensor(\n (np.log(self.a).T - np.mean(np.log(self.a), 1)).T))\n self.var2 = nn.Parameter(torch.as_tensor(\n (((1.0 / self.a) * (1 - (2.0 / num_topics))).T + (1.0 / (num_topics * num_topics)) * np.sum(1.0 / self.a, 1)).T))\n\n self.mu2.requires_grad = False\n self.var2.requires_grad = False\n\n self.fc11 = nn.Linear(vocab_size, en_units)\n self.fc12 = nn.Linear(en_units, en_units)\n self.fc21 = nn.Linear(en_units, num_topics)\n self.fc22 = nn.Linear(en_units, num_topics)\n self.fc1_dropout = nn.Dropout(dropout)\n self.theta_dropout = nn.Dropout(dropout)\n\n self.mean_bn = nn.BatchNorm1d(num_topics)\n self.mean_bn.weight.requires_grad = False\n self.logvar_bn = nn.BatchNorm1d(num_topics)\n self.logvar_bn.weight.requires_grad = False\n self.decoder_bn = nn.BatchNorm1d(vocab_size, affine=True)\n self.decoder_bn.weight.requires_grad = False\n\n if pretrained_WE is not None:\n self.word_embeddings = torch.from_numpy(pretrained_WE).float()\n else:\n self.word_embeddings = nn.init.trunc_normal_(\n torch.empty(vocab_size, embed_size))\n self.word_embeddings = nn.Parameter(F.normalize(self.word_embeddings))\n\n self.topic_embeddings = torch.empty(\n (num_topics, self.word_embeddings.shape[1]))\n nn.init.trunc_normal_(self.topic_embeddings, std=0.1)\n self.topic_embeddings = nn.Parameter(\n F.normalize(self.topic_embeddings))\n\n self.num_topics_per_group = num_topics // num_groups\n self.ECR = ECR(weight_loss_ECR, alpha_ECR, sinkhorn_max_iter)\n self.GR = GR(weight_loss_GR, alpha_GR, sinkhorn_max_iter)\n self.group_connection_regularizer = None\n\n # for InfoNCE\n self.prj_rep = nn.Sequential(nn.Linear(self.num_topics, 384),\n nn.Dropout(dropout))\n self.prj_bert = nn.Sequential()\n self.weight_loss_InfoNCE = weight_loss_InfoNCE\n\n def create_group_connection_regularizer(self):\n kmean_model = torch_kmeans.KMeans(\n n_clusters=self.num_groups, max_iter=1000, seed=0, verbose=False,\n normalize='unit')\n group_id = kmean_model.fit_predict(self.topic_embeddings.reshape(\n 1, self.topic_embeddings.shape[0], self.topic_embeddings.shape[1]))\n group_id = group_id.reshape(-1)\n self.group_topic = [[] for _ in range(self.num_groups)]\n for i in range(self.num_topics):\n self.group_topic[group_id[i]].append(i)\n\n self.group_connection_regularizer = torch.ones(\n (self.num_topics, self.num_topics), device=self.topic_embeddings.device) / 5.\n for i in range(self.num_topics):\n for j in range(self.num_topics):\n if group_id[i] == group_id[j]:\n self.group_connection_regularizer[i][j] = 1\n self.group_connection_regularizer.fill_diagonal_(0)\n self.group_connection_regularizer = self.group_connection_regularizer.clamp(min=1e-4)\n for _ in range(50):\n self.group_connection_regularizer = self.group_connection_regularizer / \\\n self.group_connection_regularizer.sum(axis=1, keepdim=True) / self.num_topics\n self.group_connection_regularizer = (self.group_connection_regularizer \\\n + self.group_connection_regularizer.T) / 2.\n \n return self.group_connection_regularizer\n\n def get_beta(self):\n dist = self.pairwise_euclidean_distance(\n self.topic_embeddings, self.word_embeddings)\n beta = F.softmax(-dist / self.beta_temp, dim=0)\n return beta\n\n def reparameterize(self, mu, logvar):\n if self.training:\n std = torch.exp(0.5 * logvar)\n eps = torch.randn_like(std)\n return mu + (eps * std)\n else:\n return mu\n\n def get_representation(self, input):\n e1 = F.softplus(self.fc11(input))\n e1 = F.softplus(self.fc12(e1))\n e1 = self.fc1_dropout(e1)\n mu = self.mean_bn(self.fc21(e1))\n logvar = self.logvar_bn(self.fc22(e1))\n z = self.reparameterize(mu, logvar)\n theta = F.softmax(z, dim=1)\n return theta, mu, logvar\n\n def encode(self, input):\n theta, mu, logvar = self.get_representation(input)\n loss_KL = self.compute_loss_KL(mu, logvar)\n return theta, loss_KL\n\n def get_theta(self, input):\n theta, loss_KL = self.encode(input)\n if self.training:\n return theta, loss_KL\n else:\n return theta\n\n def sim(self, rep, bert):\n prep = self.prj_rep(rep)\n pbert = self.prj_bert(bert)\n return torch.exp(F.cosine_similarity(prep, pbert))\n\n def csim(self, bow, bert):\n pbow = self.prj_rep(bow)\n pbert = self.prj_bert(bert)\n csim_matrix = (pbow@pbert.T) / (pbow.norm(keepdim=True,\n dim=-1)@pbert.norm(keepdim=True, dim=-1).T)\n csim_matrix = torch.exp(csim_matrix)\n csim_matrix = csim_matrix / csim_matrix.sum(dim=1, keepdim=True)\n return -csim_matrix.log()\n\n def compute_loss_InfoNCE(self, rep, contextual_emb):\n if self.weight_loss_InfoNCE <= 1e-6:\n return 0.\n else:\n sim_matrix = self.csim(rep, contextual_emb)\n return sim_matrix.diag().mean() * self.weight_loss_InfoNCE\n\n def compute_loss_KL(self, mu, logvar):\n var = logvar.exp()\n var_division = var / self.var2\n diff = mu - self.mu2\n diff_term = diff * diff / self.var2\n logvar_division = self.var2.log() - logvar\n # KLD: N*K\n KLD = 0.5 * ((var_division + diff_term +\n logvar_division).sum(axis=1) - self.num_topics)\n KLD = KLD.mean()\n return KLD\n\n def get_loss_ECR(self):\n cost = self.pairwise_euclidean_distance(\n self.topic_embeddings, self.word_embeddings)\n loss_ECR = self.ECR(cost)\n return loss_ECR\n\n def get_loss_GR(self):\n cost = self.pairwise_euclidean_distance(\n self.topic_embeddings, self.topic_embeddings) + 1e1 * torch.ones(self.num_topics, self.num_topics).cuda()\n loss_GR = self.GR(cost, self.group_connection_regularizer)\n return loss_GR\n\n def pairwise_euclidean_distance(self, x, y):\n cost = torch.sum(x ** 2, axis=1, keepdim=True) + \\\n torch.sum(y ** 2, dim=1) - 2 * torch.matmul(x, y.t())\n return cost\n\n def forward(self, input, epoch_id=None):\n bow = input[\"data\"]\n contextual_emb = input[\"contextual_embed\"]\n\n rep, mu, logvar = self.get_representation(bow)\n loss_KL = self.compute_loss_KL(mu, logvar)\n theta = rep\n # theta, loss_KL = self.encode(bow)\n beta = self.get_beta()\n\n recon = F.softmax(self.decoder_bn(torch.matmul(theta, beta)), dim=-1)\n recon_loss = -(bow * recon.log()).sum(axis=1).mean()\n\n loss_TM = recon_loss + loss_KL\n\n loss_ECR = self.get_loss_ECR()\n loss_InfoNCE = self.compute_loss_InfoNCE(rep, contextual_emb)\n if epoch_id == 10 and self.group_connection_regularizer is None:\n group_connection_regularizer = self.create_group_connection_regularizer()\n if self.group_connection_regularizer is not None and epoch_id > 10:\n loss_GR = self.get_loss_GR()\n else:\n loss_GR = 0.\n\n loss = loss_TM + loss_ECR + loss_GR + loss_InfoNCE\n\n rst_dict = {\n 'loss': loss,\n 'loss_TM': loss_TM,\n 'loss_ECR': loss_ECR,\n 'loss_GR': loss_GR,\n 'loss_InfoNCE': loss_InfoNCE,\n }\n\n return rst_dict\n" }, { "task_id": 2, "indent": 2, "completion_path": "./NeuroMax/NeuroMax.py", "script": "\npython main.py --use_pretrainWE\n", "latex_code": "\nOur inference process and topic modeling loss function follow the conventional neural topic model, as noted in Section \\ref{section:background-ntm}. Additionally, inspired by \\cite{wu2023effective}, we employ the Embedding Clustering Regularization regularizer to mitigate the topic collapsing problem:\n\\begin{equation} \\label{eq:ecr}\n\\begin{split}\n &\\mathcal{L}_{\\mathrm{ECR}} = \\sum_{i=1}^V \\sum_{j=1}^K \\Vert \\mathbf{w}_i-\\mathbf{t}_j \\Vert^2 \\pi^*_{ij}\n\\end{split}\n\\end{equation}\nwhere $\\pi^*$ is the solution of the following optimization problem:\n\\begin{equation} \\label{eq:ot-ecr}\n\\begin{split}\n \\text{minimize} & \\ \\langle C_{\\mathrm{WT}}, \\pi \\rangle - \\nu H(\\pi) \\\\\n \\text{s.t.} & \\ \\pi \\in \\mathbb{R}^{V\\times K} \\\\\n & \\ \\pi \\mathds{1}_K = \\frac{1}{V} \\mathds{1}_V, \\pi^T \\mathds{1}_V = \\frac{1}{K} \\mathds{1}_K \\\\\n\\end{split}\n\\end{equation}\nwhere $C_{\\mathrm{WT}} \\in \\mathbb{R}^{V \\times K}$ is the distance matrix between word embeddings and topic embeddings. $\\pi^*$ is obtained using the Sinkhorn algorithm \\cite{2013sinkhorn}.\n", "namespace": "NeuroMax.NeuroMax.NeuroMax.get_loss_ECR", "type": "method", "signature_position": [ 167, 167 ], "body_position": [ 168, 171 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Compute the cost matrix C_WT, which is the pairwise squared Euclidean\n# distance between topic embeddings and word embeddings. This corresponds to\n# C_WT in equation (6) of the LaTeX code, serving as the foundation for the\n# optimal transport problem to determine \u03c0*.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\ncost = self.pairwise_euclidean_distance(self.topic_embeddings, self.word_embeddings)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Compute the ECR loss by passing the cost matrix to the ECR object,\n# which solves the optimal transport problem from equation (6) to obtain \u03c0*,\n# then calculates the loss as defined in equation (5). The result is returned\n# as the regularization term.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nloss_ECR = self.ECR(cost)\nreturn loss_ECR\n# [End Snippet 2]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - None\n\n - Mismatched Details: \n - None\n", "Missing_details": [], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - self (NeuroMax): The instance of the NeuroMax class.\n - self.topic_embeddings (torch.Tensor, dtype=torch.float32, shape=[num_topics, embedding_dim]): Tensor of topic embeddings, representing K topics.\n - self.word_embeddings (torch.Tensor, dtype=torch.float32, shape=[vocab_size, embedding_dim]): Tensor of word embeddings, representing V words.\n", "Arguments_list": [ { "name": "self", "string": "- self (NeuroMax): The instance of the NeuroMax class.", "dependency": null }, { "name": "self.topic_embeddings", "string": "- self.topic_embeddings (torch.Tensor, dtype=torch.float32, shape=[num_topics, embedding_dim]): Tensor of topic embeddings, representing K topics.", "dependency": null }, { "name": "self.word_embeddings", "string": "- self.word_embeddings (torch.Tensor, dtype=torch.float32, shape=[vocab_size, embedding_dim]): Tensor of word embeddings, representing V words.", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra File Dependencies:\n - NeuroMax.pairwise_euclidean_distance\n - NeuroMax.ECR\n \n - Cross File Dependencies:\n - None\n", "intra_file": [ "NeuroMax.pairwise_euclidean_distance", "NeuroMax.ECR" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - None \n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - loss_ECR (torch.Tensor, shape=[]): The scalar ECR loss value, representing the regularization term to prevent topic collapsing.\n", "Return_list": [ { "name": "loss_ECR", "string": "- loss_ECR (torch.Tensor, shape=[]): The scalar ECR loss value, representing the regularization term to prevent topic collapsing.", "dependency": null } ] }, "ori_python_file": "import numpy as np\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom .ECR import ECR\nfrom .GR import GR\nimport torch_kmeans\nimport logging\nimport sentence_transformers\n\n\nclass NeuroMax(nn.Module):\n def __init__(self, vocab_size, num_topics=50, num_groups=10, en_units=200, dropout=0.,\n pretrained_WE=None, embed_size=200, beta_temp=0.2,\n weight_loss_ECR=250.0, weight_loss_GR=250.0,\n alpha_GR=20.0, alpha_ECR=20.0, sinkhorn_max_iter=1000,\n weight_loss_InfoNCE=10.0):\n super().__init__()\n\n self.num_topics = num_topics\n self.num_groups = num_groups\n self.beta_temp = beta_temp\n\n self.a = 1 * np.ones((1, num_topics)).astype(np.float32)\n self.mu2 = nn.Parameter(torch.as_tensor(\n (np.log(self.a).T - np.mean(np.log(self.a), 1)).T))\n self.var2 = nn.Parameter(torch.as_tensor(\n (((1.0 / self.a) * (1 - (2.0 / num_topics))).T + (1.0 / (num_topics * num_topics)) * np.sum(1.0 / self.a, 1)).T))\n\n self.mu2.requires_grad = False\n self.var2.requires_grad = False\n\n self.fc11 = nn.Linear(vocab_size, en_units)\n self.fc12 = nn.Linear(en_units, en_units)\n self.fc21 = nn.Linear(en_units, num_topics)\n self.fc22 = nn.Linear(en_units, num_topics)\n self.fc1_dropout = nn.Dropout(dropout)\n self.theta_dropout = nn.Dropout(dropout)\n\n self.mean_bn = nn.BatchNorm1d(num_topics)\n self.mean_bn.weight.requires_grad = False\n self.logvar_bn = nn.BatchNorm1d(num_topics)\n self.logvar_bn.weight.requires_grad = False\n self.decoder_bn = nn.BatchNorm1d(vocab_size, affine=True)\n self.decoder_bn.weight.requires_grad = False\n\n if pretrained_WE is not None:\n self.word_embeddings = torch.from_numpy(pretrained_WE).float()\n else:\n self.word_embeddings = nn.init.trunc_normal_(\n torch.empty(vocab_size, embed_size))\n self.word_embeddings = nn.Parameter(F.normalize(self.word_embeddings))\n\n self.topic_embeddings = torch.empty(\n (num_topics, self.word_embeddings.shape[1]))\n nn.init.trunc_normal_(self.topic_embeddings, std=0.1)\n self.topic_embeddings = nn.Parameter(\n F.normalize(self.topic_embeddings))\n\n self.num_topics_per_group = num_topics // num_groups\n self.ECR = ECR(weight_loss_ECR, alpha_ECR, sinkhorn_max_iter)\n self.GR = GR(weight_loss_GR, alpha_GR, sinkhorn_max_iter)\n self.group_connection_regularizer = None\n\n # for InfoNCE\n self.prj_rep = nn.Sequential(nn.Linear(self.num_topics, 384),\n nn.Dropout(dropout))\n self.prj_bert = nn.Sequential()\n self.weight_loss_InfoNCE = weight_loss_InfoNCE\n\n def create_group_connection_regularizer(self):\n kmean_model = torch_kmeans.KMeans(\n n_clusters=self.num_groups, max_iter=1000, seed=0, verbose=False,\n normalize='unit')\n group_id = kmean_model.fit_predict(self.topic_embeddings.reshape(\n 1, self.topic_embeddings.shape[0], self.topic_embeddings.shape[1]))\n group_id = group_id.reshape(-1)\n self.group_topic = [[] for _ in range(self.num_groups)]\n for i in range(self.num_topics):\n self.group_topic[group_id[i]].append(i)\n\n self.group_connection_regularizer = torch.ones(\n (self.num_topics, self.num_topics), device=self.topic_embeddings.device) / 5.\n for i in range(self.num_topics):\n for j in range(self.num_topics):\n if group_id[i] == group_id[j]:\n self.group_connection_regularizer[i][j] = 1\n self.group_connection_regularizer.fill_diagonal_(0)\n self.group_connection_regularizer = self.group_connection_regularizer.clamp(min=1e-4)\n for _ in range(50):\n self.group_connection_regularizer = self.group_connection_regularizer / \\\n self.group_connection_regularizer.sum(axis=1, keepdim=True) / self.num_topics\n self.group_connection_regularizer = (self.group_connection_regularizer \\\n + self.group_connection_regularizer.T) / 2.\n \n return self.group_connection_regularizer\n\n def get_beta(self):\n dist = self.pairwise_euclidean_distance(\n self.topic_embeddings, self.word_embeddings)\n beta = F.softmax(-dist / self.beta_temp, dim=0)\n return beta\n\n def reparameterize(self, mu, logvar):\n if self.training:\n std = torch.exp(0.5 * logvar)\n eps = torch.randn_like(std)\n return mu + (eps * std)\n else:\n return mu\n\n def get_representation(self, input):\n e1 = F.softplus(self.fc11(input))\n e1 = F.softplus(self.fc12(e1))\n e1 = self.fc1_dropout(e1)\n mu = self.mean_bn(self.fc21(e1))\n logvar = self.logvar_bn(self.fc22(e1))\n z = self.reparameterize(mu, logvar)\n theta = F.softmax(z, dim=1)\n return theta, mu, logvar\n\n def encode(self, input):\n theta, mu, logvar = self.get_representation(input)\n loss_KL = self.compute_loss_KL(mu, logvar)\n return theta, loss_KL\n\n def get_theta(self, input):\n theta, loss_KL = self.encode(input)\n if self.training:\n return theta, loss_KL\n else:\n return theta\n\n def sim(self, rep, bert):\n prep = self.prj_rep(rep)\n pbert = self.prj_bert(bert)\n return torch.exp(F.cosine_similarity(prep, pbert))\n\n def csim(self, bow, bert):\n pbow = self.prj_rep(bow)\n pbert = self.prj_bert(bert)\n csim_matrix = (pbow@pbert.T) / (pbow.norm(keepdim=True,\n dim=-1)@pbert.norm(keepdim=True, dim=-1).T)\n csim_matrix = torch.exp(csim_matrix)\n csim_matrix = csim_matrix / csim_matrix.sum(dim=1, keepdim=True)\n return -csim_matrix.log()\n\n def compute_loss_InfoNCE(self, rep, contextual_emb):\n if self.weight_loss_InfoNCE <= 1e-6:\n return 0.\n else:\n sim_matrix = self.csim(rep, contextual_emb)\n return sim_matrix.diag().mean() * self.weight_loss_InfoNCE\n\n def compute_loss_KL(self, mu, logvar):\n var = logvar.exp()\n var_division = var / self.var2\n diff = mu - self.mu2\n diff_term = diff * diff / self.var2\n logvar_division = self.var2.log() - logvar\n # KLD: N*K\n KLD = 0.5 * ((var_division + diff_term +\n logvar_division).sum(axis=1) - self.num_topics)\n KLD = KLD.mean()\n return KLD\n\n def get_loss_ECR(self):\n cost = self.pairwise_euclidean_distance(\n self.topic_embeddings, self.word_embeddings)\n loss_ECR = self.ECR(cost)\n return loss_ECR\n\n def get_loss_GR(self):\n cost = self.pairwise_euclidean_distance(\n self.topic_embeddings, self.topic_embeddings) + 1e1 * torch.ones(self.num_topics, self.num_topics).cuda()\n loss_GR = self.GR(cost, self.group_connection_regularizer)\n return loss_GR\n\n def pairwise_euclidean_distance(self, x, y):\n cost = torch.sum(x ** 2, axis=1, keepdim=True) + \\\n torch.sum(y ** 2, dim=1) - 2 * torch.matmul(x, y.t())\n return cost\n\n def forward(self, input, epoch_id=None):\n bow = input[\"data\"]\n contextual_emb = input[\"contextual_embed\"]\n\n rep, mu, logvar = self.get_representation(bow)\n loss_KL = self.compute_loss_KL(mu, logvar)\n theta = rep\n # theta, loss_KL = self.encode(bow)\n beta = self.get_beta()\n\n recon = F.softmax(self.decoder_bn(torch.matmul(theta, beta)), dim=-1)\n recon_loss = -(bow * recon.log()).sum(axis=1).mean()\n\n loss_TM = recon_loss + loss_KL\n\n loss_ECR = self.get_loss_ECR()\n loss_InfoNCE = self.compute_loss_InfoNCE(rep, contextual_emb)\n if epoch_id == 10 and self.group_connection_regularizer is None:\n group_connection_regularizer = self.create_group_connection_regularizer()\n if self.group_connection_regularizer is not None and epoch_id > 10:\n loss_GR = self.get_loss_GR()\n else:\n loss_GR = 0.\n\n loss = loss_TM + loss_ECR + loss_GR + loss_InfoNCE\n\n rst_dict = {\n 'loss': loss,\n 'loss_TM': loss_TM,\n 'loss_ECR': loss_ECR,\n 'loss_GR': loss_GR,\n 'loss_InfoNCE': loss_InfoNCE,\n }\n\n return rst_dict\n" } ] }, { "paper_id": 28, "paper_details": { "title": "Bridging Local Details and Global Context in Text-Attributed Graphs", "url": "https://arxiv.org/abs/2406.12608" }, "repo_original_url": "https://github.com/wykk00/GraphBridge/tree/master", "project_path": "Benchmark/28-Bridging/GraphBridge-master", "enviorment_name": "bridging", "file_organization": "\nGraphBridge-master/\n README.md\n env.sh\n train_gnn.py\n train_lm.py\n train_reduction.py\n\n data/\n dataset.py\n load.py\n sampling.py\n data_utils/\n __init__.py\n load_arxiv_2023.py\n load_arxiv.py\n load_citeseer.py\n load_cora.py\n load_photo.py\n load_products.py\n load_wikics.py\n\n models/\n GNNs/\n GCN.py\n SAGE.py\n SGC.py\n __init__.py\n LMs/\n model.py\n __init__.py\n Reduction/\n model.py\n __init__.py\n\n out/\n raw_emb/\n roberta-base/\n citeseer.pt\n\n preprocessed_data/\n new/\n citeseer_random_sbert.pt\n photo.pt\n wikics_fixed_sbert.pt\n\n utils/\n args.py\n dist.py\n metrics.py\n peft.py\n register.py\n sampling.py\n time.py\n utils.py\n __init__.py\n", "latex_code_path": "Benchmark/28-Bridging/arXiv-2406.12608v2", "task_details": [ { "task_id": 0, "indent": 1, "script": "\npython train_reduction.py --dataset citeseer --reduction_lm_type roberta-base --lr 1e-3 --batch_size 256 --epochs 100 --earlystop --patience 10 --hops 2\n", "completion_path": "./models/Reduction/model.py", "latex_code": "\n\\paragraph{Graph-Enhanced Importance Score.} \nTo measure the importance of each token, we define a graph-enhanced importance score calculated through a well designed cross-attention module, that quantifies the significance of each token utilizing both textual and structural information. Specifically, for each node \\(i\\), the query is derived from the message passing output of neighboring nodes, while the key and value come from the node's own textual token embedding. The importance score is calculated as follows: \n\n\\begin{equation}\n \\text{Score}_i=\\sigma\\left(\\frac{\\left( {z}_i^{(l)}W_{q}\\right)\\left({E}_iW_{k}\\right)^{T}}{\\sqrt{d}}\\right),\n\\end{equation}\n\nwhere \\(W_{q},W_{k}\\in\\mathbb{R}^{d \\times d^\\prime}\\) are the parameter matrices for the query and key, and \\(\\sigma\\) denotes the softmax function. A top-k function is then used to select the \\(k^\\prime\\) most crucial tokens.\n", "namespace": "models.Reduction.model.compute_attention_score", "type": "function", "signature_position": [ 5, 5 ], "body_position": [ 6, 10 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Prepare the attention mask to mask out padding tokens by setting\n# large negative values for masked positions. This ensures that padding tokens\n# do not influence the final importance scores, a practical necessity not\n# explicitly described in the LaTeX code.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nattention_mask = (1.0 - attention_mask) * -10000.0\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Compute the raw attention scores by performing a dot product\n# between the query and the key (transposed). This corresponds to the term\n# \\(\\left( z_i^{(l)} W_q \\right) \\left( E_i W_k \\right)^T\\) in the LaTeX\n# description, capturing the alignment between structural and textual information.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nscore = query.matmul(key.transpose(1, 2)).squeeze()\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Apply the attention mask to the raw scores to neglect padding\n# tokens. This step ensures that only valid tokens contribute to the final\n# scores, an enhancement to the LaTeX description for handling real-world data.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nscore = score + attention_mask\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Scale the scores by the square root of the hidden dimension and\n# apply the softmax function to obtain the final importance scores. This\n# corresponds to \\(\\sigma\\left(\\frac{\\left( z_i^{(l)} W_q \\right) \\left( E_i W_k \\right)^T}{\\sqrt{d}}\\right)\\)\n# in the LaTeX description, where \\(\\sigma\\) is the softmax function, normalizing\n# the scores across tokens.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nscore = torch.nn.functional.softmax(score / math.sqrt(hidden_dim), -1)\n\nreturn score\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The LaTeX description does not specify how to handle padding tokens in the input sequence. The reference code includes a step to create an attention mask. This mask is then used to assign large negative values to the attention scores corresponding to padding tokens. This ensures that padding tokens have minimal influence on the final softmax output, effectively excluding them from the attention mechanism. The process involves creating a mask where non-padding tokens are marked, and then modifying the raw attention scores by adding large negative values based on this mask, before the softmax calculation.\n\n - Mismatched Details:\n - There is an inconsistency in the order of operations. The reference code first computes the dot product, then adds the attention mask to the raw scores, and finally scales the result by the square root of the hidden dimension before applying the softmax. The LaTeX, however, presents the scaling as an integral part of the softmax function without clarifying the intermediate masking step. This ordering discrepancy can alter the numerical outcomes.\n", "Missing_details": [ "\n- The LaTeX description does not specify how to handle padding tokens in the input sequence. The reference code includes a step to create an attention mask. This mask is then used to assign large negative values to the attention scores corresponding to padding tokens. This ensures that padding tokens have minimal influence on the final softmax output, effectively excluding them from the attention mechanism. The process involves creating a mask where non-padding tokens are marked, and then modifying the raw attention scores by adding large negative values based on this mask, before the softmax calculation.\n" ], "Mismatched_details": [ "\n- There is an inconsistency in the order of operations. The reference code first computes the dot product, then adds the attention mask to the raw scores, and finally scales the result by the square root of the hidden dimension before applying the softmax. The LaTeX, however, presents the scaling as an integral part of the softmax function without clarifying the intermediate masking step. This ordering discrepancy can alter the numerical outcomes.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - query (torch.Tensor, shape=[batch_size, 1, hidden_dim]): The query tensor, derived from the message-passing output of neighboring nodes, i.e., \\(z_i^{(l)} W_q\\).\n - key (torch.Tensor, shape=[batch_size, seq_length, hidden_dim]): The key tensor, derived from the node's own textual token embeddings, i.e., \\(E_i W_k\\).\n - attention_mask (torch.Tensor, shape=[batch_size, seq_length]): A mask indicating valid tokens (1) and padding tokens (0).\n - hidden_dim (int): The dimension of the hidden space after projection, i.e., \\(d'\\).\n", "Arguments_list": [ { "name": "query", "string": "\n- query (torch.Tensor, shape=[batch_size, 1, hidden_dim]): The query tensor, derived from the message-passing output of neighboring nodes, i.e., \\(z_i^{(l)} W_q\\).\n", "dependency": null }, { "name": "key", "string": "\n- key (torch.Tensor, shape=[batch_size, seq_length, hidden_dim]): The key tensor, derived from the node's own textual token embeddings, i.e., \\(E_i W_k\\).\n", "dependency": null }, { "name": "attention_mask", "string": "\n- attention_mask (torch.Tensor, shape=[batch_size, seq_length]): A mask indicating valid tokens (1) and padding tokens (0).\n", "dependency": null }, { "name": "hidden_dim", "string": "\n- hidden_dim (int): The dimension of the hidden space after projection, i.e., \\(d'\\).\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra File Dependencies: \n - None\n \n Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.nn.functional.softmax\n - math.sqrt\n", "list": [ "torch.nn.functional.softmax", "math.sqrt" ] }, "Return": { "Return_String": "\nOutput Variables:\n - score (torch.Tensor, shape=[batch_size, seq_length]): The importance scores for each token in the sequence.\n", "Return_list": [ { "name": "score", "string": "\n- score (torch.Tensor, shape=[batch_size, seq_length]): The importance scores for each token in the sequence.\n", "dependency": null } ] }, "ori_python_file": "import torch\nimport torch.nn as nn\nimport math\n\ndef compute_attention_score(query, key, attention_mask, hidden_dim):\n attention_mask = (1.0 - attention_mask) * -10000.0\n score = query.matmul(key.transpose(1, 2)).squeeze()\n score = score + attention_mask\n score = torch.nn.functional.softmax(score / math.sqrt(hidden_dim), -1)\n return score\n\nclass ReductionModel(nn.Module):\n def __init__(self, num_classes, input_dim, hidden_dim=64, dropout=0.1):\n super(ReductionModel, self).__init__()\n \n self.dropout = torch.nn.Dropout(p=dropout)\n # reduction model\n self.reduction_model = nn.ModuleList()\n self.key = nn.Linear(input_dim, hidden_dim)\n self.query = nn.Linear(input_dim, hidden_dim)\n \n # classifier\n self.classifier = nn.Linear(input_dim, num_classes)\n self.hidden_dim = hidden_dim\n self.criterion = torch.nn.CrossEntropyLoss()\n \n def inference(self, x, neighbor_embeddings, attention_mask) -> torch.Tensor:\n \"\"\"\n We only need token score while infering\n \"\"\"\n query = self.query(x)\n key = self.key(neighbor_embeddings)\n key = key.unsqueeze(1)\n \n # Use the refactored function to compute scores\n score = compute_attention_score(query, key, attention_mask, x.size(-1))\n \n return score\n \n def aggregate_and_classify(self, x, attention_scores, labels):\n scores = attention_scores.unsqueeze(-1)\n expand_score = self.dropout(scores)\n expand_score = expand_score.expand_as(x)\n weighted_tokens = x * expand_score\n aggregated_representation = weighted_tokens.sum(1)\n out = self.classifier(aggregated_representation)\n loss = self.criterion(out, labels) \n return out, loss\n \n def forward(self, x, neighbor_embeddings, attention_mask, labels):\n \"\"\"\n x : [b, s, d] - Token embeddings (E_i)\n neighbor_embeddings : [b, d] - Graph neighborhood information\n attention_mask: Mask for valid tokens\n labels: Ground truth labels\n \"\"\"\n query = self.query(x)\n key = self.key(neighbor_embeddings)\n key = key.unsqueeze(1)\n \n # Use the refactored function to compute scores\n score = compute_attention_score(query, key, attention_mask, x.size(-1))\n \n # Use the combined method for token aggregation and classification\n out, loss = self.aggregate_and_classify(x, score, labels)\n \n return out, score, loss" }, { "task_id": 1, "indent": 2, "script": "\npython train_reduction.py --dataset citeseer --reduction_lm_type roberta-base --lr 1e-3 --batch_size 256 --epochs 100 --earlystop --patience 10 --hops 2\n", "latex_code": "\n\\paragraph{Optimizing Importance Score.}\nThe supervisory signals derived from downstream tasks provide valuable guidance, allowing the attention module to select informative tokens more effectively. Specifically, during the training phase, we aggregate the token representations using \\(\\text{Score}_i\\), which can be formulated as:\n\\begin{equation}\n s_i = \\text{Score}_i{E}_i,\n\\end{equation}\nwhere \\(s_i\\in\\mathbb{R}^{1\\times d}\\) denotes the weighted summation of text features using attention score. Observe that \\(E_i\\) can be directly regarded as the value matrix, because we set the value parameter matrix as the identity matrix \\(I\\) here for efficiency. Finally, \\(s_i\\) is fed into a linear classifier $\\mathcal{C}$ for prediction. The training loss $\\mathcal{L}_{\\text{down}}$ is computed using the cross-entropy loss $\\operatorname{CE}(\\cdot,\\cdot)$ between the prediction and true label for the target node $i$:\n\\begin{equation}\n \\mathcal{L}_{\\text{down}}=\\mathbb{E}_{i \\in \\mathcal{V}_{L}}\\operatorname{CE}(\\hat{y}_i\\vert \\mathcal{C}_i(s_i),y_i).\n\\end{equation}\nNote that, only the attention module and the classifier are trained while keeping the PLM frozen for efficiency.\n", "completion_path": "./models/Reduction/model.py", "namespace": "models.Reduction.model.ReductionModel.aggregate_and_classify", "type": "method", "signature_position": [ 40, 40 ], "body_position": [ 41, 48 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Compute the aggregated representation s_i by weighting the token embeddings with the importance scores.\n# This implements s_i = Score_i E_i, where Score_i is the attention score vector and E_i is the token embeddings matrix, producing a weighted sum of token features.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nscores = attention_scores.unsqueeze(-1)\nexpand_score = self.dropout(scores)\nexpand_score = expand_score.expand_as(x)\nweighted_tokens = x * expand_score\naggregated_representation = weighted_tokens.sum(1)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Apply the classifier to the aggregated representation to obtain predictions.\n# This corresponds to feeding s_i into the linear classifier C, as in C(s_i), to generate the predicted logits for node classification.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nout = self.classifier(aggregated_representation)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Compute the cross-entropy loss between the predictions and the true labels.\n# This implements the loss term L_down = E_{i in V_L} CE(y\u0302_i, y_i), where y\u0302_i is the prediction from C(s_i) and y_i is the true label, with the expectation approximated over the batch.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nloss = self.criterion(out, labels)\n# [End Snippet 3]\n\nreturn out, loss\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details: \n - The Python code applies dropout to the attention scores for regularization, which is not mentioned in the provided LaTeX snippet.\n \n - Mismatched Details: \n - The LaTeX equation \\( s_i = \\text{Score}_i{E}_i \\) suggests a direct matrix multiplication between scores and embeddings. However, the reference code implements this as an element-wise multiplication followed by summation, which assumes broadcasting and aggregation rather than a strict matrix product.\n", "Missing_details": [ "\n- The Python code applies dropout to the attention scores for regularization, which is not mentioned in the provided LaTeX snippet.\n" ], "Mismatched_details": [ "\n- The LaTeX equation \\( s_i = \\text{Score}_i{E}_i \\) suggests a direct matrix multiplication between scores and embeddings. However, the reference code implements this as an element-wise multiplication followed by summation, which assumes broadcasting and aggregation rather than a strict matrix product.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - self: Instance of the ReductionModel class, containing model parameters and modules.\n - x (torch.Tensor, shape=[batch_size, seq_length, embedding_dim]): Token embeddings for the nodes in the batch, representing E_i in the LaTeX.\n - attention_scores (torch.Tensor, shape=[batch_size, seq_length]): Importance scores for each token, corresponding to Score_i in the LaTeX, used to weight the token embeddings.\n - labels (torch.Tensor, shape=[batch_size], dtype=torch.long): True class labels for the nodes in the batch.\n\n", "Arguments_list": [ { "name": "self", "string": "\n- self: Instance of the ReductionModel class, containing model parameters and modules.\n", "dependency": null }, { "name": "x", "string": "\n- x (torch.Tensor, shape=[batch_size, seq_length, embedding_dim]): Token embeddings for the nodes in the batch, representing E_i in the LaTeX.\n", "dependency": null }, { "name": "attention_scores", "string": "\n- attention_scores (torch.Tensor, shape=[batch_size, seq_length]): Importance scores for each token, corresponding to Score_i in the LaTeX, used to weight the token embeddings.\n", "dependency": null }, { "name": "labels", "string": "\n- labels (torch.Tensor, shape=[batch_size], dtype=torch.long): True class labels for the nodes in the batch.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-file Dependencies: \n - ReductionModel.dropout,\n - ReductionModel.classifier\n - ReductionModel.criterion\n\n - Cross-file Dependencies: \n - None\n", "intra_file": [ "ReductionModel.dropout", "ReductionModel.classifier", "ReductionModel.criterion" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs: \n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - out (torch.Tensor, shape=[batch_size, num_classes]): Logits or predictions from the classifier, representing the output of C(s_i).\n - loss (torch.Tensor, scalar): The cross-entropy loss for the batch, corresponding to L_down.\n", "Return_list": [ { "name": "out", "string": "\n- out (torch.Tensor, shape=[batch_size, num_classes]): Logits or predictions from the classifier, representing the output of C(s_i).\n", "dependency": null }, { "name": "loss", "string": "\n- loss (torch.Tensor, scalar): The cross-entropy loss for the batch, corresponding to L_down.\n", "dependency": null } ] }, "ori_python_file": "import torch\nimport torch.nn as nn\nimport math\n\ndef compute_attention_score(query, key, attention_mask, hidden_dim):\n attention_mask = (1.0 - attention_mask) * -10000.0\n score = query.matmul(key.transpose(1, 2)).squeeze()\n score = score + attention_mask\n score = torch.nn.functional.softmax(score / math.sqrt(hidden_dim), -1)\n return score\n\nclass ReductionModel(nn.Module):\n def __init__(self, num_classes, input_dim, hidden_dim=64, dropout=0.1):\n super(ReductionModel, self).__init__()\n \n self.dropout = torch.nn.Dropout(p=dropout)\n # reduction model\n self.reduction_model = nn.ModuleList()\n self.key = nn.Linear(input_dim, hidden_dim)\n self.query = nn.Linear(input_dim, hidden_dim)\n \n # classifier\n self.classifier = nn.Linear(input_dim, num_classes)\n self.hidden_dim = hidden_dim\n self.criterion = torch.nn.CrossEntropyLoss()\n \n def inference(self, x, neighbor_embeddings, attention_mask) -> torch.Tensor:\n \"\"\"\n We only need token score while infering\n \"\"\"\n query = self.query(x)\n key = self.key(neighbor_embeddings)\n key = key.unsqueeze(1)\n \n # Use the refactored function to compute scores\n score = compute_attention_score(query, key, attention_mask, x.size(-1))\n \n return score\n \n def aggregate_and_classify(self, x, attention_scores, labels):\n scores = attention_scores.unsqueeze(-1)\n expand_score = self.dropout(scores)\n expand_score = expand_score.expand_as(x)\n weighted_tokens = x * expand_score\n aggregated_representation = weighted_tokens.sum(1)\n out = self.classifier(aggregated_representation)\n loss = self.criterion(out, labels) \n return out, loss\n \n def forward(self, x, neighbor_embeddings, attention_mask, labels):\n \"\"\"\n x : [b, s, d] - Token embeddings (E_i)\n neighbor_embeddings : [b, d] - Graph neighborhood information\n attention_mask: Mask for valid tokens\n labels: Ground truth labels\n \"\"\"\n query = self.query(x)\n key = self.key(neighbor_embeddings)\n key = key.unsqueeze(1)\n \n # Use the refactored function to compute scores\n score = compute_attention_score(query, key, attention_mask, x.size(-1))\n \n # Use the combined method for token aggregation and classification\n out, loss = self.aggregate_and_classify(x, score, labels)\n \n return out, score, loss" }, { "task_id": 2, "indent": 1, "completion_path": "./train_reduction.py", "script": "\npython train_reduction.py --dataset citeseer --reduction_lm_type roberta-base --lr 1e-3 --batch_size 256 --epochs 100 --earlystop --patience 10 --hops 2\n", "latex_code": "\n\\paragraph{Regularization.} \nThrough our empirical study, we discovered that the importance score for the majority of nodes deteriorates when solely optimizing $\\mathcal{L}_{\\text{down}}$, as depicted in Figure~\\ref{fig:reg_dist}. We hypothesize that this phenomenon is due to overfitting on the limited set of training nodes. Consequently, most nodes tend to converge on a single token with an excessively high importance score (\\emph{e.g.}, 0.99), thereby hindering the selection of multiple informative tokens and inhibiting exploration. To mitigate this phenomenon, \nwe introduce a regularization term. This term penalizes the network when certain tokens receive disproportionately high importance scores, achieved with a KL-divergence loss:\n\\begin{equation}\n \\mathcal{L}_{\\text{reg}} = \\mathbb{E}_{i \\in \\mathcal{V}_{L}}D_{\\text{KL}}(U\\vert \\vert\\text{Score}_i),\n\\end{equation}\nwhere \\(U\\) is an uniform distribution.\n", "namespace": "train_reduction.compute_regularization_loss", "type": "function", "signature_position": [ 53, 53 ], "body_position": [ 54, 62 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Create a uniform distribution over the valid tokens for each node\n# by normalizing the attention mask. This corresponds to the uniform distribution\n# U in the LaTeX code, where U is uniform over the tokens of each node, with the\n# Python code clarifying that it applies only to valid tokens.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nuniform_distribution = attention_mask / attention_mask.sum(1, keepdim=True)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Compute the KL divergence between the uniform distribution and the\n# attention scores for each node in the batch, using PyTorch's kl_div function.\n# This implements D_{KL}(U || Score_i) for each node i in the batch, and the\n# reduction=\"batchmean\" averages the KL divergence over the batch, contributing\n# to the approximation of the expectation E_{i \\in V_L} in the training loop\n# as part of computing L_reg.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nkl_div_loss = torch.nn.functional.kl_div(\n torch.log(attention_scores + 1e-5), # Log of predicted distribution\n torch.log(uniform_distribution + 1e-5), # Log of target uniform distribution\n reduction=\"batchmean\", # Average over batch\n log_target=True # Both inputs are already in log space\n)\n# [End Snippet 2]\n\nreturn kl_div_loss\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details: \n - The LaTeX code does not specify that the uniform distribution is computed over the valid tokens only, excluding padding tokens. The reference code explicitly accounts for this by normalizing the attention mask to create a uniform distribution over valid tokens.\n - The LaTeX code omits the need for a numerical stability constant when taking logarithms. In practice, a small constant (1e-5) is added to both the predicted and target distributions to avoid undefined log values (e.g., log(0)), which is crucial for reliable gradient computation.\n - The method for aggregating the per-sample KL divergence into a single scalar loss is not detailed. The reference code explicitly averages the KL divergence over the batch (using a \"batchmean\" reduction), an important step for aligning with the expectation notation in the paper.\n \n - Mismatched Details: \n - None\n", "Missing_details": [ "\n- The LaTeX code does not specify that the uniform distribution is computed over the valid tokens only, excluding padding tokens. The reference code explicitly accounts for this by normalizing the attention mask to create a uniform distribution over valid tokens.\n", "\n- The LaTeX code omits the need for a numerical stability constant when taking logarithms. In practice, a small constant (1e-5) is added to both the predicted and target distributions to avoid undefined log values (e.g., log(0)), which is crucial for reliable gradient computation.\n", " \n- The method for aggregating the per-sample KL divergence into a single scalar loss is not detailed. The reference code explicitly averages the KL divergence over the batch (using a \"batchmean\" reduction), an important step for aligning with the expectation notation in the paper.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - attention_scores (torch.Tensor, dtype=torch.float32, shape=[batch_size, sequence_length]):\n The importance scores for each token in each sequence (node), typically the output of a softmax, representing Score_i in the LaTeX code.\n - attention_mask (torch.Tensor, dtype=torch.float32 or torch.bool, shape=[batch_size, sequence_length]):\n A mask indicating valid tokens (1) and padding tokens (0), used to define the scope of the uniform distribution. \n", "Arguments_list": [ { "name": "attention_scores", "string": "\n- attention_scores (torch.Tensor, dtype=torch.float32, shape=[batch_size, sequence_length]):\n The importance scores for each token in each sequence (node), typically the output of a softmax, representing Score_i in the LaTeX code.\n", "dependency": null }, { "name": "attention_mask", "string": "\n- attention_mask (torch.Tensor, dtype=torch.float32 or torch.bool, shape=[batch_size, sequence_length]):\n A mask indicating valid tokens (1) and padding tokens (0), used to define the scope of the uniform distribution. \n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra File Dependencies: \n - None\n\n Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs: \n - torch.nn.functional.kl_div\n - torch.log\n", "list": [ "torch.nn.functional.kl_div", "torch.log" ] }, "Return": { "Return_String": "\nOutput Variables:\n - kl_div_loss (torch.Tensor, scalar):\n The average KL divergence loss over the batch, contributing to the regularization term L_reg in the LaTeX code.\n", "Return_list": [ { "name": "kl_div_loss", "string": "\n- kl_div_loss (torch.Tensor, scalar):\n The average KL divergence loss over the batch, contributing to the regularization term L_reg in the LaTeX code.\n", "dependency": null } ] }, "ori_python_file": "from transformers import AutoTokenizer, AutoModel\nimport torch\nimport torch.nn as nn\nfrom torch.cuda.amp import autocast, GradScaler\nimport torch_geometric\nfrom utils.args import Arguments\nfrom utils.utils import mean_pooling, model_id\nfrom data.load import load_data\nfrom data.dataset import GenerateDataset, ReductionDataset\nfrom models.Reduction import ReductionModel\nfrom tqdm import tqdm\nfrom copy import deepcopy\nimport os\n\nos.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n\n\ndef collect_txt(idx, txt):\n tmp = []\n for i in idx:\n tmp.append(txt[i])\n return tmp\n\n\ndef generate(model, dataset, config, device):\n torch.cuda.set_device(device)\n model = model.cuda()\n generation_batch_size = 192\n \n loader = torch.utils.data.DataLoader(dataset=dataset, batch_size=generation_batch_size,\n shuffle=False, num_workers=6)\n \n model.eval()\n emb = []\n pooling = []\n \n with torch.no_grad():\n for batch in tqdm(loader, desc='Generating', unit='item'):\n batch = {k: v.to(device) for k, v in batch.items()}\n out = model(**batch)['last_hidden_state']\n pooling_out = mean_pooling(out, batch['attention_mask'])\n emb.append(out.to('cpu'))\n pooling.append(pooling_out.to('cpu'))\n \n emb = torch.cat(emb, dim=0)\n pooling = torch.cat(pooling, dim=0)\n \n print(f\"{'#' * 5}Generation Complete{'#' * 5}\")\n \n return emb, pooling\n\n\ndef compute_regularization_loss(attention_scores, attention_mask):\n uniform_distribution = attention_mask / attention_mask.sum(1, keepdim=True)\n kl_div_loss = torch.nn.functional.kl_div(\n torch.log(attention_scores + 1e-5), # Log of predicted distribution\n torch.log(uniform_distribution + 1e-5), # Log of target uniform distribution\n reduction=\"batchmean\", # Average over batch\n log_target=True # Both inputs are already in log space\n )\n \n return kl_div_loss\n \ndef do_reduction(model, data_loader, device):\n model.eval()\n output = []\n with torch.no_grad():\n for batch in data_loader:\n embeddings, attention_mask, neighbor_embeddings, _ = batch\n embeddings = embeddings.to(device)\n attention_mask = attention_mask.to(device)\n neighbor_embeddings = neighbor_embeddings.to(device)\n \n with autocast():\n score = model.inference(embeddings, neighbor_embeddings, attention_mask)\n \n output.append(score.cpu())\n \n output = torch.cat(output, dim=0)\n \n return output \n\ndef eval_reduction(model, data_loader, device):\n model.eval()\n correct = 0\n total_num = 0\n \n with torch.no_grad():\n with autocast():\n for batch in data_loader:\n embeddings, attention_mask, neighbor_embeddings, labels = batch\n embeddings = embeddings.to(device)\n attention_mask = attention_mask.to(device)\n neighbor_embeddings = neighbor_embeddings.to(device)\n labels = labels.to(device)\n \n with autocast():\n out, _ = model(embeddings, neighbor_embeddings, attention_mask) \n \n pred = out.argmax(dim=1)\n \n correct += (labels == pred).sum().item()\n total_num += labels.size(0)\n \n return 1.0 * correct / total_num\n \ndef train_reduction(model, optimizer, criterion, config, train_loader, val_loader, test_loader, beta=0.1, device=0):\n cnt = 0\n patience = config.patience\n best_val = 0\n best_test_fromval = 0\n \n tqd = tqdm(range(config.epochs), desc='Training', unit='item')\n scaler = GradScaler()\n\n for epoch in tqd:\n model.train()\n optimizer.zero_grad()\n \n for batch in train_loader:\n embeddings, attention_mask, neighbor_embeddings, labels = batch\n embeddings = embeddings.to(device)\n attention_mask = attention_mask.to(device)\n neighbor_embeddings = neighbor_embeddings.to(device)\n labels = labels.to(device)\n with autocast():\n out, score, loss_tmp = model(embeddings, neighbor_embeddings, attention_mask, labels)\n \n # loss1 cross entropy loss\n loss1 = criterion(out, labels)\n # loss2 regularization loss\n loss2 = compute_regularization_loss(score, attention_mask)\n # uniform_distribution = attention_mask / attention_mask.sum(1).unsqueeze(-1).expand_as(attention_mask)\n # loss2 = torch.nn.functional.kl_div(torch.log(score.squeeze(-1) + 1e-5), torch.log(uniform_distribution + 1e-5), \n # reduction=\"batchmean\", log_target=True)\n \n loss = loss1 + beta * loss2\n \n scaler.scale(loss).backward()\n scaler.step(optimizer)\n scaler.update()\n \n # train_acc = eval_reduction(model, train_loader, device)\n # val_acc = eval_reduction(model, val_loader, device) \n # test_acc = eval_reduction(model, test_loader, device)\n \n # tqd.set_description(f\"loss : {loss:.3f}, train_acc : {train_acc:.3f}, val_acc : {val_acc:.3f}, test_acc : {test_acc:.3f}\")\n \n # if val_acc > best_val:\n # best_val = val_acc\n # best_model = deepcopy(model)\n # best_test_fromval = test_acc\n # cnt = 0\n # if config.earlystop:\n # if val_acc <= best_val:\n # cnt += 1\n # if cnt >= patience:\n # print(f'early stop at epoch {epoch}')\n # break\n \n return model, best_test_fromval\n \n \nif __name__ == '__main__':\n config = Arguments().parse_args()\n \n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n print(config)\n \n # Loading Data\n data, text, num_classes = load_data(config.dataset, use_text=True)\n \n # Load model from HuggingFace Hub\n # tokenizer = AutoTokenizer.from_pretrained(model_id[config.reduction_lm_type], add_special_tokens=False)\n tokenizer = AutoTokenizer.from_pretrained(model_id[config.reduction_lm_type])\n bert_model = AutoModel.from_pretrained(model_id[config.reduction_lm_type], output_hidden_states=True, return_dict=True, \n torch_dtype=torch.float16)\n \n encodings = tokenizer(text, add_special_tokens=False, truncation=True,\n padding=True, return_tensors=\"pt\", max_length=512)\n \n raw_emb_dir = os.path.join('out', \"raw_emb\", f\"{config.reduction_lm_type}\")\n os.makedirs(raw_emb_dir, exist_ok=True)\n raw_emb_path = os.path.join(raw_emb_dir, f\"{config.dataset}.pt\")\n \n if not os.path.exists(raw_emb_path):\n attention_mask = encodings['attention_mask']\n \n dataset = GenerateDataset(encodings=encodings)\n \n # generating text embedding\n embeddings, pooling_embeddings = generate(bert_model, dataset, config, device)\n \n save_dict = {'embeddings': embeddings, 'attention_mask': attention_mask, 'pooling_embeddings': pooling_embeddings}\n torch.save(save_dict, raw_emb_path)\n\n else:\n save_dict = torch.load(raw_emb_path)\n embeddings = save_dict['embeddings']\n attention_mask = save_dict['attention_mask']\n pooling_embeddings = save_dict['pooling_embeddings']\n \n # message passing w/o parameters, remove self-loop \n conv = torch_geometric.nn.SimpleConv(aggr=\"mean\", combine_root=None)\n neighbor_embeddings = pooling_embeddings\n\n for _ in range(config.hops):\n neighbor_embeddings = conv(neighbor_embeddings, data.edge_index)\n \n \n train_idx = data.train_mask.nonzero().squeeze()\n val_idx = data.val_mask.nonzero().squeeze()\n test_idx = data.test_mask.nonzero().squeeze()\n \n reduction_model = ReductionModel(num_classes, embeddings.size(-1), hidden_dim=config.hidden_dim).to(device) \n \n # Training Token reduction model\n optimizer = torch.optim.Adam(reduction_model.parameters(), lr=config.lr, weight_decay=config.weight_decay)\n criterion = torch.nn.CrossEntropyLoss()\n dataset = ReductionDataset(embeddings, attention_mask, neighbor_embeddings, data.y)\n train_dataset = torch.utils.data.Subset(dataset, train_idx)\n val_dataset = torch.utils.data.Subset(dataset, val_idx)\n test_dataset = torch.utils.data.Subset(dataset, test_idx)\n train_loader = torch.utils.data.DataLoader(train_dataset, shuffle=True, batch_size=config.batch_size, num_workers=6)\n val_loader = torch.utils.data.DataLoader(val_dataset, shuffle=False, batch_size=config.eval_batch_size, num_workers=6)\n test_loader = torch.utils.data.DataLoader(test_dataset, shuffle=False, batch_size=config.eval_batch_size, num_workers=6)\n if config.TestCode:\n config.epochs = 10\n reduction_model, acc = train_reduction(reduction_model, optimizer, criterion, config, train_loader, val_loader, test_loader, beta=config.beta, device=device)\n print(f\"# final_acc: {acc*100:.2f}\")\n \n # inference\n inference_loader = torch.utils.data.DataLoader(\n dataset, shuffle=False, batch_size=config.eval_batch_size, num_workers=6\n )\n \n # score : [b, s]\n score = do_reduction(reduction_model, inference_loader, device)\n \n # Save reduction score & encodings & attention_mask\n save_reduction = {'score': score, 'encodings': encodings['input_ids'], 'attention_mask' : attention_mask}\n save_dir = os.path.join('out', 'reduction_out', f'{config.reduction_lm_type}')\n\n os.makedirs(save_dir, exist_ok=True)\n\n save_path = os.path.join(save_dir, f'{config.dataset}.pt')\n \n torch.save(save_reduction, save_path)" } ] }, { "paper_id": 29, "paper_details": { "title": "Advancing Adversarial Suffix Transfer Learning on Aligned Large Language Models", "url": "https://arxiv.org/abs/2408.14866" }, "repo_original_url": "https://github.com/Waffle-Liu/DeGCG", "project_path": "Benchmark/29-DeGCG/DeGCG-main", "enviorment_name": "degcg", "file_organization": "\nDeGCG-main/\n README.md\n LICENSE\n requirements.txt\n env.sh\n\n baselines/\n baseline.py\n check_refusal_utils.py\n model_utils.py\n __init__.py\n gcg/\n gcg.py\n gcg_utils.py\n __init__.py\n gcg_ensemble/\n gcg_ensemble.py\n gcg_ray_actors.py\n __init__.py\n\n configs/\n method_configs/\n EnsembleGCG_ce_config.yaml\n EnsembleGCG_ce-ft_config.yaml\n EnsembleGCG_config.yaml\n GCG_config.yaml\n model_configs/\n models.yaml\n\n data/\n behavior_datasets/\n extra_behavior_datasets/\n advbench_behaviors.csv\n adv_training_behaviors.csv\n tdc2023_test_phase_behaviors.csv\n harmbench_behaviors_multimodal_all.csv\n harmbench_behaviors_text_all.csv\n harmbench_behaviors_text_test.csv\n harmbench_behaviors_text_val.csv\n optimizer_targets/\n extra_targets/\n advbench_targets.json\n adv_training_targets.json\n adv_training_val_targets.json\n harmbench_targets_text_orca.json\n tdc2023_test_phase_targets.json\n harmbench_targets_multimodal.json\n harmbench_targets_text.json\n\n scripts/\n content_subset/\n standard_behavior_ids_dev_chemical_biological.txt\n standard_behavior_ids_dev_cybercrime_intrusion.txt\n standard_behavior_ids_dev_harassment_bullying.txt\n standard_behavior_ids_dev_harmful.txt\n standard_behavior_ids_dev_illegal.txt\n standard_behavior_ids_dev_misinformation_disinformation.txt\n standard_behavior_ids_test_chemical_biological.txt\n standard_behavior_ids_test_cybercrime_intrusion.txt\n standard_behavior_ids_test_harassment_bullying.txt\n standard_behavior_ids_test_harmful.txt\n standard_behavior_ids_test_illegal.txt\n standard_behavior_ids_test_misinformation_disinformation.txt\n subset/\n contextual_behavior_ids_dev.txt\n contextual_behavior_ids_test.txt\n copyright_behavior_ids_dev.txt\n copyright_behavior_ids_test.txt\n standard_behavior_ids_dev.txt\n standard_behavior_ids_test.txt\n evaluate_completions.sh\n generate_completions.sh\n generate_test_cases.sh\n run_completions_cross_data.sh\n run_completions.sh\n run_degcg_cross_data.sh\n run_degcg.sh\n run_eval.sh\n\n evaluate_completions.py\n eval_utils.py\n generate_completions.py\n generate_ood_test_cases.py\n generate_test_cases.py\n run_generate_cross_data.sh\n run_generate_ood_cases.sh\n\n en_core_web_sm-3.7.1-py3-none-any.whl\n\n", "latex_code_path": "Benchmark/29-DeGCG/arXiv-2408.14866v2", "task_details": [ { "task_id": 0, "indent": 2, "script": "\npython generate_test_cases.py --method_name EnsembleGCG --experiment_name llama2_7b --behaviors_path ./data/behavior_datasets/harmbench_behaviors_text_val.csv --save_dir results/EnsembleGCG/llama2_7b/test_cases --behavior_start_idx 0 --behavior_end_idx 20 --behavior_ids_subset ./scripts/subset/standard_behavior_ids_dev.txt --run_id ce-ft --overwrite --verbose --method_config_file configs/method_configs/EnsembleGCG_ce-ft_config.yaml --suffix_path results/EnsembleGCG/llama2_7b/test_cases/suffix_st.json\n", "completion_path": "./baselines/gcg_ensemble/gcg_ray_actors.py", "latex_code": "\n\\subsection{First-Token Searching}\nWe introduce the first-token searching (FTS) task in the pre-searching stage. FTS aims to find a universal and generalizable suffix that elicits a response without refusal, applicable to all behaviors. Specifically, the goal of FTS in the pre-searching stage is defined as follows: \n\\begin{equation}\n\\begin{aligned}\n & \\mathop{\\min}\\limits_{\\mathbf{S}} \\sum_j\\mathcal{L}_{FTS}(\\mathbf{X}^{(j)}, \\mathbf{S}) \\\\\n = & \\mathop{\\min}\\limits_{\\mathbf{S}} \\sum_j\\left[- \\log p(t_{n+1}^{(j)}|t_{1:n}^{(j)})\\right]\n\\end{aligned}\n\\end{equation}\nIn this task, the suffix is optimized based on the gradient derived solely from the first target token, resulting in a direct and efficient optimization. The first target token is typically behavior-agnostic, such as ``Sure'' or ``Here''. Therefore, the obtained suffixes $\\mathbf{S}_{FTS}$ serve as a general initialization with a low cross-entropy loss for the first token. Starting the search from an effective initialization with a low first-token loss helps to mitigate the inefficiency associated with starting each search from a high first-token loss, reducing the time and computational resources accordingly.\n", "namespace": "baselines.gcg_ensemble.gcg_ray_actors.GCGModelWorker.compute_fts_loss", "type": "method", "signature_position": [ 147, 147 ], "body_position": [ 148, 163 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Retrieve the precomputed embeddings and token ids for the selected behavior and its target.\n# This corresponds to selecting the input sequence \\(\\mathbf{X}^{(j)}\\) and the target tokens for behavior \\(j\\).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nbehavior_embeds = self.all_behavior_embeds[selected_behavior_idx].to(self.device)\ntarget_ids = self.all_target_ids[selected_behavior_idx].to(self.device)\ntarget_embeds = self.all_target_embeds[selected_behavior_idx].to(self.device)\nsearch_width = sampled_top_indices.shape[0]\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Prepare the input embeddings by combining the behavior embeddings, candidate suffix embeddings, and target embeddings.\n# This constructs the sequence \\(t_{1:n}^{(j)} = \\mathbf{X}^{(j)} + \\mathbf{S}\\), where \\(\\mathbf{S}\\) is the candidate suffix, and appends the target tokens.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nsampled_top_embeds = self.embed_layer(sampled_top_indices)\ninput_embeds = self._prepare_input_embeddings(behavior_embeds, sampled_top_embeds, target_embeds, search_width)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Compute the model's output logits for the prepared input embeddings.\n# This corresponds to obtaining the model's predictions for the sequence \\(t_{1:n}^{(j)} + \\mathbf{S} + \\text{target}\\), from which we will extract the probabilities for the target tokens.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nlogits = self.compute_candidates_logits(input_embeds, batch_size)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Adjust the logits and labels to focus on the first token of the target response.\n# This implements the FTS loss by considering only the prediction for the first target token \\(t_{n+1}^{(j)}\\).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\ntmp = input_embeds.shape[1] - target_embeds.shape[1]\nshift_logits = logits[..., tmp-1:-1, :].contiguous()\nshift_labels = target_ids.repeat(search_width, 1)\nshift_logits = shift_logits[:, :1, :]\nshift_labels = shift_labels[:, :1]\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Compute the cross-entropy loss for the first target token for each candidate suffix.\n# This calculates \\(- \\log p(t_{n+1}^{(j)} | t_{1:n}^{(j)})\\) for each candidate \\(\\mathbf{S}\\), where \\(t_{1:n}^{(j)}\\) includes the behavior and the suffix.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nloss_fct = CrossEntropyLoss(reduction='none')\nloss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))\nloss = loss.view(search_width, -1).mean(dim=1)\n\nreturn loss\n# [End Snippet 5]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing details:\n - The LaTeX does not specify that the input sequence must combine three components: (1) the behavior-specific prompt embeddings, (2) the candidate suffix embeddings, and (3) the target response embeddings. The reference code explicitly concatenates these components to form the complete input sequence for loss calculation.\n - The LaTeX description omits the explicit procedure for aligning the model\u2019s output with the first target token. The reference code shifts the logits so that only the probability corresponding to the first target token (i.e., the token following the entire input context) is used for loss computation.\n\n - Mismatched details:\n - None\n", "Missing_details": [ "\n- The LaTeX does not specify that the input sequence must combine three components: (1) the behavior-specific prompt embeddings, (2) the candidate suffix embeddings, and (3) the target response embeddings. The reference code explicitly concatenates these components to form the complete input sequence for loss calculation.\n", "\n- The LaTeX description omits the explicit procedure for aligning the model\u2019s output with the first target token. The reference code shifts the logits so that only the probability corresponding to the first target token (i.e., the token following the entire input context) is used for loss computation.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - sampled_top_indices (torch.Tensor, dtype=torch.long, shape=[search_width, num_optim_tokens]): Tensor containing the token indices of the candidate suffixes to evaluate.\n - selected_behavior_idx (int): Index of the behavior to use for computing the loss.\n - batch_size (int, optional): Default is 8.\n", "Arguments_list": [ { "name": "sampled_top_indices", "string": "\n- sampled_top_indices (torch.Tensor, dtype=torch.long, shape=[search_width, num_optim_tokens]): Tensor containing the token indices of the candidate suffixes to evaluate.\n", "dependency": null }, { "name": "selected_behavior_idx", "string": "\n- selected_behavior_idx (int): Index of the behavior to use for computing the loss.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-file Dependencies: \n - GCGModelWorker._prepare_input_embeddings\n - GCGModelWorker.compute_candidates_logits\n - GCGModelWorker.all_target_ids\n - GCGModelWorker.all_target_embeds\n - GCGModelWorker.embed_layer\n - GCGModelWorker.device\n - GCGModelWorker.all_behavior_embeds\n \n - Cross-file Dependencies: \n - None\n", "intra_file": [ "GCGModelWorker._prepare_input_embeddings", "GCGModelWorker.compute_candidates_logits", "GCGModelWorker.all_target_ids", "GCGModelWorker.all_target_embeds", "GCGModelWorker.embed_layer", "GCGModelWorker.device", "GCGModelWorker.all_behavior_embeds" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.nn.CrossEntropyLoss\n", "list": [ "torch.nn.CrossEntropyLoss" ] }, "Return": { "Return_String": "\nOutput Variables:\n - loss (torch.Tensor, dtype=torch.float, shape=[search_width]): Tensor containing the FTS loss for each candidate suffix.\n", "Return_list": [ { "name": "loss", "string": "\n- loss (torch.Tensor, dtype=torch.float, shape=[search_width]): Tensor containing the FTS loss for each candidate suffix.\n", "dependency": null } ] }, "ori_python_file": "from transformers import AutoTokenizer, AutoModelForCausalLM\nimport torch\nfrom torch.nn import CrossEntropyLoss\nimport numpy as np\nfrom typing import List, Union\nimport random\nfrom ..model_utils import get_template, load_model_and_tokenizer\n# https://huggingface.co/docs/accelerate/v0.11.0/en/memory#accelerate.find_executable_batch_size\nfrom accelerate.utils import find_executable_batch_size\nimport transformers\nimport gc\n\n\nclass GCGModelWorker:\n def __init__(self, \n model_name_or_path,\n allow_non_ascii=False, \n return_tensors=\"pt\",\n seed=0,\n num_gpus=1,\n search_width=512,\n use_prefix_cache=True,\n **model_kwargs):\n random.seed(seed)\n self.search_width = search_width\n # starting search_batch_size, will auto reduce batch_size later if go OOM (distinct for each worker, but not each behavior for simplicity)\n self.search_batch_size = search_width\n self.use_prefix_cache = use_prefix_cache\n self.model_name = model_name_or_path.split(\"/\")[-1]\n self.model_name_or_path = model_name_or_path\n self.num_gpus = num_gpus\n self.model, self.tokenizer = load_model_and_tokenizer(model_name_or_path, **model_kwargs)\n self.device = self.model.device\n self.return_tensors = return_tensors\n self.embed_layer = self.model.get_input_embeddings()\n self.vocab_size = self.embed_layer.weight.shape[0] # can be larger than tokenizer.vocab_size for some models\n self.vocab_embeds = self.embed_layer(torch.arange(0, self.vocab_size).long().to(self.device))\n # Init instruction template, embeds and cache\n template = get_template(self.model_name_or_path, **model_kwargs)['prompt'].split(\"{instruction}\")\n self.before_tc, self.after_tc = template[0], template[1]\n before_ids = self.tokenizer(self.before_tc, return_tensors=self.return_tensors, add_special_tokens=True).to(self.device)['input_ids']\n self.before_embeds = self.embed_layer(before_ids)\n after_ids = self.tokenizer(self.after_tc, return_tensors=self.return_tensors, add_special_tokens=False).to(self.device)['input_ids']\n self.after_embeds = self.embed_layer(after_ids)\n # In the __init__ method, replace the following block:\n if self.use_prefix_cache:\n # Check if we're using a model that requires special KV cache handling\n if hasattr(self.model, \"config\") and hasattr(self.model.config, \"model_type\") and self.model.config.model_type == \"llama\":\n # For LLaMA models, don't use KV cache\n self.use_prefix_cache = False\n print(f\"Warning: KV cache disabled for {self.model.config.model_type} model\")\n else:\n with torch.no_grad():\n outputs = self.model(inputs_embeds=self.before_embeds, use_cache=True)\n self.prefix_cache = outputs.past_key_values\n self.behaviors, self.targets = None, None\n self.all_target_ids = []\n self.all_target_embeds = []\n self.all_behavior_embeds = []\n\n def init_behaviors_and_targets(self, behaviors: List[str], targets: List[str]):\n # NOTE: self.targets is ONLY used here, self.behaviors only used here and in generate\n self.behaviors, self.targets = behaviors, targets\n for behavior, target in zip(behaviors, targets):\n behavior_ids = self.tokenizer(behavior, return_tensors=self.return_tensors, add_special_tokens=False).to(self.device)['input_ids']\n target_ids = self.tokenizer(target, return_tensors=self.return_tensors, add_special_tokens=False).to(self.device)['input_ids']\n # if 'ft' in self.loss_func_type:\n # target_ids = target_ids[:, :1]\n behavior_embeds, target_embeds = self.embed_layer(behavior_ids), self.embed_layer(target_ids)\n # Move to CPUs here as number of behaviors can be large thus go OOM\n self.all_target_ids.append(target_ids.cpu())\n self.all_target_embeds.append(target_embeds.cpu())\n self.all_behavior_embeds.append(behavior_embeds.cpu())\n\n def get_token_gradient(self, worker_optim_ids, num_optim_tokens, selected_behavior_indices, loss_func_type='ce'):\n \"\"\"\n Calculate the token gradient for the selected behavior indices, average them, and normalize them for ensembling multiple models\n \"\"\"\n token_grads = []\n for selected_behavior_idx in selected_behavior_indices:\n token_grads.append(self.compute_token_gradient(worker_optim_ids, num_optim_tokens, selected_behavior_idx, loss_func_type=loss_func_type))\n token_grad = sum(token_grads) / len(token_grads)\n return token_grad / token_grad.norm(dim=-1, keepdim=True)\n\n def compute_token_gradient(self, worker_optim_ids, num_optim_tokens, selected_behavior_idx, loss_func_type='ce'):\n behavior_embeds = self.all_behavior_embeds[selected_behavior_idx].to(self.device)\n target_ids = self.all_target_ids[selected_behavior_idx].to(self.device)\n target_embeds = self.all_target_embeds[selected_behavior_idx].to(self.device)\n after_embeds = self.after_embeds\n before_embeds = self.before_embeds\n \n optim_ids_onehot = torch.zeros((1, num_optim_tokens, self.vocab_size), device=self.device).to(behavior_embeds.dtype)\n optim_ids_onehot.scatter_(2, worker_optim_ids.to(self.device).unsqueeze(2), 1.0).requires_grad_()\n optim_embeds = torch.matmul(optim_ids_onehot.squeeze(0), self.vocab_embeds).unsqueeze(0)\n\n if self.use_prefix_cache:\n prefix_cache = self.prefix_cache\n input_embeds = torch.cat([behavior_embeds, optim_embeds, after_embeds, target_embeds], dim=1)\n outputs = self.model(inputs_embeds=input_embeds, past_key_values=prefix_cache)\n else:\n input_embeds = torch.cat([before_embeds, behavior_embeds, optim_embeds, after_embeds, target_embeds], dim=1)\n outputs = self.model(inputs_embeds=input_embeds)\n\n logits = outputs.logits\n tmp = input_embeds.shape[1] - target_embeds.shape[1]\n shift_logits = logits[..., tmp-1:-1, :].contiguous()\n shift_labels = target_ids\n ## GCG Logit Loss ##\n\n if 'ce' in loss_func_type:\n loss_fct = CrossEntropyLoss()\n if 'ft' in loss_func_type:\n shift_logits = shift_logits[:, :1, :]\n shift_labels = shift_labels[:, :1]\n loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))\n elif loss_func_type == 'cw':\n loss = _cw_loss(shift_logits, shift_labels)\n else:\n raise ValueError(f\"Unknown loss_func: {loss_func_type}!\") \n token_grad = torch.autograd.grad(outputs=[loss], inputs=[optim_ids_onehot])[0]\n return token_grad\n\n def compute_loss_on_candidates_batch(self, sampled_top_indices, selected_behavior_indices, loss_func_type='ce'):\n all_losses = []\n for behavior_idx in selected_behavior_indices:\n if 'ft' in loss_func_type:\n all_losses.append(self.compute_fts_loss(sampled_top_indices, behavior_idx))\n elif loss_func_type == 'ce':\n all_losses.append(self.compute_cas_loss(sampled_top_indices, behavior_idx))\n elif loss_func_type == 'cw':\n all_losses.append(self.compute_cw_loss(sampled_top_indices, behavior_idx))\n else:\n raise ValueError(f\"Unknown loss_func: {loss_func_type}!\")\n behavior_losses = torch.stack(all_losses, dim=0)\n return behavior_losses\n\n def compute_loss_on_candidates(self, sampled_top_indices, selected_behavior_idx, loss_func_type='ce'):\n if 'ft' in loss_func_type:\n return self.compute_fts_loss(sampled_top_indices, selected_behavior_idx)\n elif loss_func_type == 'ce':\n return self.compute_cas_loss(sampled_top_indices, selected_behavior_idx)\n elif loss_func_type == 'cw':\n return self.compute_cw_loss(sampled_top_indices, selected_behavior_idx)\n else:\n raise ValueError(f\"Unknown loss_func: {loss_func_type}!\")\n\n def compute_fts_loss(self, sampled_top_indices, selected_behavior_idx, batch_size=8):\n behavior_embeds = self.all_behavior_embeds[selected_behavior_idx].to(self.device)\n target_ids = self.all_target_ids[selected_behavior_idx].to(self.device)\n target_embeds = self.all_target_embeds[selected_behavior_idx].to(self.device)\n search_width = sampled_top_indices.shape[0]\n sampled_top_embeds = self.embed_layer(sampled_top_indices)\n input_embeds = self._prepare_input_embeddings(behavior_embeds, sampled_top_embeds, target_embeds, search_width)\n logits = self.compute_candidates_logits(input_embeds, batch_size)\n tmp = input_embeds.shape[1] - target_embeds.shape[1]\n shift_logits = logits[..., tmp-1:-1, :].contiguous()\n shift_labels = target_ids.repeat(search_width, 1)\n shift_logits = shift_logits[:, :1, :]\n shift_labels = shift_labels[:, :1]\n loss_fct = CrossEntropyLoss(reduction='none')\n loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))\n loss = loss.view(search_width, -1).mean(dim=1)\n return loss\n\n def compute_cas_loss(self, sampled_top_indices, selected_behavior_idx, batch_size=8):\n behavior_embeds = self.all_behavior_embeds[selected_behavior_idx].to(self.device)\n target_ids = self.all_target_ids[selected_behavior_idx].to(self.device)\n target_embeds = self.all_target_embeds[selected_behavior_idx].to(self.device)\n search_width = sampled_top_indices.shape[0]\n sampled_top_embeds = self.embed_layer(sampled_top_indices)\n input_embeds = self._prepare_input_embeddings(behavior_embeds, sampled_top_embeds, target_embeds, search_width)\n logits = self.compute_candidates_logits(input_embeds, batch_size)\n tmp = input_embeds.shape[1] - target_embeds.shape[1]\n shift_logits = logits[..., tmp-1:-1, :].contiguous()\n shift_labels = target_ids.repeat(search_width, 1)\n loss_fct = CrossEntropyLoss(reduction='none')\n loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))\n loss = loss.view(search_width, -1).mean(dim=1)\n return loss\n\n def compute_cw_loss(self, sampled_top_indices, selected_behavior_idx):\n behavior_embeds = self.all_behavior_embeds[selected_behavior_idx].to(self.device)\n target_ids = self.all_target_ids[selected_behavior_idx].to(self.device)\n target_embeds = self.all_target_embeds[selected_behavior_idx].to(self.device)\n search_width = sampled_top_indices.shape[0]\n sampled_top_embeds = self.embed_layer(sampled_top_indices)\n input_embeds = self._prepare_input_embeddings(behavior_embeds, sampled_top_embeds, target_embeds, search_width)\n logits = find_executable_batch_size(self.compute_candidates_logits, self.search_batch_size)(input_embeds)\n tmp = input_embeds.shape[1] - target_embeds.shape[1]\n shift_logits = logits[..., tmp-1:-1, :].contiguous()\n shift_labels = target_ids.repeat(search_width, 1)\n loss = _cw_loss(shift_logits, shift_labels)\n return loss\n\n def compute_candidates_logits(self, input_embeds, search_batch_size):\n if self.search_batch_size != search_batch_size:\n print(f\"INFO: Setting candidates search_batch_size to {search_batch_size})\")\n self.search_batch_size = search_batch_size\n gc.collect() \n torch.cuda.empty_cache() \n logits = []\n for i in range(0, input_embeds.shape[0], search_batch_size):\n with torch.no_grad():\n input_embeds_batch = input_embeds[i:i+search_batch_size]\n if self.use_prefix_cache:\n # Check if we're using a model that requires special KV cache handling\n if hasattr(self.model, \"config\") and hasattr(self.model.config, \"model_type\") and self.model.config.model_type == \"llama\":\n # For LLaMA models, disable KV cache when using input embeddings with past_key_values\n outputs = self.model(inputs_embeds=input_embeds_batch)\n else:\n # Original code path for models that support the standard past_key_values format\n prefix_cache = self.prefix_cache\n current_batch_size = input_embeds_batch.shape[0]\n prefix_cache_batch = []\n for j in range(len(prefix_cache)):\n prefix_cache_batch.append([])\n for k in range(len(prefix_cache[j])):\n prefix_cache_batch[j].append(prefix_cache[j][k].expand(current_batch_size, -1, -1, -1))\n outputs = self.model(inputs_embeds=input_embeds_batch, past_key_values=prefix_cache_batch)\n else:\n outputs = self.model(inputs_embeds=input_embeds_batch)\n logits.append(outputs.logits)\n logits = torch.cat(logits, dim=0)\n return logits\n\n def generate(self, optim_str, selected_behavior_idx):\n inputs = self.before_tc + self.behaviors[selected_behavior_idx] + optim_str + self.after_tc\n encoded = self.tokenizer(inputs, return_tensors=self.return_tensors)\n with torch.no_grad():\n outputs = self.model.generate(**encoded.to(self.device), do_sample=False, max_new_tokens=16, use_cache=True)\n outputs = self.tokenizer.batch_decode(outputs)\n\n ouputs = outputs[0].replace(inputs, \"\")\n # for i, o in zip(inputs, outputs):\n # print(\"\\nbehavior:\", self.behaviors[selected_behavior_idx] + optim_str[0])\n # print(\"\\noutput:\", o.replace(i, \"\"))\n return ouputs\n\n def is_initialized(self): \n return f\"Initialized: {self.model_name_or_path}\"\n\n def get_attribute_(self, attr_name):\n return getattr(self, attr_name, None)\n \n def _prepare_input_embeddings(self, behavior_embeds, sampled_top_embeds, target_embeds, search_width):\n \"\"\"Helper method to prepare input embeddings based on use_prefix_cache setting.\n Args:\n behavior_embeds: Embeddings for behavior\n sampled_top_embeds: Embeddings for candidate suffix tokens\n target_embeds: Embeddings for target\n search_width: Number of candidates\n Returns:\n Tensor: Concatenated input embeddings\n \"\"\"\n if self.use_prefix_cache:\n return torch.cat([behavior_embeds.repeat(search_width, 1, 1),\n sampled_top_embeds,\n self.after_embeds.repeat(search_width, 1, 1),\n target_embeds.repeat(search_width, 1, 1)], dim=1)\n else:\n return torch.cat([self.before_embeds.repeat(search_width, 1, 1),\n behavior_embeds.repeat(search_width, 1, 1),\n sampled_top_embeds,\n self.after_embeds.repeat(search_width, 1, 1),\n target_embeds.repeat(search_width, 1, 1)], dim=1)\n#### Helper\ndef sample_control(control_toks, grad, search_width, topk=256, temp=1, not_allowed_tokens=None):\n torch.manual_seed(42)\n if torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\n if not_allowed_tokens is not None:\n # grad[:, not_allowed_tokens.to(grad.device)] = np.infty\n grad = grad.clone()\n grad[:, not_allowed_tokens.to(grad.device)] = grad.max() + 1\n\n top_indices = (-grad).topk(topk, dim=1).indices\n control_toks = control_toks.to(grad.device)\n original_control_toks = control_toks.repeat(search_width, 1)\n new_token_pos = torch.arange(\n 0, \n len(control_toks), \n len(control_toks) / search_width,\n device=grad.device\n ).type(torch.int64)\n new_token_val = torch.gather(\n top_indices[new_token_pos], 1, \n torch.randint(0, topk, (search_width, 1),\n device=grad.device)\n )\n new_control_toks = original_control_toks.scatter_(1, new_token_pos.unsqueeze(-1), new_token_val)\n return new_control_toks\n\ndef get_nonascii_toks(tokenizer, device='cpu'):\n def is_ascii(s):\n return s.isascii() and s.isprintable()\n ascii_toks = []\n for i in range(3, tokenizer.vocab_size):\n if not is_ascii(tokenizer.decode([i])):\n ascii_toks.append(i)\n if tokenizer.bos_token_id is not None:\n ascii_toks.append(tokenizer.bos_token_id)\n if tokenizer.eos_token_id is not None:\n ascii_toks.append(tokenizer.eos_token_id)\n if tokenizer.pad_token_id is not None:\n ascii_toks.append(tokenizer.pad_token_id)\n if tokenizer.unk_token_id is not None:\n ascii_toks.append(tokenizer.unk_token_id)\n\n if \"Baichuan2\" in tokenizer.name_or_path:\n ascii_toks += [i for i in range(101, 1000)]\n return torch.tensor(ascii_toks, device=device)\n\ndef _cw_loss(\n logits: torch.FloatTensor,\n target_ids: torch.LongTensor,\n cw_margin: float = 1e-3,\n dim: int = -1,\n) -> torch.FloatTensor:\n \"\"\"CW loss.\n Hinge loss on the difference between the largest and the target logits.\n \"\"\"\n input_shape = target_ids.shape\n assert logits.shape[:-1] == input_shape, (logits.shape, input_shape)\n target_ids = target_ids.unsqueeze(-1)\n tgt_logits = logits.gather(dim, target_ids).squeeze(-1)\n # Set logits of target tok very low (-1e3) so it cannot be the largest\n tmp_logits = logits.clone()\n tmp_logits.scatter_(dim, target_ids, -1e3)\n largest_non_tgt_logits = tmp_logits.max(dim).values\n loss = largest_non_tgt_logits - tgt_logits\n loss = loss.clamp_min(-cw_margin).mean(-1)\n if len(input_shape) == 1:\n assert loss.ndim == 0, loss.shape\n else:\n assert loss.shape == input_shape[:1], loss.shape\n return loss" }, { "task_id": 1, "indent": 2, "script": "\npython generate_test_cases.py --method_name EnsembleGCG --experiment_name llama2_7b --behaviors_path ./data/behavior_datasets/harmbench_behaviors_text_val.csv --save_dir results/EnsembleGCG/llama2_7b/test_cases --behavior_start_idx 0 --behavior_end_idx 20 --behavior_ids_subset ./scripts/subset/standard_behavior_ids_dev.txt --run_id ce --overwrite --verbose --method_config_file configs/method_configs/EnsembleGCG_ce_config.yaml --suffix_path results/EnsembleGCG/llama2_7b/test_cases/suffix_st.json\n", "latex_code": "\n\\subsection{Context-Aware Searching}\nSuffixes obtained from FTS are effective for behavior-agnostic targets but fall short in eliciting behavior-relevant responses. Therefore, we propose to fine-tune the suffix in the pre-searching stage by performing content-aware searching (CAS) with behavior-relevant targets, such as ``how to make a bomb''. Given that this step builds upon the success of FTS, we maintain the FTS target in this step as well. Specifically, the goal for CAS is defined as follows\n\\begin{equation}\n\\begin{aligned}\n & \\mathop{\\min}\\limits_{\\mathbf{S}} \\sum_j\\mathcal{L}_{CAS}(\\mathbf{X}^{(j)}, \\mathbf{S}) \\\\\n = & \\mathop{\\min}\\limits_{\\mathbf{S}} \\sum_j\\sum_{k=1}^{m} \\log p(t_{n+k}^{(j)}|t_{1:n+k-1}^{(j)})\n\\end{aligned}\n\\end{equation}\n", "completion_path": "./baselines/gcg_ensemble/gcg_ray_actors.py", "namespace": "baselines.gcg_ensemble.gcg_ray_actors.GCGModelWorker.compute_cas_loss", "type": "method", "signature_position": [ 165, 165 ], "body_position": [ 166, 179 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Retrieves the embeddings associated with both the selected\n# behavior and its corresponding targets, aligning with the CAS concept in\n# the LaTeX snippet where \\(\\mathbf{X}^{(j)}\\) references input sequences\n# and \\(\\mathbf{S}\\) references the proposed suffix.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nbehavior_embeds = self.all_behavior_embeds[selected_behavior_idx].to(self.device)\ntarget_ids = self.all_target_ids[selected_behavior_idx].to(self.device)\ntarget_embeds = self.all_target_embeds[selected_behavior_idx].to(self.device)\nsearch_width = sampled_top_indices.shape[0]\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Builds the specialized input embeddings necessary for evaluating\n# the CAS objective, reflecting the summation over all content-aware tokens\n# in the LaTeX.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nsampled_top_embeds = self.embed_layer(sampled_top_indices)\ninput_embeds = self._prepare_input_embeddings(behavior_embeds, sampled_top_embeds, target_embeds, search_width)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Computes the model logits for the candidate embeddings,\n# corresponding to \\(\\log p(t_{n+k}^{(j)}|t_{1:n+k-1}^{(j)})\\) in the LaTeX.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nlogits = self.compute_candidates_logits(input_embeds, batch_size)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Aligns the model\u2019s output with the CAS target by selecting\n# the relevant portion of the logits and repeating the targets, mirroring\n# the summation over m tokens in the LaTeX description.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\ntmp = input_embeds.shape[1] - target_embeds.shape[1]\nshift_logits = logits[..., tmp-1:-1, :].contiguous()\nshift_labels = target_ids.repeat(search_width, 1)\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Computes the average cross-entropy loss across all behavior-\n# relevant tokens, conforming to the CAS objective in the LaTeX.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nloss_fct = CrossEntropyLoss(reduction='none')\nloss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))\nloss = loss.view(search_width, -1).mean(dim=1)\nreturn loss\n# [End Snippet 5]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - None\n \n Mismatched Details:\n - None\n", "Missing_details": [], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - sampled_top_indices (torch.Tensor):\n Integer tensor representing candidate token indices selected during the search process. Its shape is [search_width, num_optim_tokens].\n - selected_behavior_idx (int):\n The index of the behavior from which to retrieve the corresponding embeddings and target tokens.\n - batch_size (int, optional):\n Default is 8.\n", "Arguments_list": [ { "name": "sampled_top_indices", "string": "\n- sampled_top_indices (torch.Tensor):\n Integer tensor representing candidate token indices selected during the search process. Its shape is [search_width, num_optim_tokens].\n", "dependency": null }, { "name": "selected_behavior_idx", "string": "\n- selected_behavior_idx (int):\n The index of the behavior from which to retrieve the corresponding embeddings and target tokens.\n", "dependency": null }, { "name": "batch_size", "string": "\n- batch_size (int, optional):\n Default is 8.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-file Dependencies:\n - GCGModelWorker.compute_candidates_logits\n - GCGModelWorker._prepare_input_embeddings\n - GCGModelWorker.all_behavior_embeds\n - GCGModelWorker.all_target_ids\n - GCGModelWorker.all_target_embeds\n - GCGModelWorker.embed_layer\n - GCGModelWorker.device\n \n - Cross-file Dependencies:\n - None\n", "intra_file": [ "GCGModelWorker.compute_candidates_logits", "GCGModelWorker._prepare_input_embeddings", "GCGModelWorker.all_behavior_embeds", "GCGModelWorker.all_target_ids", "GCGModelWorker.all_target_embeds", "GCGModelWorker.embed_layer", "GCGModelWorker.device" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.nn.CrossEntropyLoss\n", "list": [ "torch.nn.CrossEntropyLoss" ] }, "Return": { "Return_String": "\nOutput Variables:\n - loss (torch.Tensor, shape=[search_width]):\n Each element is the average cross-entropy loss across all tokens in the behavior-relevant targetsequence for a particular candidate.\n", "Return_list": [ { "name": "loss", "string": "\n- loss (torch.Tensor, shape=[search_width]):\n Each element is the average cross-entropy loss across all tokens in the behavior-relevant targetsequence for a particular candidate.\n", "dependency": null } ] }, "ori_python_file": "from transformers import AutoTokenizer, AutoModelForCausalLM\nimport torch\nfrom torch.nn import CrossEntropyLoss\nimport numpy as np\nfrom typing import List, Union\nimport random\nfrom ..model_utils import get_template, load_model_and_tokenizer\n# https://huggingface.co/docs/accelerate/v0.11.0/en/memory#accelerate.find_executable_batch_size\nfrom accelerate.utils import find_executable_batch_size\nimport transformers\nimport gc\n\n\nclass GCGModelWorker:\n def __init__(self, \n model_name_or_path,\n allow_non_ascii=False, \n return_tensors=\"pt\",\n seed=0,\n num_gpus=1,\n search_width=512,\n use_prefix_cache=True,\n **model_kwargs):\n random.seed(seed)\n self.search_width = search_width\n # starting search_batch_size, will auto reduce batch_size later if go OOM (distinct for each worker, but not each behavior for simplicity)\n self.search_batch_size = search_width\n self.use_prefix_cache = use_prefix_cache\n self.model_name = model_name_or_path.split(\"/\")[-1]\n self.model_name_or_path = model_name_or_path\n self.num_gpus = num_gpus\n self.model, self.tokenizer = load_model_and_tokenizer(model_name_or_path, **model_kwargs)\n self.device = self.model.device\n self.return_tensors = return_tensors\n self.embed_layer = self.model.get_input_embeddings()\n self.vocab_size = self.embed_layer.weight.shape[0] # can be larger than tokenizer.vocab_size for some models\n self.vocab_embeds = self.embed_layer(torch.arange(0, self.vocab_size).long().to(self.device))\n # Init instruction template, embeds and cache\n template = get_template(self.model_name_or_path, **model_kwargs)['prompt'].split(\"{instruction}\")\n self.before_tc, self.after_tc = template[0], template[1]\n before_ids = self.tokenizer(self.before_tc, return_tensors=self.return_tensors, add_special_tokens=True).to(self.device)['input_ids']\n self.before_embeds = self.embed_layer(before_ids)\n after_ids = self.tokenizer(self.after_tc, return_tensors=self.return_tensors, add_special_tokens=False).to(self.device)['input_ids']\n self.after_embeds = self.embed_layer(after_ids)\n # In the __init__ method, replace the following block:\n if self.use_prefix_cache:\n # Check if we're using a model that requires special KV cache handling\n if hasattr(self.model, \"config\") and hasattr(self.model.config, \"model_type\") and self.model.config.model_type == \"llama\":\n # For LLaMA models, don't use KV cache\n self.use_prefix_cache = False\n print(f\"Warning: KV cache disabled for {self.model.config.model_type} model\")\n else:\n with torch.no_grad():\n outputs = self.model(inputs_embeds=self.before_embeds, use_cache=True)\n self.prefix_cache = outputs.past_key_values\n self.behaviors, self.targets = None, None\n self.all_target_ids = []\n self.all_target_embeds = []\n self.all_behavior_embeds = []\n\n def init_behaviors_and_targets(self, behaviors: List[str], targets: List[str]):\n # NOTE: self.targets is ONLY used here, self.behaviors only used here and in generate\n self.behaviors, self.targets = behaviors, targets\n for behavior, target in zip(behaviors, targets):\n behavior_ids = self.tokenizer(behavior, return_tensors=self.return_tensors, add_special_tokens=False).to(self.device)['input_ids']\n target_ids = self.tokenizer(target, return_tensors=self.return_tensors, add_special_tokens=False).to(self.device)['input_ids']\n # if 'ft' in self.loss_func_type:\n # target_ids = target_ids[:, :1]\n behavior_embeds, target_embeds = self.embed_layer(behavior_ids), self.embed_layer(target_ids)\n # Move to CPUs here as number of behaviors can be large thus go OOM\n self.all_target_ids.append(target_ids.cpu())\n self.all_target_embeds.append(target_embeds.cpu())\n self.all_behavior_embeds.append(behavior_embeds.cpu())\n\n def get_token_gradient(self, worker_optim_ids, num_optim_tokens, selected_behavior_indices, loss_func_type='ce'):\n \"\"\"\n Calculate the token gradient for the selected behavior indices, average them, and normalize them for ensembling multiple models\n \"\"\"\n token_grads = []\n for selected_behavior_idx in selected_behavior_indices:\n token_grads.append(self.compute_token_gradient(worker_optim_ids, num_optim_tokens, selected_behavior_idx, loss_func_type=loss_func_type))\n token_grad = sum(token_grads) / len(token_grads)\n return token_grad / token_grad.norm(dim=-1, keepdim=True)\n\n def compute_token_gradient(self, worker_optim_ids, num_optim_tokens, selected_behavior_idx, loss_func_type='ce'):\n behavior_embeds = self.all_behavior_embeds[selected_behavior_idx].to(self.device)\n target_ids = self.all_target_ids[selected_behavior_idx].to(self.device)\n target_embeds = self.all_target_embeds[selected_behavior_idx].to(self.device)\n after_embeds = self.after_embeds\n before_embeds = self.before_embeds\n \n optim_ids_onehot = torch.zeros((1, num_optim_tokens, self.vocab_size), device=self.device).to(behavior_embeds.dtype)\n optim_ids_onehot.scatter_(2, worker_optim_ids.to(self.device).unsqueeze(2), 1.0).requires_grad_()\n optim_embeds = torch.matmul(optim_ids_onehot.squeeze(0), self.vocab_embeds).unsqueeze(0)\n\n if self.use_prefix_cache:\n prefix_cache = self.prefix_cache\n input_embeds = torch.cat([behavior_embeds, optim_embeds, after_embeds, target_embeds], dim=1)\n outputs = self.model(inputs_embeds=input_embeds, past_key_values=prefix_cache)\n else:\n input_embeds = torch.cat([before_embeds, behavior_embeds, optim_embeds, after_embeds, target_embeds], dim=1)\n outputs = self.model(inputs_embeds=input_embeds)\n\n logits = outputs.logits\n tmp = input_embeds.shape[1] - target_embeds.shape[1]\n shift_logits = logits[..., tmp-1:-1, :].contiguous()\n shift_labels = target_ids\n ## GCG Logit Loss ##\n\n if 'ce' in loss_func_type:\n loss_fct = CrossEntropyLoss()\n if 'ft' in loss_func_type:\n shift_logits = shift_logits[:, :1, :]\n shift_labels = shift_labels[:, :1]\n loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))\n elif loss_func_type == 'cw':\n loss = _cw_loss(shift_logits, shift_labels)\n else:\n raise ValueError(f\"Unknown loss_func: {loss_func_type}!\") \n token_grad = torch.autograd.grad(outputs=[loss], inputs=[optim_ids_onehot])[0]\n return token_grad\n\n def compute_loss_on_candidates_batch(self, sampled_top_indices, selected_behavior_indices, loss_func_type='ce'):\n all_losses = []\n for behavior_idx in selected_behavior_indices:\n if 'ft' in loss_func_type:\n all_losses.append(self.compute_fts_loss(sampled_top_indices, behavior_idx))\n elif loss_func_type == 'ce':\n all_losses.append(self.compute_cas_loss(sampled_top_indices, behavior_idx))\n elif loss_func_type == 'cw':\n all_losses.append(self.compute_cw_loss(sampled_top_indices, behavior_idx))\n else:\n raise ValueError(f\"Unknown loss_func: {loss_func_type}!\")\n behavior_losses = torch.stack(all_losses, dim=0)\n return behavior_losses\n\n def compute_loss_on_candidates(self, sampled_top_indices, selected_behavior_idx, loss_func_type='ce'):\n if 'ft' in loss_func_type:\n return self.compute_fts_loss(sampled_top_indices, selected_behavior_idx)\n elif loss_func_type == 'ce':\n return self.compute_cas_loss(sampled_top_indices, selected_behavior_idx)\n elif loss_func_type == 'cw':\n return self.compute_cw_loss(sampled_top_indices, selected_behavior_idx)\n else:\n raise ValueError(f\"Unknown loss_func: {loss_func_type}!\")\n\n def compute_fts_loss(self, sampled_top_indices, selected_behavior_idx, batch_size=8):\n behavior_embeds = self.all_behavior_embeds[selected_behavior_idx].to(self.device)\n target_ids = self.all_target_ids[selected_behavior_idx].to(self.device)\n target_embeds = self.all_target_embeds[selected_behavior_idx].to(self.device)\n search_width = sampled_top_indices.shape[0]\n sampled_top_embeds = self.embed_layer(sampled_top_indices)\n input_embeds = self._prepare_input_embeddings(behavior_embeds, sampled_top_embeds, target_embeds, search_width)\n logits = self.compute_candidates_logits(input_embeds, batch_size)\n tmp = input_embeds.shape[1] - target_embeds.shape[1]\n shift_logits = logits[..., tmp-1:-1, :].contiguous()\n shift_labels = target_ids.repeat(search_width, 1)\n shift_logits = shift_logits[:, :1, :]\n shift_labels = shift_labels[:, :1]\n loss_fct = CrossEntropyLoss(reduction='none')\n loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))\n loss = loss.view(search_width, -1).mean(dim=1)\n return loss\n\n def compute_cas_loss(self, sampled_top_indices, selected_behavior_idx, batch_size=8):\n behavior_embeds = self.all_behavior_embeds[selected_behavior_idx].to(self.device)\n target_ids = self.all_target_ids[selected_behavior_idx].to(self.device)\n target_embeds = self.all_target_embeds[selected_behavior_idx].to(self.device)\n search_width = sampled_top_indices.shape[0]\n sampled_top_embeds = self.embed_layer(sampled_top_indices)\n input_embeds = self._prepare_input_embeddings(behavior_embeds, sampled_top_embeds, target_embeds, search_width)\n logits = self.compute_candidates_logits(input_embeds, batch_size)\n tmp = input_embeds.shape[1] - target_embeds.shape[1]\n shift_logits = logits[..., tmp-1:-1, :].contiguous()\n shift_labels = target_ids.repeat(search_width, 1)\n loss_fct = CrossEntropyLoss(reduction='none')\n loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))\n loss = loss.view(search_width, -1).mean(dim=1)\n return loss\n\n def compute_cw_loss(self, sampled_top_indices, selected_behavior_idx):\n behavior_embeds = self.all_behavior_embeds[selected_behavior_idx].to(self.device)\n target_ids = self.all_target_ids[selected_behavior_idx].to(self.device)\n target_embeds = self.all_target_embeds[selected_behavior_idx].to(self.device)\n search_width = sampled_top_indices.shape[0]\n sampled_top_embeds = self.embed_layer(sampled_top_indices)\n input_embeds = self._prepare_input_embeddings(behavior_embeds, sampled_top_embeds, target_embeds, search_width)\n logits = find_executable_batch_size(self.compute_candidates_logits, self.search_batch_size)(input_embeds)\n tmp = input_embeds.shape[1] - target_embeds.shape[1]\n shift_logits = logits[..., tmp-1:-1, :].contiguous()\n shift_labels = target_ids.repeat(search_width, 1)\n loss = _cw_loss(shift_logits, shift_labels)\n return loss\n\n def compute_candidates_logits(self, input_embeds, search_batch_size):\n if self.search_batch_size != search_batch_size:\n print(f\"INFO: Setting candidates search_batch_size to {search_batch_size})\")\n self.search_batch_size = search_batch_size\n gc.collect() \n torch.cuda.empty_cache() \n logits = []\n for i in range(0, input_embeds.shape[0], search_batch_size):\n with torch.no_grad():\n input_embeds_batch = input_embeds[i:i+search_batch_size]\n if self.use_prefix_cache:\n # Check if we're using a model that requires special KV cache handling\n if hasattr(self.model, \"config\") and hasattr(self.model.config, \"model_type\") and self.model.config.model_type == \"llama\":\n # For LLaMA models, disable KV cache when using input embeddings with past_key_values\n outputs = self.model(inputs_embeds=input_embeds_batch)\n else:\n # Original code path for models that support the standard past_key_values format\n prefix_cache = self.prefix_cache\n current_batch_size = input_embeds_batch.shape[0]\n prefix_cache_batch = []\n for j in range(len(prefix_cache)):\n prefix_cache_batch.append([])\n for k in range(len(prefix_cache[j])):\n prefix_cache_batch[j].append(prefix_cache[j][k].expand(current_batch_size, -1, -1, -1))\n outputs = self.model(inputs_embeds=input_embeds_batch, past_key_values=prefix_cache_batch)\n else:\n outputs = self.model(inputs_embeds=input_embeds_batch)\n logits.append(outputs.logits)\n logits = torch.cat(logits, dim=0)\n return logits\n\n def generate(self, optim_str, selected_behavior_idx):\n inputs = self.before_tc + self.behaviors[selected_behavior_idx] + optim_str + self.after_tc\n encoded = self.tokenizer(inputs, return_tensors=self.return_tensors)\n with torch.no_grad():\n outputs = self.model.generate(**encoded.to(self.device), do_sample=False, max_new_tokens=16, use_cache=True)\n outputs = self.tokenizer.batch_decode(outputs)\n\n ouputs = outputs[0].replace(inputs, \"\")\n # for i, o in zip(inputs, outputs):\n # print(\"\\nbehavior:\", self.behaviors[selected_behavior_idx] + optim_str[0])\n # print(\"\\noutput:\", o.replace(i, \"\"))\n return ouputs\n\n def is_initialized(self): \n return f\"Initialized: {self.model_name_or_path}\"\n\n def get_attribute_(self, attr_name):\n return getattr(self, attr_name, None)\n \n def _prepare_input_embeddings(self, behavior_embeds, sampled_top_embeds, target_embeds, search_width):\n \"\"\"Helper method to prepare input embeddings based on use_prefix_cache setting.\n Args:\n behavior_embeds: Embeddings for behavior\n sampled_top_embeds: Embeddings for candidate suffix tokens\n target_embeds: Embeddings for target\n search_width: Number of candidates\n Returns:\n Tensor: Concatenated input embeddings\n \"\"\"\n if self.use_prefix_cache:\n return torch.cat([behavior_embeds.repeat(search_width, 1, 1),\n sampled_top_embeds,\n self.after_embeds.repeat(search_width, 1, 1),\n target_embeds.repeat(search_width, 1, 1)], dim=1)\n else:\n return torch.cat([self.before_embeds.repeat(search_width, 1, 1),\n behavior_embeds.repeat(search_width, 1, 1),\n sampled_top_embeds,\n self.after_embeds.repeat(search_width, 1, 1),\n target_embeds.repeat(search_width, 1, 1)], dim=1)\n#### Helper\ndef sample_control(control_toks, grad, search_width, topk=256, temp=1, not_allowed_tokens=None):\n torch.manual_seed(42)\n if torch.cuda.is_available():\n torch.cuda.manual_seed(42)\n torch.cuda.manual_seed_all(42)\n if not_allowed_tokens is not None:\n # grad[:, not_allowed_tokens.to(grad.device)] = np.infty\n grad = grad.clone()\n grad[:, not_allowed_tokens.to(grad.device)] = grad.max() + 1\n\n top_indices = (-grad).topk(topk, dim=1).indices\n control_toks = control_toks.to(grad.device)\n original_control_toks = control_toks.repeat(search_width, 1)\n new_token_pos = torch.arange(\n 0, \n len(control_toks), \n len(control_toks) / search_width,\n device=grad.device\n ).type(torch.int64)\n new_token_val = torch.gather(\n top_indices[new_token_pos], 1, \n torch.randint(0, topk, (search_width, 1),\n device=grad.device)\n )\n new_control_toks = original_control_toks.scatter_(1, new_token_pos.unsqueeze(-1), new_token_val)\n return new_control_toks\n\ndef get_nonascii_toks(tokenizer, device='cpu'):\n def is_ascii(s):\n return s.isascii() and s.isprintable()\n ascii_toks = []\n for i in range(3, tokenizer.vocab_size):\n if not is_ascii(tokenizer.decode([i])):\n ascii_toks.append(i)\n if tokenizer.bos_token_id is not None:\n ascii_toks.append(tokenizer.bos_token_id)\n if tokenizer.eos_token_id is not None:\n ascii_toks.append(tokenizer.eos_token_id)\n if tokenizer.pad_token_id is not None:\n ascii_toks.append(tokenizer.pad_token_id)\n if tokenizer.unk_token_id is not None:\n ascii_toks.append(tokenizer.unk_token_id)\n\n if \"Baichuan2\" in tokenizer.name_or_path:\n ascii_toks += [i for i in range(101, 1000)]\n return torch.tensor(ascii_toks, device=device)\n\ndef _cw_loss(\n logits: torch.FloatTensor,\n target_ids: torch.LongTensor,\n cw_margin: float = 1e-3,\n dim: int = -1,\n) -> torch.FloatTensor:\n \"\"\"CW loss.\n Hinge loss on the difference between the largest and the target logits.\n \"\"\"\n input_shape = target_ids.shape\n assert logits.shape[:-1] == input_shape, (logits.shape, input_shape)\n target_ids = target_ids.unsqueeze(-1)\n tgt_logits = logits.gather(dim, target_ids).squeeze(-1)\n # Set logits of target tok very low (-1e3) so it cannot be the largest\n tmp_logits = logits.clone()\n tmp_logits.scatter_(dim, target_ids, -1e3)\n largest_non_tgt_logits = tmp_logits.max(dim).values\n loss = largest_non_tgt_logits - tgt_logits\n loss = loss.clamp_min(-cw_margin).mean(-1)\n if len(input_shape) == 1:\n assert loss.ndim == 0, loss.shape\n else:\n assert loss.shape == input_shape[:1], loss.shape\n return loss" } ] }, { "paper_id": 30, "paper_details": { "title": "SafeDecoding: Defending against Jailbreak Attacks via Safety-Aware Decoding", "url": "https://arxiv.org/abs/2402.08983" }, "repo_original_url": "https://github.com/uw-nsl/SafeDecoding", "project_path": "Benchmark/30-SafeDecode/SafeDecoding-main", "enviorment_name": "SafeDecoding", "file_organization": "\nSafeDecoding-main/\n README.md\n LICENSE\n requirements.txt\n\n datasets/\n advbench_harmful_behaviors.json\n custom_prompts.json\n harmful_behaviors_custom.json\n seed_reject.json\n\n exp/\n defense.py\n finetune.py\n safe_eval.py\n\n figs/\n overview.gif\n overview.png\n\n just_eval/\n just_eval/\n evaluate.py\n reward_model.py\n utils.py\n _version.py\n __init__.py\n just_eval.egg-info/\n dependency_links.txt\n entry_points.txt\n PKG-INFO\n requires.txt\n SOURCES.txt\n top_level.txt\n setup.py\n README.md\n\n lora_modules/\n dolphin/\n adapter_config.json\n adapter_model.bin\n ft_datasets_dolphin.json\n falcon/\n adapter_config.json\n adapter_model.bin\n ft_datasets_falcon.json\n guanaco/\n adapter_config.json\n adapter_model.bin\n ft_datasets_guanaco.json\n llama2/\n adapter_config.json\n adapter_model.bin\n ft_datasets_llama2.json\n vicuna/\n adapter_config.json\n adapter_model.bin\n ft_datasets_vicuna.json\n\n mt_bench/\n clean_judgment.py\n common.py\n compute_agreement.py\n download_mt_bench_pregenerated.py\n gen_api_answer.py\n gen_judgment.py\n gen_model_answer.py\n qa_browser.py\n show_result.py\n README.md\n data/\n judge_prompts.jsonl\n mt_bench/\n question.jsonl\n reference_answer/\n gpt-4.jsonl\n vicuna_bench/\n question.jsonl\n reference_answer/\n gpt-4.jsonl\n\n utils/\n bpe.py\n generate.py\n model.py\n opt_utils.py\n ppl_calculator.py\n safe_decoding.py\n string_utils.py\n subword_nmt.voc\n", "latex_code_path": "Benchmark/30-SafeDecode/arXiv-2402.08983v4", "task_details": [ { "task_id": 0, "indent": 2, "script": "\npython exp/defense.py --disable_GPT_judge\n", "completion_path": "./utils/safe_decoding.py", "latex_code": "\n\\textbf{Step 1: Construct the Sample Space $\\mathcal{V}^{(c)}_{n}$.}\nAt the $n$-th step in the inference time, we forward a token sequence $x_{1:n-1}$ to both the original and expert models.\nWe denote the set of tokens that can be possibly sampled by the original model and expert model as $\\mathcal{V}_{n}$ and $\\mathcal{V}'_{n}$, respectively.\nWithout loss of generality, we assume that the tokens in $\\mathcal{V}_{n}$ and $\\mathcal{V}'_{n}$ are sorted by probability in descending order.\nThen \\ours~constructs a sample space $\\mathcal{V}^{(c)}_{n}$ as the intersection between top $k$ tokens from $\\mathcal{V}_{n}$ and $\\mathcal{V}'_{n}$, which is represented as:\n\\begin{equation*}\n \\mathcal{V}_{n}^{(c)} = \\underset{S=\\mathcal{V}^k_{n}\\cap \\mathcal{V}^{\\prime^{k}}_{n} }{\\arg \\min} k \\text{ s.t. } |S| \\geq c.\n\\end{equation*}\nHere $\\mathcal{V}^k_{n}$ and $\\mathcal{V}^{\\prime^{k}}_{n} $ represent the top $k$ tokens from $\\mathcal{V}_{n}$ and $\\mathcal{V}'_{n}$, respectively.\nOur intuition of taking the intersection is to leverage the advantages of both the original LLM and the expert model.\nSpecifically, the original LLM has been trained on a vast corpus, and thus the tokens in $\\mathcal{V}_n$ are more likely to generate diverse and high-quality responses to benign input queries; the expert model has been fine-tuned to prioritize safety, and hence the tokens in $\\mathcal{V}'_n$ are more likely to be aligned with human values when the input query is malicious.\n\nNote that here $c$ is a tunable parameter of \\ours~that controls the size of sample space. \nWhen the value of $c$ is too small, the sample space becomes limited, which restricts the possible tokens that can be chosen at inference time.\nConsequently, the responses generated with a small value of $c$ may lack diversity and be less helpful to users.\n", "namespace": "utils.safe_decoding.SafeDecoding.construct_sample_space", "type": "method", "signature_position": [ 20, 20 ], "body_position": [ 21, 36 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Initialize common token set and iteration range starting from c\n# Maps to LaTeX's \"find minimal k\" with initial condition |S| \u2265 c\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\ncommon_tokens = set()\niter_range = self.num_common_tokens\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Iterative expansion of token candidates until meeting size requirement\n# Implements the stopping condition from LaTeX equation |S| \u2265 c\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nwhile len(common_tokens) < self.num_common_tokens:\n# [End Snippet 2]\n\n # -----------------------------------------------------------------------\n # Snippet 3: Extract current top-k candidates from both models\n # Corresponds to V_n^k and V'_n^k in LaTeX notation\n # -----------------------------------------------------------------------\n # [Begin Snippet 3]\n current_indices_base = sorted_indices_base[:iter_range]\n current_indices_expert = sorted_indices_expert[:iter_range]\n # [End Snippet 3]\n\n # -----------------------------------------------------------------------\n # Snippet 4: Calculate intersection of current top-k candidates\n # Implements the set operation S = V_n^k \u2229 V'_n^k from LaTeX\n # -----------------------------------------------------------------------\n # [Begin Snippet 4]\n common_in_iteration = set(current_indices_base.tolist()) & set(current_indices_expert.tolist())\n common_tokens.update(common_in_iteration)\n # [End Snippet 4]\n\n # -----------------------------------------------------------------------\n # Snippet 5: Expand search range with termination condition\n # Handles edge case where models don't have enough overlapping tokens\n # -----------------------------------------------------------------------\n # [Begin Snippet 5]\n iter_range += 1\n if iter_range > min(len(sorted_indices_base), len(sorted_indices_expert)):\n break\n # [End Snippet 5]\n\n# ---------------------------------------------------------------------------\n# Snippet 6: Convert final token set to device-matched tensor\n# Ensures compatibility with model's computation device\n# ---------------------------------------------------------------------------\n# [Begin Snippet 6]\noutput = torch.tensor(list(common_tokens), device=self.model.device)\nreturn output\n# [End Snippet 6]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n Missing Details:\n - The LaTeX snippet describes an optimization to find the smallest \\(k\\) such that the intersection of top-k tokens has size at least \\(c\\). This implementation uses an iterative approach (increasing the range of top tokens step-by-step) until at least \\(c\\) tokens are found in the intersection.\n\n Mismatched Details:\n - None\n", "Missing_details": [ "\n- The LaTeX snippet describes an optimization to find the smallest \\(k\\) such that the intersection of top-k tokens has size at least \\(c\\). This implementation uses an iterative approach (increasing the range of top tokens step-by-step) until at least \\(c\\) tokens are found in the intersection.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - sorted_indices_base (torch.Tensor, dtype=torch.long, shape=[vocab_size]):\n Sorted token indices from the original model, in descending order of probability.\n - sorted_indices_expert (torch.Tensor, dtype=torch.long, shape=[vocab_size]):\n Sorted token indices from the expert model, in descending order of probability.\n - self.num_common_tokens (int): Minimum number of common tokens to be found in the intersection of top-k tokens.\n", "Arguments_list": [ { "name": "sorted_indices_base", "string": "\n- sorted_indices_base (torch.Tensor, dtype=torch.long, shape=[vocab_size]):\n Sorted token indices from the original model, in descending order of probability.\n", "dependency": null }, { "name": "sorted_indices_expert", "string": "\n- sorted_indices_expert (torch.Tensor, dtype=torch.long, shape=[vocab_size]):\n Sorted token indices from the expert model, in descending order of probability.\n", "dependency": null }, { "name": "self.num_common_tokens", "string": "\n- self.num_common_tokens (int): Minimum number of common tokens to be found in the intersection of top-k tokens.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-file Dependencies:\n - SafeDecoding.model\n \n - Cross-file Dependencies: \n - None\n", "intra_file": [ "SafeDecoding.model" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.tensor\n", "list": [ "torch.tensor" ] }, "Return": { "Return_String": "\nOutput Variables:\n - output (torch.Tensor, dtype=torch.long, shape=[>=num_common_tokens]):\n Final tensor of token indices that belong to both models\u2019 top sets, ensuring\n at least num_common_tokens (self.num_common_tokens) tokens are collected.\n", "Return_list": [ { "name": "output", "string": "\n- output (torch.Tensor, dtype=torch.long, shape=[>=num_common_tokens]):\n Final tensor of token indices that belong to both models\u2019 top sets, ensuring\n at least num_common_tokens (self.num_common_tokens) tokens are collected.\n", "dependency": null } ] }, "ori_python_file": "import torch\nimport numpy as np\nimport copy\nimport logging\nfrom peft import PeftModel, PeftModelForCausalLM\n\nclass SafeDecoding:\n def __init__(self, model, tokenizer, adapter_names, alpha=1, first_m=5, top_k=10, num_common_tokens=3, verbose=False):\n self.model = model\n self.tokenizer = tokenizer\n self.adapter_names = adapter_names\n self.alpha = alpha\n self.first_m = first_m \n self.top_k = top_k\n self.num_common_tokens = num_common_tokens\n self.verbose = verbose\n\n logging.info(\"SafeDecoding initialized.\")\n\n def construct_sample_space(self, sorted_indices_base, sorted_indices_expert):\n common_tokens = set()\n iter_range = self.num_common_tokens\n \n while len(common_tokens) < self.num_common_tokens:\n current_indices_base = sorted_indices_base[:iter_range]\n current_indices_expert = sorted_indices_expert[:iter_range]\n\n common_in_iteration = set(current_indices_base.tolist()) & set(current_indices_expert.tolist())\n common_tokens.update(common_in_iteration)\n\n iter_range += 1\n\n if iter_range > min(len(sorted_indices_base), len(sorted_indices_expert)):\n break\n \n return torch.tensor(list(common_tokens), device=self.model.device)\n \n def define_probability_function(self, intersection_indices, scores_base, scores_expert):\n updated_scores = []\n \n for token_id in intersection_indices:\n # Steer probabilities according to the equation in the paper\n prob_diff = torch.exp(scores_expert[token_id]) - torch.exp(scores_base[token_id])\n updated_prob = torch.exp(scores_base[token_id]) + self.alpha * prob_diff\n # Floor probability to avoid log(0)\n updated_prob = updated_prob if updated_prob > 0 else torch.tensor(1e-8, device=self.model.device)\n updated_score = torch.log(updated_prob)\n updated_scores.append(updated_score)\n\n # Normalize probabilities to sum to 1\n normalized_probs = torch.nn.functional.softmax(torch.tensor(updated_scores).float(), dim=0)\n\n # Sort tokens by probability\n sorted_indices = sorted(range(len(normalized_probs)), key=lambda i: normalized_probs[i], reverse=True)\n sorted_probs = torch.tensor([normalized_probs[i] for i in sorted_indices])\n sorted_token_ids = [intersection_indices[i] for i in sorted_indices]\n \n return sorted_token_ids, sorted_probs\n \n def safedecoding_lora(self, inputs, gen_config=None):\n if gen_config is None:\n gen_config = self.model.generation_config\n\n max_token_len = gen_config.max_new_tokens\n do_sample = gen_config.do_sample\n\n # Override the generation config for our decoding\n gen_config.max_new_tokens = 1 # We generate one token at a time\n gen_config.do_sample = False # We use greedy decoding\n\n generated_sequence = []\n if self.verbose:\n logging.info(f\"Generation config: {gen_config}\")\n\n inputs = {k:v.cuda(self.model.device) for k,v in inputs.items()}\n input_len = inputs['input_ids'].shape[1]\n\n step = 1 # Keep track of generation steps\n while step <= min(max_token_len, self.first_m): # Loop until we reach the first m tokens\n # Generate the next token\n # duplicate inputs for two original and expert model\n inputs_duplicated = {k:v.repeat(2,1) for k,v in inputs.items()}\n\n outputs = self.model.generate(**inputs_duplicated,\n adapter_names=self.adapter_names,\n generation_config=gen_config,\n pad_token_id=self.tokenizer.pad_token_id,\n return_dict_in_generate=True,\n output_scores=True,)\n \n output_base = copy.deepcopy(outputs)\n output_expert = copy.deepcopy(outputs)\n output_base.sequences = output_base.sequences[0].unsqueeze(0)\n output_base.scores = output_base.scores[0][0].unsqueeze(0)\n output_expert.sequences = output_expert.sequences[1].unsqueeze(0)\n output_expert.scores = output_expert.scores[0][1].unsqueeze(0)\n\n # Process the scores to get the top tokens\n k = self.top_k # Change this to display more or less tokens\n scores_base = output_base.scores[-1].squeeze() # Get the scores of the last token\n scores_base = torch.nn.functional.log_softmax(scores_base, dim=-1)\n topk_scores_base, topk_indices_base = scores_base.topk(k) \n \n scores_expert = output_expert.scores[-1].squeeze() # Get the scores of the last token\n scores_expert = torch.nn.functional.log_softmax(scores_expert, dim=-1)\n topk_scores_expert, topk_indices_expert = scores_expert.topk(k) \n\n sorted_indices_base = torch.argsort(scores_base, descending=True)\n sorted_indices_expert = torch.argsort(scores_expert, descending=True)\n\n # Display the top tokens from each model if in verbose mode\n if self.verbose and step == 1:\n self._log_model_tokens(\"Original Model\", topk_scores_base, topk_indices_base)\n self._log_model_tokens(\"Expert Model\", topk_scores_expert, topk_indices_expert)\n\n # Step 1: Construct the sample space\n intersection_indices = self.construct_sample_space(sorted_indices_base, sorted_indices_expert)\n \n # Step 2: Define the probability function\n sorted_token_ids, sorted_probs = self.define_probability_function(\n intersection_indices, scores_base, scores_expert\n )\n\n # Log the final probabilities\n if self.verbose:\n self._log_final_probabilities(step, sorted_probs, sorted_token_ids)\n\n ### Sample the next token\n if do_sample == False:\n # Greedy decoding\n selected_token_id = sorted_token_ids[0].unsqueeze(0)\n elif gen_config.top_p != None and do_sample == True:\n # Top-p sampling\n selected_token_id = self._apply_top_p_sampling(sorted_token_ids, sorted_probs, gen_config.top_p)\n else:\n raise ValueError(\"Please set do_sample to False or top_p to a value.\")\n\n if self.verbose:\n logging.info(f\"Selected token: {self.tokenizer.decode(selected_token_id.item())}, ID: {selected_token_id.item()}\")\n generated_sequence.append(selected_token_id.item())\n\n # if the chosen token id is eos, then stop\n if selected_token_id.item() == self.tokenizer.eos_token_id:\n break\n\n inputs['input_ids'] = torch.cat([inputs['input_ids'], selected_token_id.unsqueeze(0)], dim=1)\n inputs['attention_mask'] = torch.cat([inputs['attention_mask'], torch.tensor([[1]], device=self.model.device)], dim=1)\n\n step += 1\n\n # Free up memory\n del output_base, output_expert\n\n # Use the normal model to generate the rest of the tokens\n # Early stop if the last token is eos\n if generated_sequence[-1] == self.tokenizer.eos_token_id:\n logging.info(\"Early stop triggered.\")\n else:\n remaining_steps = max_token_len - min(max_token_len, self.first_m)\n gen_config.max_new_tokens = remaining_steps\n gen_config.do_sample = do_sample\n output_base = self.model.generate(**inputs,\n adapter_names=[\"base\"],\n generation_config=gen_config,\n pad_token_id=self.tokenizer.pad_token_id,\n return_dict_in_generate=True,\n output_scores=True,)\n \n generated_sequence = output_base.sequences[0].tolist()[input_len:]\n\n # logging.info generated sequence\n logging.info(f\"Generated sequence: {self.tokenizer.decode(generated_sequence)}\")\n\n return self.tokenizer.decode(generated_sequence), len(generated_sequence)\n \n def _apply_top_p_sampling(self, sorted_token_ids, sorted_probs, top_p):\n \"\"\"Apply top-p (nucleus) sampling to select the next token\"\"\"\n cumulative_probs = torch.cumsum(sorted_probs, dim=-1)\n p_index = torch.where(cumulative_probs >= top_p)[0][0]\n sorted_top_p_token_ids = sorted_token_ids[:p_index + 1]\n sorted_top_p_probs = sorted_probs[:p_index + 1]\n sorted_top_p_scores = torch.log(sorted_top_p_probs)\n \n if self.verbose:\n logging.info(f\"Top-p token ids: {sorted_top_p_token_ids}\")\n logging.info(f\"Top-p scores: {sorted_top_p_scores}\")\n logging.info(f\"Top-p probabilities: {sorted_top_p_probs}\")\n \n # Sample from the top-p tokens\n return sorted_top_p_token_ids[torch.multinomial(\n torch.softmax(sorted_top_p_scores, dim=-1), 1\n )].unsqueeze(0)\n \n def _log_model_tokens(self, model_name, scores, token_indices):\n \"\"\"Helper method to log token information for debugging\"\"\"\n logging.info(\"\\n-----------------------------------------------\")\n logging.info(f\"Generation Step 1\")\n logging.info(model_name)\n logging.info(\"|No. | Token ID | Token | Log Prob | Prob |\")\n logging.info(\"|----|----------|---------|----------|---------|\")\n for idx, (score, token_id) in enumerate(zip(scores, token_indices)):\n token = self.tokenizer.decode(token_id.item())\n prob = torch.exp(score)\n logging.info(f\"{idx+1:4d} | {token_id:8d} | {token:7s} | {score:.3f} | {prob:.2%} |\")\n \n def _log_final_probabilities(self, step, probs, token_ids):\n \"\"\"Helper method to log final token probabilities\"\"\"\n logging.info(\"\\n-----------------------------------------------\")\n logging.info(f\"Generation Step {step}\")\n logging.info(\"|No. | Token ID | Token | Log Prob | Prob |\")\n logging.info(\"|----|----------|---------|----------|---------|\")\n for idx, (prob, token_id) in enumerate(zip(probs, token_ids)):\n token = self.tokenizer.decode(token_id.item())\n score = torch.log(prob)\n logging.info(f\"{idx+1:4d} | {token_id:8d} | {token:7s} | {score:.3f} | {prob:.2%} |\")\n \n def generate_baseline(self, inputs, adapter_name = [\"base\"], gen_config=None):\n if gen_config is None:\n gen_config = self.model.generation_config\n \n if self.verbose:\n logging.info(f\"Generation config: {gen_config}\")\n\n inputs = {k:v.cuda(self.model.device) for k,v in inputs.items()}\n\n output_base = self.model.generate(**inputs,\n adapter_names=adapter_name,\n generation_config=gen_config,\n pad_token_id=self.tokenizer.pad_token_id,\n return_dict_in_generate=True,\n output_scores=True,)\n \n generated_sequence = output_base.sequences[0][inputs[\"input_ids\"].shape[1]:]\n logging.info(f\"Generated sequence: {self.tokenizer.decode(generated_sequence)}\")\n \n return self.tokenizer.decode(generated_sequence), len(generated_sequence)" }, { "task_id": 1, "indent": 2, "script": "\npython exp/defense.py --disable_GPT_judge\n", "latex_code": "\n\\textbf{Step 2: Define the Probability Function $P_n$.}\nWe use $\\theta$ and $\\theta'$ to denote the original and expert models, respectively.\nFor a token sequence $x_{1:n-1}$, we construct probability function $P_n$ over $\\mathcal{V}_n^{(c)}$ as \n\\begin{multline}\\label{eq:prob function}\n P_n (x | x_{1:n-1})=p_\\theta(x | x_{1:n-1})\\\\ \n + \\alpha (p_{\\theta'}(x | x_{1:n-1})-p_\\theta(x | x_{1:n-1})),\n\\end{multline}\nwhere $\\alpha \\geq 0$ is a hyper-parameter that determines the weights assigned to the original model and expert model.\nWe finally normalize the values obtained in Eq. \\eqref{eq:prob function} such that $\\sum_{x\\in \\mathcal{V}_{n}^{(c)}}P_{n}(x)=1$. \n\nWe characterize $P_n$ by considering the following two cases.\nWhen a query is benign, both the original and expert models are likely to respond positively.\nTherefore, sampling a token from the sample space $\\mathcal{V}^{(c)}_n$ will satisfy the query and ensure the helpfulness of LLM.\nWhen a query is malicious and aims to jailbreak the LLM, we expect to observe a discrepancy between $p_{\\theta'}(x|x_{1:n-1})$ and $p_\\theta(x|x_{1:n-1})$.\nThat is, the original model responds to the query with positive affirmation, whereas the expert model would decline the query due to safety alignment.\nConsequently, $p_{\\theta'}(x | x_{1:n-1})-p_\\theta(x | x_{1:n-1})>0$ if token $x$ aligns with human values and $<0$ if $x$ induces unsafe behavior.\nHence, Eq. \\eqref{eq:prob function} attenuates the token probabilities that satisfy the attacker's goal and amplifies the token probabilities that are aligned with human values. \n\nThe sample space $\\mathcal{V}_n^{(c)}$ and probability function $P_n$ constructed by \\ours~are compatible with all existing sampling methods, including top-$p$, top-$k$, greedy, and beam search. Developers of LLMs have the flexibility to combine \\ours~with their preferred sampling method based on their needs.\n\nAppendix \\ref{sec:finetune not enough} presents examples to emphasize the importance of the Inference phase, thus justifying our two-phase approach.\n", "completion_path": "./utils/safe_decoding.py", "namespace": "utils.safe_decoding.SafeDecoding.define_probability_function", "type": "method", "signature_position": [ 38, 38 ], "body_position": [ 39, 58 ], "ReferenceCode_With_Comments": "\nupdated_scores = []\n\nfor token_id in intersection_indices:\n # ---------------------------------------------------------------------------\n # Snippet 1: Calculates the difference in probabilities between the expert and original models for the current token.\n # It corresponds to the (\ud835\udc5d\ud835\udf03\u2032(\ud835\udc65|\ud835\udc651:\ud835\udc5b\u22121)\u2212\ud835\udc5d\ud835\udf03(\ud835\udc65|\ud835\udc651:\ud835\udc5b\u22121)) part of Equation (1).\n # ---------------------------------------------------------------------------\n # [Begin Snippet 1]\n prob_diff = torch.exp(scores_expert[token_id]) - torch.exp(scores_base[token_id])\n # [End Snippet 1]\n # ---------------------------------------------------------------------------\n # Snippet 2: Updates the probability of the current token by adding the scaled difference to the original model's probability.\n # The scaling factor 'alpha' is used as defined in LaTeX. This corresponds to Equation (1):\n # \ud835\udc43\ud835\udc5b(\ud835\udc65|\ud835\udc651:\ud835\udc5b\u22121)=\ud835\udc5d\ud835\udf03(\ud835\udc65|\ud835\udc651:\ud835\udc5b\u22121) + \ud835\udefc(\ud835\udc5d\ud835\udf03\u2032(\ud835\udc65|\ud835\udc651:\ud835\udc5b\u22121)\u2212\ud835\udc5d\ud835\udf03(\ud835\udc65|\ud835\udc651:\ud835\udc5b\u22121))\n # ---------------------------------------------------------------------------\n # [Begin Snippet 2]\n updated_prob = torch.exp(scores_base[token_id]) + self.alpha * prob_diff\n # [End Snippet 2]\n\n # ---------------------------------------------------------------------------\n # Snippet 3: Ensures the updated probability is not zero to avoid issues with taking the logarithm. Implements a numerical stability check.\n # Missing detail: The LaTeX code doesn't explicitly include this, it's a standard practice in numerical computation.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 3]\n updated_prob = updated_prob if updated_prob > 0 else torch.tensor(1e-8, device=self.model.device)\n # [End Snippet 3]\n\n # ---------------------------------------------------------------------------\n # Snippet 4: Converts the probability back to the log domain.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 4]\n updated_score = torch.log(updated_prob)\n updated_scores.append(updated_score)\n # [End Snippet 4]\n\n\n# ---------------------------------------------------------------------------\n# Snippet 5: According to the LaTeX, after computing the updated probabilities\n# we normalize them to ensure they sum to 1, allowing subsequent sampling\n# methods (top-p, top-k, etc.) to work seamlessly.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nnormalized_probs = torch.nn.functional.softmax(torch.tensor(updated_scores).float(), dim=0)\n\nsorted_indices = sorted(range(len(normalized_probs)), key=lambda i: normalized_probs[i], reverse=True)\nsorted_probs = torch.tensor([normalized_probs[i] for i in sorted_indices])\nsorted_token_ids = [intersection_indices[i] for i in sorted_indices]\n# [End Snippet 5]\n\n# ---------------------------------------------------------------------------\n# Snippet 6: The final list of sorted tokens, along with their probabilities,\n# represents the newly defined distribution P_n, completing the step of\n# amplifying safe tokens while attenuating malicious ones.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 6]\nreturn sorted_token_ids, sorted_probs\n# [End Snippet 6]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Detail:\n - A small floor value (1e-8) is applied here to ensure numerical stability when calculating the logarithm of the updated probability.\n - The LaTeX description does not specify that the initial model scores (logits) must be converted to probabilities (e.g., via exponentiation) before computing the difference between the expert and original models. In the reference implementation, this conversion is essential to correctly combine the contributions.\n - The LaTeX omits the step of converting the updated probabilities back to the logarithmic domain (by taking the logarithm) after the combination. This conversion is used in the reference code to maintain numerical stability and proper scaling.\n \n - Mismatched Detail:\n - None\n", "Missing_details": [ "\n- A small floor value (1e-8) is applied here to ensure numerical stability when calculating the logarithm of the updated probability.\n", "\n- The LaTeX description does not specify that the initial model scores (logits) must be converted to probabilities (e.g., via exponentiation) before computing the difference between the expert and original models. In the reference implementation, this conversion is essential to correctly combine the contributions.\n", "\n- The LaTeX omits the step of converting the updated probabilities back to the logarithmic domain (by taking the logarithm) after the combination. This conversion is used in the reference code to maintain numerical stability and proper scaling.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - intersection_indices (torch.Tensor, dtype=torch.long, shape=[num_common_tokens]):\n A set of token indices that appear in both the original and expert\n model top-ranked candidates, representing the sample space V_n^(c).\n - scores_base (torch.Tensor, dtype=torch.float32, shape=[vocabulary_size]):\n Logits (often pre-softmax or log-softmax scores) from the original (base) model,\n evaluated at the current decoding step.\n - scores_expert (torch.Tensor, dtype=torch.float32, shape=[vocabulary_size]):\n Logits from the expert model at the current decoding step.\n", "Arguments_list": [ { "name": "intersection_indices", "string": "\n- intersection_indices (torch.Tensor, dtype=torch.long, shape=[num_common_tokens]):\n A set of token indices that appear in both the original and expert\n model top-ranked candidates, representing the sample space V_n^(c).\n", "dependency": null }, { "name": "scores_base", "string": "\n- scores_base (torch.Tensor, dtype=torch.float32, shape=[vocabulary_size]):\n Logits (often pre-softmax or log-softmax scores) from the original (base) model,\n evaluated at the current decoding step.\n", "dependency": null }, { "name": "scores_expert", "string": "\n- scores_expert (torch.Tensor, dtype=torch.float32, shape=[vocabulary_size]):\n Logits from the expert model at the current decoding step.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-file Dependencies:\n - SafeDecoding.alpha\n - SafeDecoding.model\n \n - Cross-file Dependencies:\n - None\n", "intra_file": [ "SafeDecoding.alpha", "SafeDecoding.model" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.exp\n - torch.log\n - torch.nn.functional.softmax\n - torch.tensor\n", "list": [ "torch.exp", "torch.log", "torch.nn.functional.softmax", "torch.tensor" ] }, "Return": { "Return_String": "\nOutput Variables:\n - sorted_token_ids (list[int]):\n Token IDs (num_common_tokens) from intersection_indices, sorted by the newly defined probability\n in descending order (most probable to least probable).\n - sorted_probs (torch.Tensor, dtype=torch.float32, shape=[num_common_tokens]):\n Normalized probabilities (after combining original and expert model contributions),\n sorted in descending order.\n", "Return_list": [ { "name": "sorted_token_ids", "string": "\n- sorted_token_ids (list[int]):\n Token IDs (num_common_tokens) from intersection_indices, sorted by the newly defined probability\n in descending order (most probable to least probable).\n", "dependency": null }, { "name": "sorted_probs", "string": "\n- sorted_probs (torch.Tensor, dtype=torch.float32, shape=[num_common_tokens]):\n Normalized probabilities (after combining original and expert model contributions),\n sorted in descending order.\n", "dependency": null } ] }, "ori_python_file": "import torch\nimport numpy as np\nimport copy\nimport logging\nfrom peft import PeftModel, PeftModelForCausalLM\n\nclass SafeDecoding:\n def __init__(self, model, tokenizer, adapter_names, alpha=1, first_m=5, top_k=10, num_common_tokens=3, verbose=False):\n self.model = model\n self.tokenizer = tokenizer\n self.adapter_names = adapter_names\n self.alpha = alpha\n self.first_m = first_m \n self.top_k = top_k\n self.num_common_tokens = num_common_tokens\n self.verbose = verbose\n\n logging.info(\"SafeDecoding initialized.\")\n\n def construct_sample_space(self, sorted_indices_base, sorted_indices_expert):\n common_tokens = set()\n iter_range = self.num_common_tokens\n \n while len(common_tokens) < self.num_common_tokens:\n current_indices_base = sorted_indices_base[:iter_range]\n current_indices_expert = sorted_indices_expert[:iter_range]\n\n common_in_iteration = set(current_indices_base.tolist()) & set(current_indices_expert.tolist())\n common_tokens.update(common_in_iteration)\n\n iter_range += 1\n\n if iter_range > min(len(sorted_indices_base), len(sorted_indices_expert)):\n break\n \n return torch.tensor(list(common_tokens), device=self.model.device)\n \n def define_probability_function(self, intersection_indices, scores_base, scores_expert):\n updated_scores = []\n \n for token_id in intersection_indices:\n # Steer probabilities according to the equation in the paper\n prob_diff = torch.exp(scores_expert[token_id]) - torch.exp(scores_base[token_id])\n updated_prob = torch.exp(scores_base[token_id]) + self.alpha * prob_diff\n # Floor probability to avoid log(0)\n updated_prob = updated_prob if updated_prob > 0 else torch.tensor(1e-8, device=self.model.device)\n updated_score = torch.log(updated_prob)\n updated_scores.append(updated_score)\n\n # Normalize probabilities to sum to 1\n normalized_probs = torch.nn.functional.softmax(torch.tensor(updated_scores).float(), dim=0)\n\n # Sort tokens by probability\n sorted_indices = sorted(range(len(normalized_probs)), key=lambda i: normalized_probs[i], reverse=True)\n sorted_probs = torch.tensor([normalized_probs[i] for i in sorted_indices])\n sorted_token_ids = [intersection_indices[i] for i in sorted_indices]\n \n return sorted_token_ids, sorted_probs\n \n def safedecoding_lora(self, inputs, gen_config=None):\n if gen_config is None:\n gen_config = self.model.generation_config\n\n max_token_len = gen_config.max_new_tokens\n do_sample = gen_config.do_sample\n\n # Override the generation config for our decoding\n gen_config.max_new_tokens = 1 # We generate one token at a time\n gen_config.do_sample = False # We use greedy decoding\n\n generated_sequence = []\n if self.verbose:\n logging.info(f\"Generation config: {gen_config}\")\n\n inputs = {k:v.cuda(self.model.device) for k,v in inputs.items()}\n input_len = inputs['input_ids'].shape[1]\n\n step = 1 # Keep track of generation steps\n while step <= min(max_token_len, self.first_m): # Loop until we reach the first m tokens\n # Generate the next token\n # duplicate inputs for two original and expert model\n inputs_duplicated = {k:v.repeat(2,1) for k,v in inputs.items()}\n\n outputs = self.model.generate(**inputs_duplicated,\n adapter_names=self.adapter_names,\n generation_config=gen_config,\n pad_token_id=self.tokenizer.pad_token_id,\n return_dict_in_generate=True,\n output_scores=True,)\n \n output_base = copy.deepcopy(outputs)\n output_expert = copy.deepcopy(outputs)\n output_base.sequences = output_base.sequences[0].unsqueeze(0)\n output_base.scores = output_base.scores[0][0].unsqueeze(0)\n output_expert.sequences = output_expert.sequences[1].unsqueeze(0)\n output_expert.scores = output_expert.scores[0][1].unsqueeze(0)\n\n # Process the scores to get the top tokens\n k = self.top_k # Change this to display more or less tokens\n scores_base = output_base.scores[-1].squeeze() # Get the scores of the last token\n scores_base = torch.nn.functional.log_softmax(scores_base, dim=-1)\n topk_scores_base, topk_indices_base = scores_base.topk(k) \n \n scores_expert = output_expert.scores[-1].squeeze() # Get the scores of the last token\n scores_expert = torch.nn.functional.log_softmax(scores_expert, dim=-1)\n topk_scores_expert, topk_indices_expert = scores_expert.topk(k) \n\n sorted_indices_base = torch.argsort(scores_base, descending=True)\n sorted_indices_expert = torch.argsort(scores_expert, descending=True)\n\n # Display the top tokens from each model if in verbose mode\n if self.verbose and step == 1:\n self._log_model_tokens(\"Original Model\", topk_scores_base, topk_indices_base)\n self._log_model_tokens(\"Expert Model\", topk_scores_expert, topk_indices_expert)\n\n # Step 1: Construct the sample space\n intersection_indices = self.construct_sample_space(sorted_indices_base, sorted_indices_expert)\n \n # Step 2: Define the probability function\n sorted_token_ids, sorted_probs = self.define_probability_function(\n intersection_indices, scores_base, scores_expert\n )\n\n # Log the final probabilities\n if self.verbose:\n self._log_final_probabilities(step, sorted_probs, sorted_token_ids)\n\n ### Sample the next token\n if do_sample == False:\n # Greedy decoding\n selected_token_id = sorted_token_ids[0].unsqueeze(0)\n elif gen_config.top_p != None and do_sample == True:\n # Top-p sampling\n selected_token_id = self._apply_top_p_sampling(sorted_token_ids, sorted_probs, gen_config.top_p)\n else:\n raise ValueError(\"Please set do_sample to False or top_p to a value.\")\n\n if self.verbose:\n logging.info(f\"Selected token: {self.tokenizer.decode(selected_token_id.item())}, ID: {selected_token_id.item()}\")\n generated_sequence.append(selected_token_id.item())\n\n # if the chosen token id is eos, then stop\n if selected_token_id.item() == self.tokenizer.eos_token_id:\n break\n\n inputs['input_ids'] = torch.cat([inputs['input_ids'], selected_token_id.unsqueeze(0)], dim=1)\n inputs['attention_mask'] = torch.cat([inputs['attention_mask'], torch.tensor([[1]], device=self.model.device)], dim=1)\n\n step += 1\n\n # Free up memory\n del output_base, output_expert\n\n # Use the normal model to generate the rest of the tokens\n # Early stop if the last token is eos\n if generated_sequence[-1] == self.tokenizer.eos_token_id:\n logging.info(\"Early stop triggered.\")\n else:\n remaining_steps = max_token_len - min(max_token_len, self.first_m)\n gen_config.max_new_tokens = remaining_steps\n gen_config.do_sample = do_sample\n output_base = self.model.generate(**inputs,\n adapter_names=[\"base\"],\n generation_config=gen_config,\n pad_token_id=self.tokenizer.pad_token_id,\n return_dict_in_generate=True,\n output_scores=True,)\n \n generated_sequence = output_base.sequences[0].tolist()[input_len:]\n\n # logging.info generated sequence\n logging.info(f\"Generated sequence: {self.tokenizer.decode(generated_sequence)}\")\n\n return self.tokenizer.decode(generated_sequence), len(generated_sequence)\n \n def _apply_top_p_sampling(self, sorted_token_ids, sorted_probs, top_p):\n \"\"\"Apply top-p (nucleus) sampling to select the next token\"\"\"\n cumulative_probs = torch.cumsum(sorted_probs, dim=-1)\n p_index = torch.where(cumulative_probs >= top_p)[0][0]\n sorted_top_p_token_ids = sorted_token_ids[:p_index + 1]\n sorted_top_p_probs = sorted_probs[:p_index + 1]\n sorted_top_p_scores = torch.log(sorted_top_p_probs)\n \n if self.verbose:\n logging.info(f\"Top-p token ids: {sorted_top_p_token_ids}\")\n logging.info(f\"Top-p scores: {sorted_top_p_scores}\")\n logging.info(f\"Top-p probabilities: {sorted_top_p_probs}\")\n \n # Sample from the top-p tokens\n return sorted_top_p_token_ids[torch.multinomial(\n torch.softmax(sorted_top_p_scores, dim=-1), 1\n )].unsqueeze(0)\n \n def _log_model_tokens(self, model_name, scores, token_indices):\n \"\"\"Helper method to log token information for debugging\"\"\"\n logging.info(\"\\n-----------------------------------------------\")\n logging.info(f\"Generation Step 1\")\n logging.info(model_name)\n logging.info(\"|No. | Token ID | Token | Log Prob | Prob |\")\n logging.info(\"|----|----------|---------|----------|---------|\")\n for idx, (score, token_id) in enumerate(zip(scores, token_indices)):\n token = self.tokenizer.decode(token_id.item())\n prob = torch.exp(score)\n logging.info(f\"{idx+1:4d} | {token_id:8d} | {token:7s} | {score:.3f} | {prob:.2%} |\")\n \n def _log_final_probabilities(self, step, probs, token_ids):\n \"\"\"Helper method to log final token probabilities\"\"\"\n logging.info(\"\\n-----------------------------------------------\")\n logging.info(f\"Generation Step {step}\")\n logging.info(\"|No. | Token ID | Token | Log Prob | Prob |\")\n logging.info(\"|----|----------|---------|----------|---------|\")\n for idx, (prob, token_id) in enumerate(zip(probs, token_ids)):\n token = self.tokenizer.decode(token_id.item())\n score = torch.log(prob)\n logging.info(f\"{idx+1:4d} | {token_id:8d} | {token:7s} | {score:.3f} | {prob:.2%} |\")\n \n def generate_baseline(self, inputs, adapter_name = [\"base\"], gen_config=None):\n if gen_config is None:\n gen_config = self.model.generation_config\n \n if self.verbose:\n logging.info(f\"Generation config: {gen_config}\")\n\n inputs = {k:v.cuda(self.model.device) for k,v in inputs.items()}\n\n output_base = self.model.generate(**inputs,\n adapter_names=adapter_name,\n generation_config=gen_config,\n pad_token_id=self.tokenizer.pad_token_id,\n return_dict_in_generate=True,\n output_scores=True,)\n \n generated_sequence = output_base.sequences[0][inputs[\"input_ids\"].shape[1]:]\n logging.info(f\"Generated sequence: {self.tokenizer.decode(generated_sequence)}\")\n \n return self.tokenizer.decode(generated_sequence), len(generated_sequence)" } ] }, { "paper_id": 31, "paper_details": { "title": "MaskLID: Code-Switching Language Identification through Iterative Masking", "url": "https://arxiv.org/abs/2406.06263" }, "repo_original_url": "https://github.com/cisnlp/MaskLID", "project_path": "Benchmark/31-MaskLID/MaskLID-main", "enviorment_name": "MaskLID", "file_organization": "\nMaskLID-main/\n README.md\n LICENSE\n main.py\n masklid.py\n model_v3.bin\n", "latex_code_path": "Benchmark/31-MaskLID/arXiv-2406.06263v1", "task_details": [ { "task_id": 0, "indent": 2, "script": "\npython main.py\n", "completion_path": "./masklid.py", "latex_code": "\n\\subsection{\\fasttext-based LIDs}\n\nIn this paper, we explore the use of \\genericname for LIDs based on the \\fasttext~\\citep{bojanowski-etal-2017-enriching} architecture. However, it is also possible to apply \\genericname to other LIDs, as long as they enable to determine how much each feature (\\eg word) contributes to each supported language. \\fasttext is one of the most popular LID architectures due to its open-source nature, high performance, ease of use, and efficiency. \\fasttext classifier is a multinomial logistic classifier that represents the input sentence as a set of feature embeddings, making it easy to assess each feature's contribution to the final prediction.\n\nGiven a sentence $s$, let $f_1, f_2, \\ldots, f_T$ represent\nthe features extracted from $s$. Note that these features are linearly ordered,\ni.e., $f_i$ precedes $f_{i+1}$ in $s$. \n\\fasttext maps these features onto vectors in $\\mathbb{R}^d$ via feature embeddings $\\mathbf{x}_1, \\mathbf{x}_2, \\ldots, \\mathbf{x}_T$. The dimensionality of these embeddings, denoted $d$, is a hyperparameter. A base LID using \\fasttext{} architecture computes the posterior probability for a language $c \\in [1:N]$ by applying the softmax function over logits as:\n\n\\begin{equation}\\eqlabel{predict}\nP(c|s) = \\frac{\\exp( \\mathbf{b}_{c} \\cdot \\frac{1}{T} \\sum_{t=1}^{T} \\mathbf{x}_t)}{\\sum_{c'=1}^{N} \\exp(\\mathbf{b}_{c'} \\cdot \\frac{1}{T} \\sum_{t=1}^{T} \\mathbf{x}_t)}.\n\\end{equation}\n\n\\(P(c|s)\\) is the base LID probability of the input text $s$ belonging to language \\(c\\), \n\\(\\mathbf{b}_c\\) is the weight vector for language \\(c\\), and \\(N\\) is the total number of classes supported by the base LID.\n\nTo evaluate how much each feature contributes to each supported language, we need to compute logits separately for each feature. For simplicity and alignment with the \\fasttext tokenizer (which considers white-spaces as token boundaries), we set the level of granularity of features to be the word level. The word-level feature embedding is obtained as the summation of all feature embeddings that build each word. Noting $W$ the number of words in a sentence $s$, we define the $N\\times W$ matrix \\(\\mathbf{V}(s)\\), where each element \\(\\mathbf{V}_{c,t}(s)\\) represents the logits for language \\(c\\) and word-level feature \\(\\mathbf{x}_t\\):\n\n\\begin{equation}\\eqlabel{matrix_v}\n\\mathbf{V}_{c,t}(s) = \\mathbf{b}_{c} \\cdot \\mathbf{x}_t.\n\\end{equation}\n", "namespace": "masklid.MaskLID.fasttext_lid", "type": "method", "signature_position": [ 62, 62 ], "body_position": [ 63, 70 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Computes the sentence vector, which represents the average of all feature \n# embeddings as described in the paper's equation (1). This corresponds to \n# 1/T * sum(x_t) in the LaTeX formulation.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nsentence_vector = self.model.get_sentence_vector(text)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Computes logits by taking the dot product of language weight vectors \n# (b_c in the LaTeX) with the sentence vector. This implements the numerator \n# exponent term in equation (1): b_c \u00b7 (1/T * sum(x_t)).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nresult_vector = np.dot(self.output_matrix, sentence_vector)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Applies the softmax function to convert logits to probabilities.\n# This implements P(c|s) in equation (1), using only the specified language \n# indices from the full set of languages the model supports.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nsoftmax_result = self._softmax(result_vector)[self.language_indices]\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Identifies the top-k language predictions along with their \n# probabilities. This extends the LaTeX formula by retrieving not just the\n# highest probability language but the top k languages.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\ntop_k_indices = np.argsort(softmax_result)[-k:][::-1]\ntop_k_labels = [self.labels[i] for i in top_k_indices]\ntop_k_probs = softmax_result[top_k_indices]\ntop_k_labels = tuple(top_k_labels)\n\nreturn top_k_labels, top_k_probs\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The LaTeX describes the model as computing P(c|s) using the average of all feature embeddings, while the code directly uses fastText's get_sentence_vector method which already implements this averaging.\n - The implementation includes a k parameter for top-k prediction retrieval not explicitly mentioned in the LaTeX.\n - The LaTeX description does not specify how to obtain the sentence-level representation. The reference implementation relies on a pretrained model function that returns a sentence vector.\n - The LaTeX does not mention the filtering of language classes during softmax computation. The reference code restricts probabilities to a predefined subset of languages.\n\n - Mismatched Details:\n - None\n", "Missing_details": [ "\n- The LaTeX describes the model as computing P(c|s) using the average of all feature embeddings, while the code directly uses fastText's get_sentence_vector method which already implements this averaging.\n", "\n- The implementation includes a k parameter for top-k prediction retrieval not explicitly mentioned in the LaTeX.\n", "\n- The LaTeX description does not specify how to obtain the sentence-level representation. The reference implementation relies on a pretrained model function that returns a sentence vector.\n", "\n- The LaTeX does not mention the filtering of language classes during softmax computation. The reference code restricts probabilities to a predefined subset of languages.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - text (str): The input sentence s to be classified.\n - k (int): Number of top predictions to retrieve. Defaults to 1.\n", "Arguments_list": [ { "name": "text", "string": "\n- text (str): The input sentence s to be classified.\n", "dependency": null }, { "name": "k", "string": "\n- k (int): Number of top predictions to retrieve. Defaults to 1.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra File Dependencies:\n - MaskLID.model.get_sentence_vector\n - MaskLID._softmax\n - MaskLID.language_indices\n - MaskLID.labels\n - MaskLID.output_matrix\n\n - Cross File Dependencies: \n - None\n", "intra_file": [ "MaskLID.model.get_sentence_vector", "MaskLID._softmax", "MaskLID.language_indices", "MaskLID.labels", "MaskLID.output_matrix" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - numpy.dot\n - numpy.argsort\n", "list": [ "numpy.dot", "numpy.argsort" ] }, "Return": { "Return_String": "\nOutput Variables:\n - top_k_labels (Tuple): It is a tuple of strings containing the predicted language codes, sorted in descending order of their prediction probabilities.\n - top_k_probs (np.array): Corresponding probabilities for each predicted language.\n\n", "Return_list": [ { "name": "top_k_labels", "string": "\n- top_k_labels (Tuple): It is a tuple of strings containing the predicted language codes, sorted in descending order of their prediction probabilities.\n", "dependency": null }, { "name": "top_k_probs", "string": "\n- top_k_probs (np.array): Corresponding probabilities for each predicted language.\n", "dependency": null } ] }, "ori_python_file": "import fasttext\nimport numpy as np\nimport re\nimport string\nfrom copy import deepcopy\n\nclass MaskLID:\n \"\"\"A class for code-switching language identification using iterative masking.\"\"\"\n \n def __init__(self, model_path, languages=-1):\n \"\"\"Initialize the MaskLID class.\n \n Args:\n model_path (str): The path to the fastText model.\n languages (int or list, optional): The indices or list of language labels to consider. Defaults to -1.\n \"\"\"\n self.model = fasttext.load_model(model_path)\n self.output_matrix = self.model.get_output_matrix()\n self.labels = self.model.get_labels()\n self.language_indices = self._compute_language_indices(languages)\n self.labels = [self.labels[i] for i in self.language_indices]\n\n def _compute_language_indices(self, languages):\n \"\"\"Compute indices of selected languages.\n \n Args:\n languages (int or list): The indices or list of language labels.\n \n Returns:\n list: Indices of selected languages.\n \"\"\"\n if languages != -1 and isinstance(languages, list):\n return [self.labels.index(l) for l in set(languages) if l in self.labels]\n return list(range(len(self.labels)))\n\n def _softmax(self, x):\n \"\"\"Compute softmax values for each score in array x.\n \n Args:\n x (numpy.ndarray): Input array.\n \n Returns:\n numpy.ndarray: Softmax output.\n \"\"\"\n exp_x = np.exp(x - np.max(x))\n return exp_x / np.sum(exp_x)\n\n def _normalize_text(self, text):\n \"\"\"Normalize input text.\n \n Args:\n text (str): Input text.\n \n Returns:\n str: Normalized text.\n \"\"\"\n replace_by = \" \"\n replacement_map = {ord(c): replace_by for c in '\\n_:' + '\u2022#{|}' + string.digits}\n text = text.translate(replacement_map)\n return re.sub(r'\\s+', ' ', text).strip()\n \n def fasttext_lid(self, text, k=1):\n sentence_vector = self.model.get_sentence_vector(text)\n result_vector = np.dot(self.output_matrix, sentence_vector)\n softmax_result = self._softmax(result_vector)[self.language_indices]\n top_k_indices = np.argsort(softmax_result)[-k:][::-1]\n top_k_labels = [self.labels[i] for i in top_k_indices]\n top_k_probs = softmax_result[top_k_indices]\n \n return tuple(top_k_labels), top_k_probs\n\n def compute_v(self, sentence_vector):\n \"\"\"Compute the language vectors for a given sentence vector.\n \n Args:\n sentence_vector (numpy.ndarray): Sentence vector.\n \n Returns:\n list: Sorted list of labels and their associated vectors.\n \"\"\"\n result_vector = np.dot(self.output_matrix[self.language_indices, :], sentence_vector)\n return sorted(zip(self.labels, result_vector), key=lambda x: x[1], reverse=True)\n\n def compute_v_per_word(self, text):\n \"\"\"Compute language vectors for each word in the input text.\n \n Args:\n text (str): Input text.\n \n Returns:\n dict: Dictionary containing language vectors for each word.\n \"\"\"\n text = self._normalize_text(text)\n words = self.model.get_line(text)[0]\n words = [w for w in words if w not in ['', '']]\n subword_ids = [self.model.get_subwords(sw)[1] for sw in words]\n sentence_vector = [np.sum([self.model.get_input_vector(id) for id in sid], axis=0) for sid in subword_ids]\n\n dict_text = {}\n for i, word in enumerate(words):\n key = f\"{i}_{word}\"\n dict_text[key] = {'logits': self.compute_v(sentence_vector[i])}\n\n return dict_text\n\n def mask_label_top_k(self, dict_text, label, top_keep, top_remove):\n \"\"\"Mask top predictions for a given label.\n \n Args:\n dict_text (dict): Dictionary containing language vectors for each word.\n label (str): Label to mask.\n top_keep (int): Number of top predictions to keep.\n top_remove (int): Number of top predictions to remove.\n \n Returns:\n tuple: Dictionaries of remaining and deleted words after masking.\n \"\"\"\n dict_remained = deepcopy(dict_text)\n dict_deleted = {}\n\n for key, value in dict_text.items():\n logits = value['logits']\n labels = [t[0] for t in logits]\n\n if label in labels[:top_keep]:\n dict_deleted[key] = dict_remained[key]\n\n if label in labels[:top_remove]:\n dict_remained.pop(key, None)\n\n return dict_remained, dict_deleted\n\n @staticmethod\n def get_sizeof(text):\n \"\"\"Compute the size of text in bytes.\n \n Args:\n text (str): Input text.\n \n Returns:\n int: Size of text in bytes.\n \"\"\"\n return len(text.encode('utf-8'))\n\n @staticmethod\n def custom_sort(word):\n \"\"\"Custom sorting function for words.\n \n Args:\n word (str): Input word.\n \n Returns:\n int or float: Sorted value.\n \"\"\"\n match = re.match(r'^(\\d+)_', word)\n if match:\n return int(match.group(1))\n else:\n return float('inf') # Return infinity for words without numbers at the beginning\n\n def sum_logits(self, dict_data, label):\n \"\"\"Compute the sum of logits for a specific label across all words.\n \n Args:\n dict_data (dict): Dictionary containing language vectors for each word.\n label (str): Label to sum logits for.\n \n Returns:\n float: Total sum of logits for the given label.\n \"\"\"\n total = 0\n for value in dict_data.values():\n logits = value['logits']\n labels = [t[0] for t in logits]\n if label in labels:\n total += logits[labels.index(label)][1]\n return total\n\n def masklid_algorithm(self, text, alpha, beta, min_length, max_lambda=1, min_prob=0.5, max_retry=3, alpha_step_increase=5, beta_step_increase=5):\n info = {}\n iteration = 0\n retry_count = 0\n\n # Step 0: Compute V(s) for the input text\n word_language_matrix = self.compute_v_per_word(text)\n remaining_text = text\n\n # Main algorithm loop\n while iteration < max_lambda and retry_count < max_retry:\n # Step 1: Find most likely language\n pred_labels, pred_probs = self.fasttext_lid(remaining_text, k=1)\n current_language = pred_labels[0]\n \n # Save current state in case we need to backtrack\n previous_text = remaining_text\n previous_matrix = deepcopy(word_language_matrix)\n \n # Step 2: Mask words with strong association to current language\n word_language_matrix, masked_words = self.mask_label_top_k(\n word_language_matrix, current_language, beta, alpha)\n\n # Extract text from remaining and masked words\n masked_text = ' '.join(x.split('_', 1)[1] for x in masked_words.keys())\n remaining_text = ' '.join(x.split('_', 1)[1] for x in word_language_matrix.keys())\n \n # Step 3: Check if remaining text is above threshold\n if self.get_sizeof(masked_text) > min_length or iteration == 0:\n # Verify if masked text still belongs to identified language\n temp_labels, temp_probs = self.fasttext_lid(masked_text)\n \n if (temp_probs[0] > min_prob and temp_labels[0] == current_language) or iteration == 0:\n # Store information about this language segment\n info[iteration] = {\n 'label': current_language,\n 'text': masked_text,\n 'text_keys': masked_words.keys(),\n 'size': self.get_sizeof(masked_text),\n 'sum_logit': self.sum_logits(masked_words, current_language)\n }\n iteration += 1\n else:\n # Masking didn't work well, retry with adjusted parameters\n word_language_matrix = previous_matrix\n remaining_text = previous_text\n beta += beta_step_increase\n alpha += alpha_step_increase\n retry_count += 1\n else:\n # Text too short after masking, retry with adjusted parameters\n word_language_matrix = previous_matrix\n remaining_text = previous_text\n beta += beta_step_increase\n alpha += alpha_step_increase\n retry_count += 1\n \n # Check termination condition based on remaining text size\n if self.get_sizeof(remaining_text) < min_length:\n break\n\n # Post-process results by language\n result = {}\n for value in info.values():\n language = value['label']\n if language in result:\n result[language].extend(value['text_keys'])\n else:\n result[language] = list(value['text_keys'])\n\n # Format output by joining words for each language\n for language in result:\n result[language] = ' '.join([\n x.split('_', 1)[1] for x in sorted(set(result[language]), key=self.custom_sort)\n ])\n \n return result\n " }, { "task_id": 1, "indent": 2, "script": "\npython main.py\n", "latex_code": "\n\\subsection{The \\genericname Method \\seclabel{model}}\n\nWe define the \\genericname algorithm in alignment with \\citet{burchell-etal-2024-code}: given an input text, the objective is to return a set of codes corresponding to the language(s) it contains. However, \\genericname is more explainable and provides insights into which parts of the sentence contributed to its decision. The \\genericname algorithm works as follows:\n\n\\textbf{Input:}\n\\begin{itemize}[topsep=0pt,partopsep=0pt,parsep=0pt,itemsep=0pt]\n\\item[1)] sentence $s$. \n\\item[2)] $\\alpha$, an integer parameter used to define \\emph{strong associations} between words and languages: having a language appear in the top-$\\alpha$ logit values for a word is a strong cue that this word belongs to that language. \n\\item[3)] $\\beta$, an integer parameter used to define \\emph{weak associations} between words and languages: languages appearing in the top-$\\beta$ logit values for a word are weakly associated with that word. $\\beta$ is always greater than $\\alpha$.\n\\item[4)] $\\tau$, a threshold representing the minimum size of a sentence (in bytes) for which the LID makes reliable decisions. \n\\item[5)] $\\lambda$, a parameter defining the number of times the algorithm should be repeated.\n\\end{itemize}\n\\newpage\n\\textbf{Output:}\n\\begin{itemize}[topsep=0pt,partopsep=0pt,parsep=0pt,itemsep=0pt]\n\\item[1)] List of predicted languages, along with their associated word-level features.\n\\end{itemize}\n\\textbf{Procedure:}\n\\begin{itemize}[topsep=0pt,partopsep=0pt,parsep=0pt,itemsep=0pt]\n\\item[0)] Take sentence $s$ and compute $\\mathbf{V}(s)$ using \\eqref{matrix_v}. Assign $s$ to variable $u$.\n\\item[1)] Compute the posterior probability for each possible language using~\\eqref{predict}. Find the most likely class (\\(L1 = \\arg\\max_c P(c|u)\\)) along with its corresponding probability \\(P(L1|u)\\). Assign L1 to variable $\\text{L}_u$.\n\\item[2)] Process column \\(\\mathbf{V}_{:,t}(s)\\) for each unmasked word \\(t\\) in $u$. If the value of \\(\\mathbf{V}_{\\text{L}_u,t}(s)\\) is in the top-\\(\\beta\\) values for that column, then assign word \\(t\\) to language $\\text{L}_u$. If the value of \\(\\mathbf{V}_{\\text{L}_u,t}\\) is among the top-\\(\\alpha\\) values for that column, mask word $t$ from sentence $u$.\n\nMasked words play here a role similar to the anchors used in \\citep{mendels-etal-2018-collecting}: recall that for these authors, anchor words are selected to uniquely identify one language -- there removal is likely to decrease the recognition of L1, without impacting the ability to recognize L2. In our approach, we identify these \\emph{pseudo-anchors} on the spot, relying on the LID internal scoring procedure.\n\n\\item[3)] check if length of $u$ (in bytes, ignoring masked words) is greater than $\\tau$. If not, then terminate. This is one termination condition (for additional considerations, refer to~\\Appref{consideration}). Setting $\\tau =0$ will just check that the masked sentence is not empty, but it is better to use a non-zero threshold, as most sentence-level LIDs do not reliably predict short sentences \\cite{jauhiainen2019automatic}. \n\\item[4)] if the number of iterations is lower than $\\lambda$ then go to back to step~1, else stop.\n\\end{itemize}\n\nThe complexity of this greedy procedure is $O(\\lambda\\times{} T\\times{} N\\log\\beta)$.\n", "completion_path": "./masklid.py", "namespace": "masklid.MaskLID.masklid_algorithm", "type": "method", "signature_position": [ 179, 179 ], "body_position": [ 180, 255 ], "ReferenceCode_With_Comments": "\ninfo = {}\niteration = 0\nretry_count = 0\n\n# ---------------------------------------------------------------------------\n# Snippet 1: Compute the V(s) matrix for the input text and initialize u to s. \n# This implements step 0 from the LaTeX procedure: \"Take sentence s and compute \n# V(s) using equation (2). Assign s to variable u.\"\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nword_language_matrix = self.compute_v_per_word(text)\nremaining_text = text\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Main algorithm loop that continues until reaching maximum iterations\n# (\u03bb) or maximum retries. This implements step 4 from the LaTeX: \"if the number\n# of iterations is lower than \u03bb then go back to step 1, else stop.\"\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nwhile iteration < max_lambda and retry_count < max_retry:\n# [End Snippet 2]\n\n # ---------------------------------------------------------------------------\n # Snippet 3: Find the most likely language for the current text. This implements\n # step 1 from the LaTeX: \"Compute the posterior probability for each possible\n # language using equation (1). Find the most likely class L1 = argmax_c P(c|u)\n # along with its corresponding probability P(L1|u). Assign L1 to variable L_u.\"\n # ---------------------------------------------------------------------------\n # [Begin Snippet 3]\n pred_labels, pred_probs = self.fasttext_lid(remaining_text, k=1)\n current_language = pred_labels[0]\n previous_text = remaining_text\n previous_matrix = deepcopy(word_language_matrix)\n # [End Snippet 3]\n \n # ---------------------------------------------------------------------------\n # Snippet 4: Process each word and mask those with strong association to the\n # detected language. This implements step 2 from the LaTeX: \"Process column \n # V_{:,t}(s) for each unmasked word t in u. If the value of V_{L_u,t}(s) is \n # in the top-\u03b2 values for that column, then assign word t to language L_u. \n # If the value of V_{L_u,t} is among the top-\u03b1 values for that column, mask \n # word t from sentence u.\"\n # ---------------------------------------------------------------------------\n # [Begin Snippet 4]\n word_language_matrix, masked_words = self.mask_label_top_k(\n word_language_matrix, current_language, beta, alpha)\n masked_text = ' '.join(x.split('_', 1)[1] for x in masked_words.keys())\n remaining_text = ' '.join(x.split('_', 1)[1] for x in word_language_matrix.keys())\n # [End Snippet 4]\n \n # ---------------------------------------------------------------------------\n # Snippet 5: Check if the remaining text is above the threshold \u03c4 and verify\n # language identification. This implements step 3 from the LaTeX: \"check if \n # length of u (in bytes, ignoring masked words) is greater than \u03c4. If not, \n # then terminate.\"\n # ---------------------------------------------------------------------------\n # [Begin Snippet 5]\n if self.get_sizeof(masked_text) > min_length or iteration == 0:\n temp_labels, temp_probs = self.fasttext_lid(masked_text)\n \n if (temp_probs[0] > min_prob and temp_labels[0] == current_language) or iteration == 0:\n info[iteration] = {\n 'label': current_language,\n 'text': masked_text,\n 'text_keys': masked_words.keys(),\n 'size': self.get_sizeof(masked_text),\n 'sum_logit': self.sum_logits(masked_words, current_language)\n }\n iteration += 1\n else:\n word_language_matrix = previous_matrix\n remaining_text = previous_text\n beta += beta_step_increase\n alpha += alpha_step_increase\n retry_count += 1\n else:\n word_language_matrix = previous_matrix\n remaining_text = previous_text\n beta += beta_step_increase\n alpha += alpha_step_increase\n retry_count += 1\n if self.get_sizeof(remaining_text) < min_length:\n break\n # [End Snippet 5]\n\n# ---------------------------------------------------------------------------\n# Snippet 6: Post-process results by organizing words by language. This corresponds\n# to formatting the output as described in the LaTeX: \"List of predicted languages,\n# along with their associated word-level features.\"\n# ---------------------------------------------------------------------------\n# [Begin Snippet 6]\nresult = {}\nfor value in info.values():\n language = value['label']\n if language in result:\n result[language].extend(value['text_keys'])\n else:\n result[language] = list(value['text_keys'])\nfor language in result:\n result[language] = ' '.join([\n x.split('_', 1)[1] for x in sorted(set(result[language]), key=self.custom_sort)\n ])\n \nreturn result\n# [End Snippet 6]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The code includes a confidence check with min_prob parameter to verify language identification.\n - The LaTeX does not describe a dynamic adjustment mechanism for the parameters (\u03b1 and \u03b2) in the event that no words are masked. In contrast, the reference code includes a retry loop where these parameters are incrementally increased to eventually achieve the desired masking effect.\n - There is no mention in the LaTeX of maintaining and reverting to a previous state (i.e., saving the previous text and matrix) when a masking attempt fails. The reference code implements a rollback mechanism to restore the previous state if the language prediction or masked text size check does not meet the required criteria.\n - The LaTeX states termination occurs when the masked text length \u2264 \u03c4 (Step 3), but the reference code uses **two termination triggers**: (1) masked text length \u2264 \u03c4 *or* (2) predicted confidence of masked text < `min_prob`.\n - The workflow for post-processing the results is not detailed in the LaTeX. The reference code organizes the masked words by language and sorts them to create a coherent output.\n\n - Mismatched Details:\n - In LaTeX, \u03b2 > \u03b1 is stated, but the code doesn't enforce this constraint.\n", "Missing_details": [ "\n- The code includes a confidence check with min_prob parameter to verify language identification.\n", "\n- The LaTeX does not describe a dynamic adjustment mechanism for the parameters (\u03b1 and \u03b2) in the event that no words are masked. In contrast, the reference code includes a retry loop where these parameters are incrementally increased to eventually achieve the desired masking effect.\n", "\n- There is no mention in the LaTeX of maintaining and reverting to a previous state (i.e., saving the previous text and matrix) when a masking attempt fails. The reference code implements a rollback mechanism to restore the previous state if the language prediction or masked text size check does not meet the required criteria.\n", "\n- The LaTeX states termination occurs when the masked text length \u2264 \u03c4 (Step 3), but the reference code uses **two termination triggers**: (1) masked text length \u2264 \u03c4 *or* (2) predicted confidence of masked text < `min_prob`.\n", "\n- The workflow for post-processing the results is not detailed in the LaTeX. The reference code organizes the masked words by language and sorts them to create a coherent output.\n" ], "Mismatched_details": [ "\n- In LaTeX, \u03b2 > \u03b1 is stated, but the code doesn't enforce this constraint.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - text (str): Input sentence s for language identification.\n - alpha (int): Parameter \u03b1 for strong associations - words with language in top-\u03b1 logits are masked.\n - beta (int): Parameter \u03b2 for weak associations - words with language in top-\u03b2 logits are assigned to that language.\n - min_length (int): Threshold \u03c4 representing minimum size (in bytes) for reliable language detection.\n - max_lambda (int, optional): Parameter \u03bb defining maximum iterations of the algorithm. Defaults to 1.\n - min_prob (float, optional): Confidence threshold for language prediction. Defaults to 0.5.\n - max_retry (int, optional): Maximum number of retry attempts if masking fails. Defaults to 3.\n - alpha_step_increase (int, optional): Step size for increasing \u03b1 when retrying. Defaults to 5.\n - beta_step_increase (int, optional): Step size for increasing \u03b2 when retrying. Defaults to 5.\n", "Arguments_list": [ { "name": "text", "string": "\n- text (str): Input sentence s for language identification.\n", "dependency": null }, { "name": "alpha", "string": "\n- alpha (int): Parameter \u03b1 for strong associations - words with language in top-\u03b1 logits are masked.\n", "dependency": null }, { "name": "beta", "string": "\n- beta (int): Parameter \u03b2 for weak associations - words with language in top-\u03b2 logits are assigned to that language.\n", "dependency": null }, { "name": "min_length", "string": "\n- min_length (int): Threshold \u03c4 representing minimum size (in bytes) for reliable language detection.\n", "dependency": null }, { "name": "max_lambda", "string": "\n- max_lambda (int, optional): Parameter \u03bb defining maximum iterations of the algorithm. Defaults to 1.\n", "dependency": null }, { "name": "min_prob", "string": "\n- min_prob (float, optional): Confidence threshold for language prediction. Defaults to 0.5.\n", "dependency": null }, { "name": "max_retry", "string": "\n- max_retry (int, optional): Maximum number of retry attempts if masking fails. Defaults to 3.\n", "dependency": null }, { "name": "alpha_step_increase", "string": "\n- alpha_step_increase (int, optional): Step size for increasing \u03b1 when retrying. Defaults to 5.\n", "dependency": null }, { "name": "beta_step_increase", "string": " \n- beta_step_increase (int, optional): Step size for increasing \u03b2 when retrying. Defaults to 5.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra File Dependencies:\n - MaskLID.compute_v_per_word\n - MaskLID.fasttext_lid\n - MaskLID.mask_label_top_k\n - MaskLID.get_sizeof\n - MaskLID.sum_logits\n - MaskLID.custom_sort\n\n - Cross File Dependencies: \n - None\n", "intra_file": [ "MaskLID.compute_v_per_word", "MaskLID.fasttext_lid", "MaskLID.mask_label_top_k", "MaskLID.get_sizeof", "MaskLID.sum_logits", "MaskLID.custom_sort" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - copy.deepcopy\n", "list": [ "copy.deepcopy" ] }, "Return": { "Return_String": "\nOutput Variables:\n - result: The output variable result is a dictionary where keys are language identification codes and values are the associated text segments in those languages. \n", "Return_list": [ { "name": "result", "string": "\n- result: The output variable result is a dictionary where keys are language identification codes and values are the associated text segments in those languages. \n", "dependency": null } ] }, "ori_python_file": "import fasttext\nimport numpy as np\nimport re\nimport string\nfrom copy import deepcopy\n\nclass MaskLID:\n \"\"\"A class for code-switching language identification using iterative masking.\"\"\"\n \n def __init__(self, model_path, languages=-1):\n \"\"\"Initialize the MaskLID class.\n \n Args:\n model_path (str): The path to the fastText model.\n languages (int or list, optional): The indices or list of language labels to consider. Defaults to -1.\n \"\"\"\n self.model = fasttext.load_model(model_path)\n self.output_matrix = self.model.get_output_matrix()\n self.labels = self.model.get_labels()\n self.language_indices = self._compute_language_indices(languages)\n self.labels = [self.labels[i] for i in self.language_indices]\n\n def _compute_language_indices(self, languages):\n \"\"\"Compute indices of selected languages.\n \n Args:\n languages (int or list): The indices or list of language labels.\n \n Returns:\n list: Indices of selected languages.\n \"\"\"\n if languages != -1 and isinstance(languages, list):\n return [self.labels.index(l) for l in set(languages) if l in self.labels]\n return list(range(len(self.labels)))\n\n def _softmax(self, x):\n \"\"\"Compute softmax values for each score in array x.\n \n Args:\n x (numpy.ndarray): Input array.\n \n Returns:\n numpy.ndarray: Softmax output.\n \"\"\"\n exp_x = np.exp(x - np.max(x))\n return exp_x / np.sum(exp_x)\n\n def _normalize_text(self, text):\n \"\"\"Normalize input text.\n \n Args:\n text (str): Input text.\n \n Returns:\n str: Normalized text.\n \"\"\"\n replace_by = \" \"\n replacement_map = {ord(c): replace_by for c in '\\n_:' + '\u2022#{|}' + string.digits}\n text = text.translate(replacement_map)\n return re.sub(r'\\s+', ' ', text).strip()\n \n def fasttext_lid(self, text, k=1):\n sentence_vector = self.model.get_sentence_vector(text)\n result_vector = np.dot(self.output_matrix, sentence_vector)\n softmax_result = self._softmax(result_vector)[self.language_indices]\n top_k_indices = np.argsort(softmax_result)[-k:][::-1]\n top_k_labels = [self.labels[i] for i in top_k_indices]\n top_k_probs = softmax_result[top_k_indices]\n \n return tuple(top_k_labels), top_k_probs\n\n def compute_v(self, sentence_vector):\n \"\"\"Compute the language vectors for a given sentence vector.\n \n Args:\n sentence_vector (numpy.ndarray): Sentence vector.\n \n Returns:\n list: Sorted list of labels and their associated vectors.\n \"\"\"\n result_vector = np.dot(self.output_matrix[self.language_indices, :], sentence_vector)\n return sorted(zip(self.labels, result_vector), key=lambda x: x[1], reverse=True)\n\n def compute_v_per_word(self, text):\n \"\"\"Compute language vectors for each word in the input text.\n \n Args:\n text (str): Input text.\n \n Returns:\n dict: Dictionary containing language vectors for each word.\n \"\"\"\n text = self._normalize_text(text)\n words = self.model.get_line(text)[0]\n words = [w for w in words if w not in ['', '']]\n subword_ids = [self.model.get_subwords(sw)[1] for sw in words]\n sentence_vector = [np.sum([self.model.get_input_vector(id) for id in sid], axis=0) for sid in subword_ids]\n\n dict_text = {}\n for i, word in enumerate(words):\n key = f\"{i}_{word}\"\n dict_text[key] = {'logits': self.compute_v(sentence_vector[i])}\n\n return dict_text\n\n def mask_label_top_k(self, dict_text, label, top_keep, top_remove):\n \"\"\"Mask top predictions for a given label.\n \n Args:\n dict_text (dict): Dictionary containing language vectors for each word.\n label (str): Label to mask.\n top_keep (int): Number of top predictions to keep.\n top_remove (int): Number of top predictions to remove.\n \n Returns:\n tuple: Dictionaries of remaining and deleted words after masking.\n \"\"\"\n dict_remained = deepcopy(dict_text)\n dict_deleted = {}\n\n for key, value in dict_text.items():\n logits = value['logits']\n labels = [t[0] for t in logits]\n\n if label in labels[:top_keep]:\n dict_deleted[key] = dict_remained[key]\n\n if label in labels[:top_remove]:\n dict_remained.pop(key, None)\n\n return dict_remained, dict_deleted\n\n @staticmethod\n def get_sizeof(text):\n \"\"\"Compute the size of text in bytes.\n \n Args:\n text (str): Input text.\n \n Returns:\n int: Size of text in bytes.\n \"\"\"\n return len(text.encode('utf-8'))\n\n @staticmethod\n def custom_sort(word):\n \"\"\"Custom sorting function for words.\n \n Args:\n word (str): Input word.\n \n Returns:\n int or float: Sorted value.\n \"\"\"\n match = re.match(r'^(\\d+)_', word)\n if match:\n return int(match.group(1))\n else:\n return float('inf') # Return infinity for words without numbers at the beginning\n\n def sum_logits(self, dict_data, label):\n \"\"\"Compute the sum of logits for a specific label across all words.\n \n Args:\n dict_data (dict): Dictionary containing language vectors for each word.\n label (str): Label to sum logits for.\n \n Returns:\n float: Total sum of logits for the given label.\n \"\"\"\n total = 0\n for value in dict_data.values():\n logits = value['logits']\n labels = [t[0] for t in logits]\n if label in labels:\n total += logits[labels.index(label)][1]\n return total\n\n def masklid_algorithm(self, text, alpha, beta, min_length, max_lambda=1, min_prob=0.5, max_retry=3, alpha_step_increase=5, beta_step_increase=5):\n info = {}\n iteration = 0\n retry_count = 0\n\n # Step 0: Compute V(s) for the input text\n word_language_matrix = self.compute_v_per_word(text)\n remaining_text = text\n\n # Main algorithm loop\n while iteration < max_lambda and retry_count < max_retry:\n # Step 1: Find most likely language\n pred_labels, pred_probs = self.fasttext_lid(remaining_text, k=1)\n current_language = pred_labels[0]\n \n # Save current state in case we need to backtrack\n previous_text = remaining_text\n previous_matrix = deepcopy(word_language_matrix)\n \n # Step 2: Mask words with strong association to current language\n word_language_matrix, masked_words = self.mask_label_top_k(\n word_language_matrix, current_language, beta, alpha)\n\n # Extract text from remaining and masked words\n masked_text = ' '.join(x.split('_', 1)[1] for x in masked_words.keys())\n remaining_text = ' '.join(x.split('_', 1)[1] for x in word_language_matrix.keys())\n \n # Step 3: Check if remaining text is above threshold\n if self.get_sizeof(masked_text) > min_length or iteration == 0:\n # Verify if masked text still belongs to identified language\n temp_labels, temp_probs = self.fasttext_lid(masked_text)\n \n if (temp_probs[0] > min_prob and temp_labels[0] == current_language) or iteration == 0:\n # Store information about this language segment\n info[iteration] = {\n 'label': current_language,\n 'text': masked_text,\n 'text_keys': masked_words.keys(),\n 'size': self.get_sizeof(masked_text),\n 'sum_logit': self.sum_logits(masked_words, current_language)\n }\n iteration += 1\n else:\n # Masking didn't work well, retry with adjusted parameters\n word_language_matrix = previous_matrix\n remaining_text = previous_text\n beta += beta_step_increase\n alpha += alpha_step_increase\n retry_count += 1\n else:\n # Text too short after masking, retry with adjusted parameters\n word_language_matrix = previous_matrix\n remaining_text = previous_text\n beta += beta_step_increase\n alpha += alpha_step_increase\n retry_count += 1\n \n # Check termination condition based on remaining text size\n if self.get_sizeof(remaining_text) < min_length:\n break\n\n # Post-process results by language\n result = {}\n for value in info.values():\n language = value['label']\n if language in result:\n result[language].extend(value['text_keys'])\n else:\n result[language] = list(value['text_keys'])\n\n # Format output by joining words for each language\n for language in result:\n result[language] = ' '.join([\n x.split('_', 1)[1] for x in sorted(set(result[language]), key=self.custom_sort)\n ])\n \n return result\n " } ] }, { "paper_id": 32, "paper_details": { "title": "Towards Robust and Generalized Parameter-Efficient Fine-Tuning for Noisy Label Learning", "url": "https://arxiv.org/abs/2411.00873" }, "repo_original_url": "https://github.com/yeachan-kr/clear/tree/main", "project_path": "Benchmark/32-clear/clear-main", "enviorment_name": "clear", "file_organization": "\nclear-main/\n README.md\n env.sh\n train.sh\n main.py\n\n activations.py\n attentions.py\n blocks.py\n loss.py\n transformer_model.py\n transformer_utils.py\n utils.py\n save/\n\n solvers/\n routing_adapter_solver.py\n routing_bitfit_solver.py\n routing_lora_solver.py\n routing_prefix_solver.py\n", "latex_code_path": "Benchmark/32-clear/arXiv-2411.00873v1", "task_details": [ { "task_id": 0, "indent": 2, "script": "\npython main.py --dataset SetFit/sst5 --model bert-base-uncased --alg routing_adapter --device 0 --adapter routing_adapter --batch_size 32 --epochs 8\n", "completion_path": "./solvers/routing_adapter_solver.py", "latex_code": "\n\\paragraph{Estimating clean probability for routing} \nTo derive the clean probability for each sample, we leverage the distinct learning patterns when learning with clean and noisy samples: \\textit{deep networks prefer to learn clean samples first before fitting noisy ones} \\cite{clean_first}. Namely, noisy samples tend to have a higher loss than clean samples in the early training stage. \nThis enables to distinguish potentially clean samples from the datasets based on loss deviation \\cite{mentornet,co-teaching}. \nTaking advantage of such phenomena, we adopt the widely-used Gaussian Mixture Model (GMM) in noise label learning \\cite{devidemix, selfmix}, in which the probability of samples being clean is estimated by the per-sample loss. \n\nBased on the estimated mixture models, we compute the clean probability $p$ using the posterior probability, i.e., $p(g|\\ell)$ where $\\ell$ is the loss for the training sample, and $g$ is the Gaussian component with a smaller mean (i.e., smaller loss). Specifically, we first train our model for the $k$ epochs warm-up to measure the loss of samples, and then we estimate the clean probability for each training sample on every subsequent epoch. \nIt is noteworthy that we leverage training losses obtained from the previous epoch to estimate clean probabilities, thereby reducing the additional computational cost from redundant forward passes.\n", "namespace": "solvers.routing_adapter_solver.RoutingAdapterSolver.estimate_clean_probability", "type": "method", "signature_position": [ 81, 81 ], "body_position": [ 82, 154 ], "ReferenceCode_With_Comments": "\nsample_indexes = []\nsample_losses = []\nsample_correct_labels = []\nsample_preds = []\n\nmodel = model.eval()\nwith torch.no_grad():\n for batch in dataloader:\n indexes = batch['id'].to(self.device)\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n noisy_labels = batch['noise_label'].to(self.device)\n\n # ---------------------------------------------------------------------------\n # Snippet 1: Obtain model predictions. Stochastic routing, mentioned later, is implicitly applied *within* the model during the forward pass when adapter routing probabilities are set.\n # The loop and averaging implement the idea from the LaTeX of making 'multiple forwards to reduce predictive variance'.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 1]\n preds = []\n probs = []\n for _ in range(1):\n # Apply random routing masks\n for layeridx in range(model.config.num_hidden_layers):\n mask = (torch.rand(input_ids.size(0)).cuda() < self.args.r_prob).float()\n model.bert.encoder.layer[layeridx].attention.output.main_adapter.routing_probs.data = mask\n model.bert.encoder.layer[layeridx].output.main_adapter.routing_probs.data = mask\n\n outputs = model(input_ids, attention_mask=attention_mask)\n logits = outputs.logits\n preds.append(logits.unsqueeze(0))\n probs.append(torch.softmax(logits, dim=-1).unsqueeze(0))\n\n preds = torch.cat(preds, dim=0).mean(dim=0)\n probs = torch.cat(probs, dim=0).mean(dim=0)\n # [End Snippet 1]\n\n # ---------------------------------------------------------------------------\n # Snippet 2: Calculate the cross-entropy loss between the model's predictions and the *noisy* labels.\n # This corresponds to calculating 'l', the loss for the training sample, in the LaTeX.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 2]\n loss = (-F.one_hot(noisy_labels, self.num_class) * preds.log_softmax(dim=-1)).sum(dim=-1)\n # [End Snippet 2]\n \n # ---------------------------------------------------------------------------\n # Snippet 3: Apply momentum-based smoothing to the calculated losses, using losses from the previous epoch if available.\n # This implements the idea of 'leveraging training losses obtained from the previous epoch'.\n # ---------------------------------------------------------------------------\n # [Begin Snippet 3]\n if prev_losses is not None:\n loss = loss * (1 - loss_momentum) + prev_losses.cuda()[indexes].squeeze() * loss_momentum\n # [End Snippet 3]\n \n sample_indexes.append(indexes)\n sample_losses.append(loss)\n sample_correct_labels.append((labels == noisy_labels).float())\n sample_preds.append(preds)\n \n# ---------------------------------------------------------------------------\n# Snippet 4: Aggregate stored results and convert them into a unified form for\n# subsequent processing. This step represents the transition in the LaTeX snippet\n# where the per-sample losses are prepared for GMM fitting to obtain the clean\n# probability p(g|\u2113).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nsample_preds = torch.cat(sample_preds, dim=0)\nsample_indexes = torch.cat(sample_indexes, dim=0)\nsample_correct_labels = torch.cat(sample_correct_labels, dim=0).cpu()\nsample_losses = torch.cat(sample_losses, dim=0)\n\nsample_losses_np = sample_losses.unsqueeze(-1).detach().cpu().numpy()\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Fit a two-component Gaussian Mixture Model and derive the clean\n# probability for each sample. This corresponds to the LaTeX sub-section\u2019s\n# statement that the Gaussian component with smaller mean is deemed clean\n# (lower loss).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\ngm = GaussianMixture(n_components=2, random_state=0).fit(sample_losses_np)\nclean_component_idx = np.argmin(gm.means_) # Clean samples have smaller loss\nclean_probs = gm.predict_proba(sample_losses_np)[:, clean_component_idx]\ndecision = (clean_probs > min_prob).astype(np.float32)\n\ndecision_tensor = torch.from_numpy(decision).float()\nclean_probs_tensor = torch.tensor(clean_probs).float().to(self.device)\n# [End Snippet 5]\n\n# ---------------------------------------------------------------------------\n# Snippet 6: Map decisions and probabilities back to the original sample order\n# and return the final outputs. In the LaTeX snippet, the final p(g|\u2113) is used\n# to decide whether to route the sample through the PEFT modules.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 6]\ndecision_tensor[sample_indexes] = copy.deepcopy(decision_tensor)\nclean_probs_tensor[sample_indexes] = copy.deepcopy(clean_probs_tensor)\nsample_preds[sample_indexes] = copy.deepcopy(sample_preds)\n\nsample_losses_tensor = torch.tensor(sample_losses_np)\nsample_losses_tensor[sample_indexes] = copy.deepcopy(sample_losses_tensor)\n\nreturn decision_tensor, clean_probs_tensor, sample_preds, sample_losses_tensor\n# [End Snippet 6]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The LaTeX description states that training losses from the previous epoch are leveraged to estimate clean probabilities, suggesting a straightforward incorporation of past losses. However, the reference implementation applies a momentum-based smoothing technique where the current epoch\u2019s loss for each sample is blended with a weighted version of the previous epoch\u2019s loss, using a specific weighting factor (e.g., 0.9 for past losses and 0.1 for current losses).\n - Stochastic routing mask application during inference: The LaTeX does not mention that the model applies random binary masks to adapter layers during forward passes to induce predictive variance.\n - The LaTeX description omits the explicit step of mapping the computed probabilities, decisions, and losses back to their original positions in the dataset using sample identifiers.\n - The LaTeX description omits the explicit mention of averaging multiple forward pass outputs to reduce predictive variance. While the reference code iterates through several passes with different routing masks and averages the outcomes\n \n - Mismatched Details:\n - Loss calculation methodology: The LaTeX implies standard cross-entropy loss calculation (\"\u2113 is the loss for the training sample\"), but the reference code implements a custom variant using log-softmax + one-hot multiplication instead of standard cross_entropy.\n\n", "Missing_details": [ "\n- The LaTeX description states that training losses from the previous epoch are leveraged to estimate clean probabilities, suggesting a straightforward incorporation of past losses. However, the reference implementation applies a momentum-based smoothing technique where the current epoch\u2019s loss for each sample is blended with a weighted version of the previous epoch\u2019s loss, using a specific weighting factor (e.g., 0.9 for past losses and 0.1 for current losses).\n", "\n- Stochastic routing mask application during inference: The LaTeX does not mention that the model applies random binary masks to adapter layers during forward passes to induce predictive variance.\n", "\n- The LaTeX description omits the explicit step of mapping the computed probabilities, decisions, and losses back to their original positions in the dataset using sample identifiers.\n", "\n- The LaTeX description omits the explicit mention of averaging multiple forward pass outputs to reduce predictive variance. While the reference code iterates through several passes with different routing masks and averages the outcomes\n" ], "Mismatched_details": [ "\n- Loss calculation methodology: The LaTeX implies standard cross-entropy loss calculation (\"\u2113 is the loss for the training sample\"), but the reference code implements a custom variant using log-softmax + one-hot multiplication instead of standard cross_entropy.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - model (BertForSequenceClassification):\n The neural model with parameter-efficient fine-tuning modules, from which per-sample losses are computed.\n - dataloader (torch.utils.data.DataLoader):\n An iterable DataLoader providing batched input samples for loss-based estimations.\n Each batch contains:\n - 'id': Tensor containing unique identifiers for each sample in the batch used for mapping samples back to their original positions and for retrieving clean probabilities during the routing decision process\n - 'input_ids': Tensor of token IDs from the tokenized text input for the BERT model, representing the encoded text sequences\n - 'attention_mask': Tensor indicating which tokens should be attended to (1) vs padding (0) Used by the transformer attention mechanism to ignore padding tokens\n - 'label': Tensor containing ground truth labels for each sample used for computing accuracy metrics and identifying clean vs noisy samples\n - 'noise_label': Tensor containing potentially noisy labels. These are the labels used for training and may differ from the true 'label' when noise has been injected\n - prev_losses (torch.Tensor, optional, shape=[dataset_size]):\n It contains the previous epoch\u2019s losses for each sample index, used for momentum-based smoothing. Defaults to None if not used.\n - loss_momentum (float, optional):\n A smoothing factor applied to the current batch\u2019s losses, default is 0.9. \n - min_prob (float, optional):\n Threshold for deciding which samples are predicted clean after GMM fitting, default is 0.5.\n\n The function also uses the following class attributes:\n - self.num_class (int): The number of classes in the dataset.\n - self.args.r_prob (float): It is a hyperparameter that controls the probability of activating the adapter routing for each transformer layer during the forward pass. For each sample, a random value is compared against this probability; if the random value is below self.args.r_prob, the adapter in that layer is activated (i.e., the routing mask is set to 1), otherwise it is deactivated (mask set to 0).\n - self.device (torch.device): The device on which the model is loaded (e.g., 'cuda' for GPU).\n", "Arguments_list": [ { "name": "model", "string": "\n- model (BertForSequenceClassification):\n The neural model with parameter-efficient fine-tuning modules, from which per-sample losses are computed.\n", "dependency": "BertForSequenceClassification" }, { "name": "dataloader", "string": "\n- dataloader (torch.utils.data.DataLoader):\n An iterable DataLoader providing batched input samples for loss-based estimations.\n Each batch contains:\n - 'id': Tensor containing unique identifiers for each sample in the batch used for mapping samples back to their original positions and for retrieving clean probabilities during the routing decision process\n - 'input_ids': Tensor of token IDs from the tokenized text input for the BERT model, representing the encoded text sequences\n - 'attention_mask': Tensor indicating which tokens should be attended to (1) vs padding (0) Used by the transformer attention mechanism to ignore padding tokens\n - 'label': Tensor containing ground truth labels for each sample used for computing accuracy metrics and identifying clean vs noisy samples\n - 'noise_label': Tensor containing potentially noisy labels. These are the labels used for training and may differ from the true 'label' when noise has been injected\n", "dependency": null }, { "name": "prev_losses", "string": "\n- prev_losses (torch.Tensor, optional, shape=[dataset_size]):\n It contains the previous epoch\u2019s losses for each sample index, used for momentum-based smoothing. Defaults to None if not used.\n", "dependency": null }, { "name": "loss_momentum", "string": "\n- loss_momentum (float, optional):\n A smoothing factor applied to the current batch\u2019s losses, default is 0.9.\n", "dependency": null }, { "name": "min_prob", "string": "\n- min_prob (float, optional):\n Threshold for deciding which samples are predicted clean after GMM fitting, default is 0.5.\n", "dependency": null }, { "name": "self.classes", "string": "\n- self.classes (int): The number of classes in the dataset.\n", "dependency": null }, { "name": "self.args.r_prob", "string": "\n- self.args.r_prob (float): It is a hyperparameter that controls the probability of activating the adapter routing for each transformer layer during the forward pass. For each sample, a random value is compared against this probability; if the random value is below self.args.r_prob, the adapter in that layer is activated (i.e., the routing mask is set to 1), otherwise it is deactivated (mask set to 0).\n", "dependency": null }, { "name": "self.device", "string": "\n- self.device (torch.device): The device on which the model is loaded (e.g., 'cuda' for GPU).\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-file Dependencies:\n - None\n\n - Cross-file Dependencies:\n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - numpy.argmin\n - torch.rand\n - sklearn.mixture.GaussianMixture\n - copy.deepcopy\n - torch.cat\n - torch.functional.F.one_hot\n - torch.tensor\n - torch.no_grad\n - torch.softmax\n - torch.from_numpy\n", "list": [ "numpy.argmin", "torch.rand", "sklearn.mixture.GaussianMixture", "copy.deepcopy", "torch.cat", "torch.functional.F.one_hot", "torch.tensor", "torch.no_grad", "torch.softmax", "torch.from_numpy" ] }, "Return": { "Return_String": "\nOutput Variables:\n - decision_tensor (torch.Tensor, shape=[dataset_size]):\n A tensor where each entry is 1.0 if the sample is predicted to be clean (above min_prob) and 0.0 otherwise.\n - clean_probs_tensor (torch.Tensor, shape=[dataset_size]):\n A tensor of clean probabilities for each sample, used for routing decisions in subsequent training steps.\n - sample_preds (torch.Tensor, [dataset_size, num_classes]):\n Model predictions (logits) for each sample.\n - sample_losses_tensor (torch.Tensor, [dataset_size, 1]):\n The final per-sample losses (after any momentum-based smoothing) converted to a tensor.\n", "Return_list": [ { "name": "decision_tensor", "string": "\n- decision_tensor (torch.Tensor, shape=[dataset_size]):\n A tensor where each entry is 1.0 if the sample is predicted to be clean (above min_prob) and 0.0 otherwise.\n", "dependency": null }, { "name": "clean_probs_tensor", "string": "\n- clean_probs_tensor (torch.Tensor, shape=[dataset_size]):\n A tensor of clean probabilities for each sample, used for routing decisions in subsequent training steps.\n", "dependency": null }, { "name": "sample_preds", "string": "\n- sample_preds (torch.Tensor, [dataset_size, num_classes]):\n Model predictions (logits) for each sample.\n", "dependency": null }, { "name": "sample_losses_tensor", "string": "\n- sample_losses_tensor (torch.Tensor, [dataset_size, 1]):\n The final per-sample losses (after any momentum-based smoothing) converted to a tensor.\n", "dependency": null } ] }, "ori_python_file": "import os\nimport copy\nimport time\nimport pickle\nimport datetime\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.manifold import TSNE\n\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom utils import get_num_classes, initialize_networks, get_dataloader\nfrom sklearn.mixture import GaussianMixture\nfrom blocks import AdaMixAdapter\nfrom loss import GeneralizedCrossEntropy\nimport logging\nlogging.getLogger(\"imported_module\").setLevel(logging.WARNING)\n\nfrom torch.cuda.amp import GradScaler \nfrom loss import FocalLoss\n\nclass RoutingAdapterSolver(object):\n\n def __init__(self, args, dataset):\n \"\"\" Initialize configurations. \"\"\"\n self.args = args\n self.dataset = dataset\n self.num_class = get_num_classes(args.dataset)\n\n # Load training networks\n self.model = initialize_networks(dataset=args.dataset, model=args.model, adapter=args.adapter)\n self.pre_model = initialize_networks(dataset=args.dataset, model=args.model, adapter='none')\n \n # Optimizer\n self.criterion = nn.CrossEntropyLoss().cuda()\n self.device = torch.device('cuda')\n\n def testing_plm(self, global_loader, model=None):\n writer = {'loss': 0., 'acc': 0., 'step': 0}\n if model is None:\n model = self.model\n net = model.to(self.device)\n net.eval()\n\n writer['loss'] = 0.\n writer['acc'] = 0.\n writer['step'] = 0.\n\n predictions = []\n labels = []\n with torch.no_grad():\n for batch in global_loader:\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n\n # decision probability updates\n for layeridx in range(model.config.num_hidden_layers):\n mask = (torch.rand(input_ids.size(0)).cuda() < self.args.r_prob).float()\n model.bert.encoder.layer[layeridx].attention.output.main_adapter.routing_probs.data = mask\n model.bert.encoder.layer[layeridx].output.main_adapter.routing_probs.data = mask\n\n outputs = model(input_ids, attention_mask=attention_mask)\n logits = outputs.logits\n # Summary\n writer['acc'] += torch.eq(logits.argmax(dim=-1), labels).float().mean()\n writer['step'] += 1\n\n return float(writer['acc'] / writer['step'])\n\n def JSdivergence(self, output1, output2):\n divergence = (F.kl_div(output1.log_softmax(dim=-1), output2.softmax(dim=-1), reduce=False) + F.kl_div(output2.log_softmax(dim=-1), output1.softmax(dim=-1), reduce=False))/2\n return divergence.mean(dim=-1)\n \n def estimate_clean_probability(self, model, dataloader, prev_losses=None, loss_momentum=0.9, min_prob=0.5):\n sample_indexes = []\n sample_losses = []\n sample_correct_labels = []\n sample_preds = []\n \n model = model.eval()\n with torch.no_grad():\n for batch in dataloader:\n indexes = batch['id'].to(self.device)\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n noisy_labels = batch['noise_label'].to(self.device)\n\n # Get model predictions with stochastic routing\n preds = []\n probs = []\n for _ in range(1):\n # Apply random routing masks\n for layeridx in range(model.config.num_hidden_layers):\n mask = (torch.rand(input_ids.size(0)).cuda() < self.args.r_prob).float()\n model.bert.encoder.layer[layeridx].attention.output.main_adapter.routing_probs.data = mask\n model.bert.encoder.layer[layeridx].output.main_adapter.routing_probs.data = mask\n\n outputs = model(input_ids, attention_mask=attention_mask)\n logits = outputs.logits\n preds.append(logits.unsqueeze(0))\n probs.append(torch.softmax(logits, dim=-1).unsqueeze(0))\n \n preds = torch.cat(preds, dim=0).mean(dim=0)\n probs = torch.cat(probs, dim=0).mean(dim=0)\n\n # Calculate loss\n loss = (-F.one_hot(noisy_labels, self.num_class) * preds.log_softmax(dim=-1)).sum(dim=-1)\n \n # Apply momentum-based loss smoothing if available\n if prev_losses is not None:\n loss = loss * (1 - loss_momentum) + prev_losses.cuda()[indexes].squeeze() * loss_momentum\n \n sample_indexes.append(indexes)\n sample_losses.append(loss)\n sample_correct_labels.append((labels == noisy_labels).float())\n sample_preds.append(preds)\n \n # Aggregate batch results\n sample_preds = torch.cat(sample_preds, dim=0)\n sample_indexes = torch.cat(sample_indexes, dim=0)\n sample_correct_labels = torch.cat(sample_correct_labels, dim=0).cpu()\n sample_losses = torch.cat(sample_losses, dim=0)\n\n # Convert to numpy for GMM\n sample_losses_np = sample_losses.unsqueeze(-1).detach().cpu().numpy()\n\n # Fit GMM and estimate clean probabilities\n gm = GaussianMixture(n_components=2, random_state=0).fit(sample_losses_np)\n clean_component_idx = np.argmin(gm.means_) # Clean samples have smaller loss\n clean_probs = gm.predict_proba(sample_losses_np)[:, clean_component_idx]\n decision = (clean_probs > min_prob).astype(np.float32)\n \n # Convert to torch tensors\n decision_tensor = torch.from_numpy(decision).float()\n clean_probs_tensor = torch.tensor(clean_probs).float().to(self.device)\n \n # Map results back to original indexes\n decision_tensor[sample_indexes] = copy.deepcopy(decision_tensor)\n clean_probs_tensor[sample_indexes] = copy.deepcopy(clean_probs_tensor)\n sample_preds[sample_indexes] = copy.deepcopy(sample_preds)\n\n # Convert losses to tensor for return\n sample_losses_tensor = torch.tensor(sample_losses_np)\n sample_losses_tensor[sample_indexes] = copy.deepcopy(sample_losses_tensor)\n \n return decision_tensor, clean_probs_tensor, sample_preds, sample_losses_tensor\n\n def modeling_loss_pos_neg(self, pos_model, neg_model, epoch, dataloader):\n\n sample_indexes = []\n sample_losses = []\n sample_correct_labels = []\n sample_preds = []\n pos_model = pos_model.eval()\n neg_model = neg_model.eval()\n with torch.no_grad():\n for batch in dataloader:\n indexes = batch['id'].to(self.device)\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n noisy_labels = batch['noise_label'].to(self.device)\n\n\n outputs = pos_model(input_ids, attention_mask=attention_mask)\n pos_logits = outputs.logits\n \n # outputs = neg_model(input_ids, attention_mask=attention_mask)\n # neg_logits = outputs.logits \n \n # kl_div = self.jenson_shannon_divergence(pos_logits, neg_logits)\n \n # Model Updates\n loss = (-F.one_hot(noisy_labels, self.num_class) * pos_logits.log_softmax(dim=-1)).sum(dim=-1)\n sample_indexes.append(indexes)\n sample_losses.append(loss)\n sample_correct_labels.append((labels == noisy_labels).float())\n # sample_preds.append(probs)\n # sample_preds = torch.cat(sample_preds, dim=0)\n sample_indexes = torch.cat(sample_indexes, dim=0)\n sample_correct_labels = torch.cat(sample_correct_labels, dim=0).cpu()\n sample_losses = torch.cat(sample_losses, dim=0)\n sample_losses = sample_losses.unsqueeze(-1).detach().cpu().numpy()\n\n confidence_decision, decision_probs = self.estimate_MM(sample_losses, min_prob=0.5, is_min_clean=True)\n # sample_losses /= sample_losses.max()\n\n self.plot_MM(clean=sample_losses[sample_correct_labels == 1.0],\n noisy=sample_losses[sample_correct_labels == 0.0], title='{}_Confidence_{}'.format(self.args.dataset, epoch))\n print('[{}]: # of clean samples: {} (acc {})'.format('Confidence', confidence_decision.sum(), sample_correct_labels[confidence_decision == 1].mean()))\n confidence_decision[sample_indexes] = copy.deepcopy(confidence_decision)\n decision_probs[sample_indexes] = copy.deepcopy(decision_probs)\n # sample_preds[sample_indexes] = copy.deepcopy(sample_preds)\n return confidence_decision.float()#, sample_preds\n\n def apply_routing_decisions_to_adapters(self, model, routing_decisions, layer_idx):\n # Assign routing decisions to self-attention adapter\n model.bert.encoder.layer[layer_idx].attention.output.main_adapter.routing_probs.data = routing_decisions\n \n # Assign routing decisions to feed-forward adapter\n model.bert.encoder.layer[layer_idx].output.main_adapter.routing_probs.data = routing_decisions\n attention_routing_probs = model.bert.encoder.layer[layer_idx].attention.output.main_adapter.routing_probs.data\n output_routing_probs = model.bert.encoder.layer[layer_idx].output.main_adapter.routing_probs.data\n return attention_routing_probs, output_routing_probs\n\n def apply_stochastic_routing(self, model, input_ids, clean_probs=None, indexes=None, gamma=None, warm_up_period=False):\n batch_size = input_ids.size(0)\n batch_probs_output = list()\n # Determine routing probability\n if warm_up_period or clean_probs is None:\n # During warm-up, use a fixed probability for all samples\n routing_prob = gamma\n # Sample batch-specific masks once for each layer\n for layer_idx in range(model.config.num_hidden_layers):\n mask = (torch.rand(batch_size).cuda() < routing_prob).float()\n model.bert.encoder.layer[layer_idx].attention.output.main_adapter.routing_probs.data = mask\n model.bert.encoder.layer[layer_idx].output.main_adapter.routing_probs.data = mask\n else:\n # After warm-up, use the estimated clean probability scaled by gamma\n batch_probs = clean_probs[indexes].cuda() * gamma\n batch_probs_output.append(batch_probs)\n # Sample independent masks for each layer (as per the paper)\n for layer_idx in range(model.config.num_hidden_layers):\n # Sample from Bernoulli distribution: r ~ Bernoulli(\u03b3p)\n routing_decisions = (torch.rand(batch_size).cuda() < batch_probs).float()\n # Apply routing decisions to adapters\n attention_routing_probs, output_routing_probs = self.apply_routing_decisions_to_adapters(model, routing_decisions, layer_idx)\n return batch_probs_output\n\n def modeling_robustness(self, model, epoch, dataloader):\n sample_indexes = []\n sample_losses = []\n sample_correct_labels = []\n sample_preds = []\n model = model.eval()\n with torch.no_grad():\n for batch in dataloader:\n indexes = batch['id'].to(self.device)\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n noisy_labels = batch['noise_label'].to(self.device)\n\n outputs = model(input_ids, attention_mask=attention_mask)\n pos_logits = outputs.logits\n\n # Model Updates\n sample_indexes.append(indexes)\n sample_correct_labels.append((labels == noisy_labels).float())\n sample_preds.append(pos_logits)\n \n # sample_preds = torch.cat(sample_preds, dim=0)\n sample_indexes = torch.cat(sample_indexes, dim=0)\n sample_preds = torch.cat(sample_preds, dim=0)#.cpu()\n sample_correct_labels = torch.cat(sample_correct_labels, dim=0).cpu()\n # confidence_decision, decision_probs = self.estimate_MM(sample_losses, min_prob=0.5, is_min_clean=True)\n \n # K-NN\n norm_sample_preds = sample_preds / (torch.norm(sample_preds, dim=-1, keepdim=True) + 1e-8)\n knn_map = norm_sample_preds @ norm_sample_preds.transpose(0, 1)\n knn_values, knn_indices = torch.topk(knn_map, k=30)\n print(knn_values.size(), knn_indices.size()) # NER \ub4f1\uc758 Task\uc5d0 \ubd88\ub9ac\ud568 (Batch, Top-K)\n\n exit()\n\n\n self.plot_MM(clean=sample_losses[sample_correct_labels == 1.0],\n noisy=sample_losses[sample_correct_labels == 0.0], title='{}_Confidence_{}'.format(self.args.dataset, epoch))\n print('[{}]: # of clean samples: {} (acc {})'.format('Confidence', confidence_decision.sum(), sample_correct_labels[confidence_decision == 1].mean()))\n confidence_decision[sample_indexes] = copy.deepcopy(confidence_decision)\n decision_probs[sample_indexes] = copy.deepcopy(decision_probs)\n # sample_preds[sample_indexes] = copy.deepcopy(sample_preds)\n return confidence_decision.float()#, sample_preds\n\n def estimate_MM(self, data, min_prob, is_min_clean=True):\n gm = GaussianMixture(n_components=2, random_state=0).fit(data)\n if is_min_clean:\n clean_label_index = np.argmin(gm.means_)\n else:\n clean_label_index = np.argmax(gm.means_)\n\n probs = gm.predict_proba(data)[:, clean_label_index]\n decision = (probs > min_prob)\n decision = torch.from_numpy(decision).float()\n return decision, torch.tensor(probs).float().to(self.device)\n\n def plot_MM(self, clean, noisy, title):\n import matplotlib.pyplot as plt\n import matplotlib.ticker as mticker\n\n fig = plt.figure(figsize=(9, 3))\n\n plt.style.use('ggplot')\n plt.rcParams['axes.facecolor']='#EAEAF1'\n COLOR = 'black'\n plt.rcParams['text.color'] = COLOR\n plt.rcParams['axes.labelcolor'] = COLOR\n plt.rcParams['xtick.color'] = COLOR\n plt.rcParams['ytick.color'] = COLOR\n plt.rcParams.update({'font.size': 14})\n\n plt.hist(clean, bins=50, density=True, color='blue', alpha=0.65, label='True identification')\n plt.hist(noisy, bins=50, density=True, color='red', alpha=0.65, label='False identification')\n plt.legend()\n plt.xlabel('Predictive Confidence')\n plt.ylabel('Empirical PDF')\n plt.grid(True)\n plt.savefig('./plot/{}.pdf'.format(title.split('/')[-1]), bbox_inches='tight')\n plt.close()\n\n def jenson_shannon_divergence(self, net_1_logits, net_2_logits):\n from torch.functional import F\n net_1_probs = F.softmax(net_1_logits, dim=0)\n net_2_probs = F.softmax(net_2_logits, dim=0)\n \n total_m = 0.5 * (net_1_probs + net_1_probs)\n \n loss = 0.0\n loss += F.kl_div(F.log_softmax(net_1_logits, dim=0), total_m, reduce=False).sum(dim=-1)\n loss += F.kl_div(F.log_softmax(net_2_logits, dim=0), total_m, reduce=False).sum(dim=-1)\n return (0.5 * loss)\n\n def apply_consistency_regularization(self, logits, noisy_labels, ensemble_preds=None, indexes=None, temperature=0.5):\n # Standard cross-entropy loss with noisy labels\n ce_loss = (-F.one_hot(noisy_labels, self.num_class) * logits.log_softmax(dim=-1)).sum(dim=-1)\n \n # Get \"teacher\" predictions from previous ensemble\n teacher_preds = (ensemble_preds[indexes] / temperature).softmax(dim=-1)\n \n # Knowledge distillation loss (student-teacher)\n distillation_loss = (-teacher_preds.detach() * (logits / temperature).log_softmax(dim=-1)).sum(dim=-1)\n \n # Combine losses (implicitly using \u03bb=1 as scaling factor)\n combined_loss = ce_loss.mean() + distillation_loss.mean()\n return combined_loss\n\n def run(self):\n \n \"\"\" Start federated learning scenario \"\"\"\n # Load global validation set\n pos_train_loader, test_loader, _ = get_dataloader(dataset=self.dataset, train_bs=self.args.batch_size, test_bs=self.args.batch_size)\n\n # self.model = self.load_model('sst5_2_0.4281249940395355')\n\n optimizer = torch.optim.AdamW(self.model.parameters(), lr=self.args.lr) \n criterion = nn.CrossEntropyLoss(reduce=False)\n focal_criterion = FocalLoss(alpha=2.0)\n gce = GeneralizedCrossEntropy(self.num_class)\n \n scaler = GradScaler()\n def update_ema_variables(model, ema_model, alpha):\n # Use the true average until the exponential average is more correct\n for ema_param, param in zip(ema_model.parameters(), model.parameters()):\n ema_param.data.mul_(alpha).add_(1 - alpha, param.data)\n \n self.model_hist = []\n self.acc_hist = []\n\n # print(peft_modules)\n # exit()\n self.model = self.model.to(self.device)\n self.pre_model = self.pre_model.to(self.device)\n self.prev_ensemble_preds = None\n self.prev_sample_losses = None\n\n # self.model = copy.deepcopy()\n training_history = {'cka': [], 'test_acc': [], 'clean_acc': [], 'noise_acc': []}\n for epoch in range(self.args.epochs):\n writer = {'loss': 0., 'acc': 0., 'step': 0, 'cka': 0, 'clean_acc': 0, 'nclean': 0, 'noise_acc': 0, 'nnoise': 0}\n self.model.train()\n\n if epoch >= self.args.warm_up:\n decision, decision_probs, ensemble_preds, sample_losses = self.estimate_clean_probability(\n self.model, \n pos_train_loader, \n self.prev_sample_losses\n )\n self.prev_sample_losses = sample_losses\n\n for name, param in self.model.named_parameters():\n if 'main' in name:#or 'pool' in name: \n param.requires_grad = True\n else:\n param.requires_grad = False\n\n for batch in tqdm(pos_train_loader):\n\n indexes = batch['id'].to(self.device)\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n noisy_labels = batch['noise_label'].to(self.device)\n\n # decision probability updates\n batch_probs_output = self.apply_stochastic_routing(\n model=self.model,\n input_ids=input_ids,\n clean_probs=decision_probs if epoch >= self.args.warm_up else None,\n indexes=indexes,\n gamma=self.args.r_prob,\n warm_up_period=(epoch < self.args.warm_up)\n )\n\n outputs = self.model(input_ids, attention_mask=attention_mask, output_hidden_states=False)\n logits = outputs.logits\n\n # Model Updates\n optimizer.zero_grad()\n if epoch >= self.args.warm_up:\n loss = self.apply_consistency_regularization(\n logits=logits,\n noisy_labels=noisy_labels,\n ensemble_preds=ensemble_preds if epoch >= self.args.warm_up else None,\n indexes=indexes if epoch >= self.args.warm_up else None,\n temperature=0.5\n )\n\n else:\n loss = (-F.one_hot(noisy_labels, self.num_class) * logits.log_softmax(dim=-1)).sum(dim=-1)\n loss = loss.mean()\n loss.backward(retain_graph=True)\n optimizer.step()\n\n writer['loss'] += loss.mean().item()\n # writer['cka'] += ((fixed_hidden_state - hidden_state) ** 2).mean() # L2 distance\n writer['acc'] += torch.eq(logits.argmax(dim=-1), labels).float().sum()\n \n writer['clean_acc'] += torch.eq(logits[noisy_labels == labels].argmax(dim=-1), labels[noisy_labels == labels]).float().sum()\n writer['nclean'] += (noisy_labels == labels).float().sum()\n \n writer['noise_acc'] += torch.eq(logits[noisy_labels != labels].argmax(dim=-1), noisy_labels[noisy_labels != labels]).float().sum()\n writer['nnoise'] += (noisy_labels != labels).float().sum()\n \n writer['step'] += len(logits)\n\n # Evaluate the global model\n cka = writer['cka'] / writer['step']\n clean_acc = writer['clean_acc'] / writer['nclean']\n noise_acc = writer['noise_acc'] / writer['nnoise']\n test_acc = self.testing_plm(global_loader=test_loader)\n\n training_history['cka'].append(float(cka))\n training_history['clean_acc'].append(float(clean_acc))\n training_history['noise_acc'].append(float(noise_acc))\n training_history['test_acc'].append(float(test_acc))\n\n print('Epoch ({}) Test accuracy {}, avg loss {}, cka {}'.format(epoch, test_acc, writer['loss']/writer['step'], writer['cka'] / writer['step']))\n \n for key in training_history:\n print(f'{key}=', training_history[key])\n\n def load_model(self, file_name):\n model = pickle.load(open(os.path.join(self.args.modeldir, f'{file_name}.pkl'), 'rb'))\n return model\n\n def save_model(self, model, file_name):\n pickle.dump(model, open(os.path.join(self.args.modeldir, f'{file_name}.pkl'), 'wb'))\n" }, { "task_id": 1, "indent": 2, "script": "\npython main.py --dataset SetFit/sst5 --model bert-base-uncased --alg routing_adapter --device 0 --adapter routing_adapter --batch_size 32 --epochs 8\n", "latex_code": "\n\\paragraph{Sampling routing decision}\nOnce the clean probability is estimated, the PEFT modules are stochastically routed across the transformer layers. To derive the routing decision (i.e., routing through PEFT or bypassing PEFT), we sample the decision from a Bernoulli distribution with the estimated clean probability $p$:\n\n\\begin{equation}\\label{eq:sampling}\nr \\sim \\textsc{Bernoulli}(\\gamma p),\n\\end{equation}\nwhere $r$ is an independent Bernoulli random variable with a probability $\\gamma p$ of being $1$ and a probability $1 - \\gamma p$ of being 0. The coefficient $\\gamma \\in [0,1]$ limits the range of clean probability, setting its upper bound at $\\gamma$. This coefficient plays a role in preventing over-reliance on the estimated probability, considering that small-loss samples might still contain noisy samples (i.e., high clean probability despite being noisy samples) \\cite{devidemix}. \nCrucially, this routing decision is independently made at each layer, allowing for the fine-grained differentiation of each sample's influence based on its probability of being clean.\nFor example, if the clean probability is 70\\% and the number of layers is 10, seven PEFT modules are activated in average\\footnote{While different positions of the PEFT could have varying effects on the prediction \\cite{design}, in this work, we focus solely on the clean probability as a trigger to activate the PEFT. We reserve further exploration of this for future work.}.\n", "completion_path": "./solvers/routing_adapter_solver.py", "namespace": "solvers.routing_adapter_solver.RoutingAdapterSolver.apply_stochastic_routing", "type": "method", "signature_position": [ 214, 214 ], "body_position": [ 215, 236 ], "ReferenceCode_With_Comments": "\nbatch_size = input_ids.size(0)\nattention_routing_probs = list()\noutput_routing_probs = list()\n\n# ---------------------------------------------------------------------------\n# Snippet 1: Handle the warm-up period case, where clean probabilities are not yet\n# estimated. This corresponds to an implicit initialization phase before the\n# process described in the LaTeX, using a fixed probability \u03b3 instead of \u03b3p.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nif warm_up_period or clean_probs is None:\n # During warm-up, use a fixed probability for all samples\n routing_prob = gamma\n # Sample batch-specific masks once for each layer\n for layer_idx in range(model.config.num_hidden_layers):\n mask = (torch.rand(batch_size).cuda() < routing_prob).float()\n model.bert.encoder.layer[layer_idx].attention.output.main_adapter.routing_probs.data = mask\n model.bert.encoder.layer[layer_idx].output.main_adapter.routing_probs.data = mask\n attention_routing_probs.append(model.bert.encoder.layer[layer_idx].attention.output.main_adapter.routing_probs.data)\n output_routing_probs.append(model.bert.encoder.layer[layer_idx].output.main_adapter.routing_probs.data)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: After warm-up, implement the stochastic routing as described in\n# the LaTeX snippet. This directly implements the equation r ~ Bernoulli(\u03b3p)\n# where p is the clean probability and \u03b3 is the coefficient that limits its range.\n# The routing is independently applied across layers as specified in the paragraph.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nelse:\n # After warm-up, use the estimated clean probability scaled by gamma\n batch_probs = clean_probs[indexes].cuda() * gamma\n # Sample independent masks for each layer (as per the paper)\n for layer_idx in range(model.config.num_hidden_layers):\n # Sample from Bernoulli distribution: r ~ Bernoulli(\u03b3p)\n routing_decisions = (torch.rand(batch_size).cuda() < batch_probs).float()\n # Apply routing decisions to adapters\n attention_routing_probs_, output_routing_probs_ = self.apply_routing_decisions_to_adapters(model, routing_decisions, layer_idx)\n attention_routing_probs.append(attention_routing_probs_)\n output_routing_probs.append(output_routing_probs_)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Return the batch probabilities for monitoring. While not explicitly\n# mentioned in the LaTeX, this allows tracking the actual probabilities used\n# during training.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nreturn attention_routing_probs, output_routing_probs\n# [End Snippet 3]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The LaTeX code omits the distinct handling of the warm-up period. The reference implementation uses a fixed probability during warm-up, effectively bypassing the use of clean probability estimates. This staged approach\u2014using a uniform fixed probability during warm-up and transitioning to the scaled clean probability thereafter\u2014is essential to the behavior of the model but is not described in the LaTeX.\n - The LaTeX description does not detail the workflow of applying the sampled routing decisions to the transformer's modules. In the reference code, after sampling the Bernoulli decisions, these values are immediately used to update the state of both the attention and feed-forward adapter modules for each transformer layer. This step is crucial because it actively controls whether each module is activated or bypassed during model execution.\n \n - Mismatched Details:\n - The LaTeX description does not detail the workflow of applying the sampled routing decisions to the transformer's modules. In the reference code, after sampling the Bernoulli decisions, these values are immediately used to update the state of both the attention and feed-forward adapter modules for each transformer layer. This step is crucial because it actively controls whether each module is activated or bypassed during model execution.\n \n", "Missing_details": [ "\n- The LaTeX code omits the distinct handling of the warm-up period. The reference implementation uses a fixed probability during warm-up, effectively bypassing the use of clean probability estimates. This staged approach\u2014using a uniform fixed probability during warm-up and transitioning to the scaled clean probability thereafter\u2014is essential to the behavior of the model but is not described in the LaTeX.\n", "\n- The LaTeX description does not detail the workflow of applying the sampled routing decisions to the transformer's modules. In the reference code, after sampling the Bernoulli decisions, these values are immediately used to update the state of both the attention and feed-forward adapter modules for each transformer layer. This step is crucial because it actively controls whether each module is activated or bypassed during model execution.\n", "\n- The LaTeX description does not detail the workflow of applying the sampled routing decisions to the transformer's modules. In the reference code, after sampling the Bernoulli decisions, these values are immediately used to update the state of both the attention and feed-forward adapter modules for each transformer layer. This step is crucial because it actively controls whether each module is activated or bypassed during model execution.\n" ], "Mismatched_details": [] }, "Arguments": { "string": "\nInput Variables:\n - model (BertForSequenceClassification):\n The transformer model with parameter-efficient fine-tuning modules to which routing decisions will be applied.\n - input_ids (torch.Tensor, shape=[batch_size, seq_len]):\n Tensor of token IDs used to determine batch size for creating routing masks.\n - clean_probs (torch.Tensor, optional, shape=[dataset_size]):\n Tensor containing clean probability estimates for all samples in the dataset.\n - indexes (torch.Tensor, optional, shape=[batch_size]):\n Batch sample indexes used to retrieve the corresponding clean probabilities from clean_probs.\n - gamma (float, optional):\n Coefficient that limits the range of clean probability (0 \u2264 \u03b3 \u2264 1), controlling the maximum\n activation probability of PEFT modules.\n - warm_up_period (bool, optional):\n Flag indicating if the model is in warm-up stage; if True, routing is uniformly determined by clean probability alone\n", "Arguments_list": [ { "name": "model", "string": "\n- model (BertForSequenceClassification):\n The transformer model with parameter-efficient fine-tuning modules to which routing decisions will be applied.\n", "dependency": "BertForSequenceClassification" }, { "name": "input_ids", "string": "\n- input_ids (torch.Tensor, shape=[batch_size, seq_len]):\n Tensor of token IDs used to determine batch size for creating routing masks.\n", "dependency": null }, { "name": "clean_probs", "string": "\n- clean_probs (torch.Tensor, optional, shape=[dataset_size]):\n Tensor containing clean probability estimates for all samples in the dataset.\n", "dependency": null }, { "name": "indexes", "string": " \n- indexes (torch.Tensor, optional, shape=[batch_size]):\n Batch sample indexes used to retrieve the corresponding clean probabilities from clean_probs.\n", "dependency": null }, { "name": "gamma", "string": "\n- gamma (float, optional):\n Coefficient that limits the range of clean probability (0 \u2264 \u03b3 \u2264 1), controlling the maximum\n activation probability of PEFT modules.\n", "dependency": null }, { "name": "warm_up_period", "string": "\n- warm_up_period (bool, optional): \n Flag indicating if the model is in warm-up stage; if True, routing is uniformly determined by clean probability alone\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-file Dependencies:\n - RoutingAdapterSolver.apply_routing_decisions_to_adapters\n \n - Cross-file Dependencies:\n - None\n", "intra_file": [ "RoutingAdapterSolver.apply_routing_decisions_to_adapters" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.rand\n", "list": [ "torch.rand" ] }, "Return": { "Return_String": "\nOutput Variables:\n - attention_routing_probs (list of torch.Tensor): A list where each element is a tensor reference (shape=[batch_size]) to the routing probability data applied to the self-attention adapters in each transformer layer. Each tensor contains binary values (0.0 or 1.0) indicating whether the adapter should be activated (1.0) or bypassed (0.0) for each sample in the batch. The list has length equal to the number of transformer layers.\n - output_routing_probs (list of torch.Tensor): A list where each element is a tensor reference (shape=[batch_size]) to the routing probability data applied to the feed-forward output adapters in each transformer layer. Like the attention adapter tensors, these contain binary values for each sample. The list has length equal to the number of transformer layers.output_routing_probs (torch.Tensor, shape=[batch_size]): A tensor reference to the routing probability data that has been applied to the feed-forward output adapter in the same transformer layer. Like the attention adapter tensor, this contains binary values for each sample, indicating whether the feed-forward adapter should be activated or bypassed. While these values should match the attention routing probabilities (since both are set to the same values), returning both allows for verification that routing was properly applied to both components.\n", "Return_list": [ { "name": "attention_routing_probs", "string": "\n- attention_routing_probs (list of torch.Tensor): A list where each element is a tensor reference (shape=[batch_size]) to the routing probability data applied to the self-attention adapters in each transformer layer. Each tensor contains binary values (0.0 or 1.0) indicating whether the adapter should be activated (1.0) or bypassed (0.0) for each sample in the batch. The list has length equal to the number of transformer layers.\n", "dependency": null }, { "name": "output_routing_probs", "string": "\n- output_routing_probs (list of torch.Tensor): A list where each element is a tensor reference (shape=[batch_size]) to the routing probability data applied to the feed-forward output adapters in each transformer layer. Like the attention adapter tensors, these contain binary values for each sample. The list has length equal to the number of transformer layers.output_routing_probs (torch.Tensor, shape=[batch_size]): A tensor reference to the routing probability data that has been applied to the feed-forward output adapter in the same transformer layer. Like the attention adapter tensor, this contains binary values for each sample, indicating whether the feed-forward adapter should be activated or bypassed. While these values should match the attention routing probabilities (since both are set to the same values), returning both allows for verification that routing was properly applied to both components.\n", "dependency": null } ] }, "ori_python_file": "import os\nimport copy\nimport time\nimport pickle\nimport datetime\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.manifold import TSNE\n\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom utils import get_num_classes, initialize_networks, get_dataloader\nfrom sklearn.mixture import GaussianMixture\nfrom blocks import AdaMixAdapter\nfrom loss import GeneralizedCrossEntropy\nimport logging\nlogging.getLogger(\"imported_module\").setLevel(logging.WARNING)\n\nfrom torch.cuda.amp import GradScaler \nfrom loss import FocalLoss\n\nclass RoutingAdapterSolver(object):\n\n def __init__(self, args, dataset):\n \"\"\" Initialize configurations. \"\"\"\n self.args = args\n self.dataset = dataset\n self.num_class = get_num_classes(args.dataset)\n\n # Load training networks\n self.model = initialize_networks(dataset=args.dataset, model=args.model, adapter=args.adapter)\n self.pre_model = initialize_networks(dataset=args.dataset, model=args.model, adapter='none')\n \n # Optimizer\n self.criterion = nn.CrossEntropyLoss().cuda()\n self.device = torch.device('cuda')\n\n def testing_plm(self, global_loader, model=None):\n writer = {'loss': 0., 'acc': 0., 'step': 0}\n if model is None:\n model = self.model\n net = model.to(self.device)\n net.eval()\n\n writer['loss'] = 0.\n writer['acc'] = 0.\n writer['step'] = 0.\n\n predictions = []\n labels = []\n with torch.no_grad():\n for batch in global_loader:\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n\n # decision probability updates\n for layeridx in range(model.config.num_hidden_layers):\n mask = (torch.rand(input_ids.size(0)).cuda() < self.args.r_prob).float()\n model.bert.encoder.layer[layeridx].attention.output.main_adapter.routing_probs.data = mask\n model.bert.encoder.layer[layeridx].output.main_adapter.routing_probs.data = mask\n\n outputs = model(input_ids, attention_mask=attention_mask)\n logits = outputs.logits\n # Summary\n writer['acc'] += torch.eq(logits.argmax(dim=-1), labels).float().mean()\n writer['step'] += 1\n\n return float(writer['acc'] / writer['step'])\n\n def JSdivergence(self, output1, output2):\n divergence = (F.kl_div(output1.log_softmax(dim=-1), output2.softmax(dim=-1), reduce=False) + F.kl_div(output2.log_softmax(dim=-1), output1.softmax(dim=-1), reduce=False))/2\n return divergence.mean(dim=-1)\n \n def estimate_clean_probability(self, model, dataloader, prev_losses=None, loss_momentum=0.9, min_prob=0.5):\n sample_indexes = []\n sample_losses = []\n sample_correct_labels = []\n sample_preds = []\n \n model = model.eval()\n with torch.no_grad():\n for batch in dataloader:\n indexes = batch['id'].to(self.device)\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n noisy_labels = batch['noise_label'].to(self.device)\n\n # Get model predictions with stochastic routing\n preds = []\n probs = []\n for _ in range(1):\n # Apply random routing masks\n for layeridx in range(model.config.num_hidden_layers):\n mask = (torch.rand(input_ids.size(0)).cuda() < self.args.r_prob).float()\n model.bert.encoder.layer[layeridx].attention.output.main_adapter.routing_probs.data = mask\n model.bert.encoder.layer[layeridx].output.main_adapter.routing_probs.data = mask\n\n outputs = model(input_ids, attention_mask=attention_mask)\n logits = outputs.logits\n preds.append(logits.unsqueeze(0))\n probs.append(torch.softmax(logits, dim=-1).unsqueeze(0))\n \n preds = torch.cat(preds, dim=0).mean(dim=0)\n probs = torch.cat(probs, dim=0).mean(dim=0)\n\n # Calculate loss\n loss = (-F.one_hot(noisy_labels, self.num_class) * preds.log_softmax(dim=-1)).sum(dim=-1)\n \n # Apply momentum-based loss smoothing if available\n if prev_losses is not None:\n loss = loss * (1 - loss_momentum) + prev_losses.cuda()[indexes].squeeze() * loss_momentum\n \n sample_indexes.append(indexes)\n sample_losses.append(loss)\n sample_correct_labels.append((labels == noisy_labels).float())\n sample_preds.append(preds)\n \n # Aggregate batch results\n sample_preds = torch.cat(sample_preds, dim=0)\n sample_indexes = torch.cat(sample_indexes, dim=0)\n sample_correct_labels = torch.cat(sample_correct_labels, dim=0).cpu()\n sample_losses = torch.cat(sample_losses, dim=0)\n\n # Convert to numpy for GMM\n sample_losses_np = sample_losses.unsqueeze(-1).detach().cpu().numpy()\n\n # Fit GMM and estimate clean probabilities\n gm = GaussianMixture(n_components=2, random_state=0).fit(sample_losses_np)\n clean_component_idx = np.argmin(gm.means_) # Clean samples have smaller loss\n clean_probs = gm.predict_proba(sample_losses_np)[:, clean_component_idx]\n decision = (clean_probs > min_prob).astype(np.float32)\n \n # Convert to torch tensors\n decision_tensor = torch.from_numpy(decision).float()\n clean_probs_tensor = torch.tensor(clean_probs).float().to(self.device)\n \n # Map results back to original indexes\n decision_tensor[sample_indexes] = copy.deepcopy(decision_tensor)\n clean_probs_tensor[sample_indexes] = copy.deepcopy(clean_probs_tensor)\n sample_preds[sample_indexes] = copy.deepcopy(sample_preds)\n\n # Convert losses to tensor for return\n sample_losses_tensor = torch.tensor(sample_losses_np)\n sample_losses_tensor[sample_indexes] = copy.deepcopy(sample_losses_tensor)\n \n return decision_tensor, clean_probs_tensor, sample_preds, sample_losses_tensor\n\n def modeling_loss_pos_neg(self, pos_model, neg_model, epoch, dataloader):\n\n sample_indexes = []\n sample_losses = []\n sample_correct_labels = []\n sample_preds = []\n pos_model = pos_model.eval()\n neg_model = neg_model.eval()\n with torch.no_grad():\n for batch in dataloader:\n indexes = batch['id'].to(self.device)\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n noisy_labels = batch['noise_label'].to(self.device)\n\n\n outputs = pos_model(input_ids, attention_mask=attention_mask)\n pos_logits = outputs.logits\n \n # outputs = neg_model(input_ids, attention_mask=attention_mask)\n # neg_logits = outputs.logits \n \n # kl_div = self.jenson_shannon_divergence(pos_logits, neg_logits)\n \n # Model Updates\n loss = (-F.one_hot(noisy_labels, self.num_class) * pos_logits.log_softmax(dim=-1)).sum(dim=-1)\n sample_indexes.append(indexes)\n sample_losses.append(loss)\n sample_correct_labels.append((labels == noisy_labels).float())\n # sample_preds.append(probs)\n # sample_preds = torch.cat(sample_preds, dim=0)\n sample_indexes = torch.cat(sample_indexes, dim=0)\n sample_correct_labels = torch.cat(sample_correct_labels, dim=0).cpu()\n sample_losses = torch.cat(sample_losses, dim=0)\n sample_losses = sample_losses.unsqueeze(-1).detach().cpu().numpy()\n\n confidence_decision, decision_probs = self.estimate_MM(sample_losses, min_prob=0.5, is_min_clean=True)\n # sample_losses /= sample_losses.max()\n\n self.plot_MM(clean=sample_losses[sample_correct_labels == 1.0],\n noisy=sample_losses[sample_correct_labels == 0.0], title='{}_Confidence_{}'.format(self.args.dataset, epoch))\n print('[{}]: # of clean samples: {} (acc {})'.format('Confidence', confidence_decision.sum(), sample_correct_labels[confidence_decision == 1].mean()))\n confidence_decision[sample_indexes] = copy.deepcopy(confidence_decision)\n decision_probs[sample_indexes] = copy.deepcopy(decision_probs)\n # sample_preds[sample_indexes] = copy.deepcopy(sample_preds)\n return confidence_decision.float()#, sample_preds\n\n def apply_routing_decisions_to_adapters(self, model, routing_decisions, layer_idx):\n # Assign routing decisions to self-attention adapter\n model.bert.encoder.layer[layer_idx].attention.output.main_adapter.routing_probs.data = routing_decisions\n \n # Assign routing decisions to feed-forward adapter\n model.bert.encoder.layer[layer_idx].output.main_adapter.routing_probs.data = routing_decisions\n attention_routing_probs = model.bert.encoder.layer[layer_idx].attention.output.main_adapter.routing_probs.data\n output_routing_probs = model.bert.encoder.layer[layer_idx].output.main_adapter.routing_probs.data\n return attention_routing_probs, output_routing_probs\n\n def apply_stochastic_routing(self, model, input_ids, clean_probs=None, indexes=None, gamma=None, warm_up_period=False):\n batch_size = input_ids.size(0)\n batch_probs_output = list()\n # Determine routing probability\n if warm_up_period or clean_probs is None:\n # During warm-up, use a fixed probability for all samples\n routing_prob = gamma\n # Sample batch-specific masks once for each layer\n for layer_idx in range(model.config.num_hidden_layers):\n mask = (torch.rand(batch_size).cuda() < routing_prob).float()\n model.bert.encoder.layer[layer_idx].attention.output.main_adapter.routing_probs.data = mask\n model.bert.encoder.layer[layer_idx].output.main_adapter.routing_probs.data = mask\n else:\n # After warm-up, use the estimated clean probability scaled by gamma\n batch_probs = clean_probs[indexes].cuda() * gamma\n batch_probs_output.append(batch_probs)\n # Sample independent masks for each layer (as per the paper)\n for layer_idx in range(model.config.num_hidden_layers):\n # Sample from Bernoulli distribution: r ~ Bernoulli(\u03b3p)\n routing_decisions = (torch.rand(batch_size).cuda() < batch_probs).float()\n # Apply routing decisions to adapters\n attention_routing_probs, output_routing_probs = self.apply_routing_decisions_to_adapters(model, routing_decisions, layer_idx)\n return batch_probs_output\n\n def modeling_robustness(self, model, epoch, dataloader):\n sample_indexes = []\n sample_losses = []\n sample_correct_labels = []\n sample_preds = []\n model = model.eval()\n with torch.no_grad():\n for batch in dataloader:\n indexes = batch['id'].to(self.device)\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n noisy_labels = batch['noise_label'].to(self.device)\n\n outputs = model(input_ids, attention_mask=attention_mask)\n pos_logits = outputs.logits\n\n # Model Updates\n sample_indexes.append(indexes)\n sample_correct_labels.append((labels == noisy_labels).float())\n sample_preds.append(pos_logits)\n \n # sample_preds = torch.cat(sample_preds, dim=0)\n sample_indexes = torch.cat(sample_indexes, dim=0)\n sample_preds = torch.cat(sample_preds, dim=0)#.cpu()\n sample_correct_labels = torch.cat(sample_correct_labels, dim=0).cpu()\n # confidence_decision, decision_probs = self.estimate_MM(sample_losses, min_prob=0.5, is_min_clean=True)\n \n # K-NN\n norm_sample_preds = sample_preds / (torch.norm(sample_preds, dim=-1, keepdim=True) + 1e-8)\n knn_map = norm_sample_preds @ norm_sample_preds.transpose(0, 1)\n knn_values, knn_indices = torch.topk(knn_map, k=30)\n print(knn_values.size(), knn_indices.size()) # NER \ub4f1\uc758 Task\uc5d0 \ubd88\ub9ac\ud568 (Batch, Top-K)\n\n exit()\n\n\n self.plot_MM(clean=sample_losses[sample_correct_labels == 1.0],\n noisy=sample_losses[sample_correct_labels == 0.0], title='{}_Confidence_{}'.format(self.args.dataset, epoch))\n print('[{}]: # of clean samples: {} (acc {})'.format('Confidence', confidence_decision.sum(), sample_correct_labels[confidence_decision == 1].mean()))\n confidence_decision[sample_indexes] = copy.deepcopy(confidence_decision)\n decision_probs[sample_indexes] = copy.deepcopy(decision_probs)\n # sample_preds[sample_indexes] = copy.deepcopy(sample_preds)\n return confidence_decision.float()#, sample_preds\n\n def estimate_MM(self, data, min_prob, is_min_clean=True):\n gm = GaussianMixture(n_components=2, random_state=0).fit(data)\n if is_min_clean:\n clean_label_index = np.argmin(gm.means_)\n else:\n clean_label_index = np.argmax(gm.means_)\n\n probs = gm.predict_proba(data)[:, clean_label_index]\n decision = (probs > min_prob)\n decision = torch.from_numpy(decision).float()\n return decision, torch.tensor(probs).float().to(self.device)\n\n def plot_MM(self, clean, noisy, title):\n import matplotlib.pyplot as plt\n import matplotlib.ticker as mticker\n\n fig = plt.figure(figsize=(9, 3))\n\n plt.style.use('ggplot')\n plt.rcParams['axes.facecolor']='#EAEAF1'\n COLOR = 'black'\n plt.rcParams['text.color'] = COLOR\n plt.rcParams['axes.labelcolor'] = COLOR\n plt.rcParams['xtick.color'] = COLOR\n plt.rcParams['ytick.color'] = COLOR\n plt.rcParams.update({'font.size': 14})\n\n plt.hist(clean, bins=50, density=True, color='blue', alpha=0.65, label='True identification')\n plt.hist(noisy, bins=50, density=True, color='red', alpha=0.65, label='False identification')\n plt.legend()\n plt.xlabel('Predictive Confidence')\n plt.ylabel('Empirical PDF')\n plt.grid(True)\n plt.savefig('./plot/{}.pdf'.format(title.split('/')[-1]), bbox_inches='tight')\n plt.close()\n\n def jenson_shannon_divergence(self, net_1_logits, net_2_logits):\n from torch.functional import F\n net_1_probs = F.softmax(net_1_logits, dim=0)\n net_2_probs = F.softmax(net_2_logits, dim=0)\n \n total_m = 0.5 * (net_1_probs + net_1_probs)\n \n loss = 0.0\n loss += F.kl_div(F.log_softmax(net_1_logits, dim=0), total_m, reduce=False).sum(dim=-1)\n loss += F.kl_div(F.log_softmax(net_2_logits, dim=0), total_m, reduce=False).sum(dim=-1)\n return (0.5 * loss)\n\n def apply_consistency_regularization(self, logits, noisy_labels, ensemble_preds=None, indexes=None, temperature=0.5):\n # Standard cross-entropy loss with noisy labels\n ce_loss = (-F.one_hot(noisy_labels, self.num_class) * logits.log_softmax(dim=-1)).sum(dim=-1)\n \n # Get \"teacher\" predictions from previous ensemble\n teacher_preds = (ensemble_preds[indexes] / temperature).softmax(dim=-1)\n \n # Knowledge distillation loss (student-teacher)\n distillation_loss = (-teacher_preds.detach() * (logits / temperature).log_softmax(dim=-1)).sum(dim=-1)\n \n # Combine losses (implicitly using \u03bb=1 as scaling factor)\n combined_loss = ce_loss.mean() + distillation_loss.mean()\n return combined_loss\n\n def run(self):\n \n \"\"\" Start federated learning scenario \"\"\"\n # Load global validation set\n pos_train_loader, test_loader, _ = get_dataloader(dataset=self.dataset, train_bs=self.args.batch_size, test_bs=self.args.batch_size)\n\n # self.model = self.load_model('sst5_2_0.4281249940395355')\n\n optimizer = torch.optim.AdamW(self.model.parameters(), lr=self.args.lr) \n criterion = nn.CrossEntropyLoss(reduce=False)\n focal_criterion = FocalLoss(alpha=2.0)\n gce = GeneralizedCrossEntropy(self.num_class)\n \n scaler = GradScaler()\n def update_ema_variables(model, ema_model, alpha):\n # Use the true average until the exponential average is more correct\n for ema_param, param in zip(ema_model.parameters(), model.parameters()):\n ema_param.data.mul_(alpha).add_(1 - alpha, param.data)\n \n self.model_hist = []\n self.acc_hist = []\n\n # print(peft_modules)\n # exit()\n self.model = self.model.to(self.device)\n self.pre_model = self.pre_model.to(self.device)\n self.prev_ensemble_preds = None\n self.prev_sample_losses = None\n\n # self.model = copy.deepcopy()\n training_history = {'cka': [], 'test_acc': [], 'clean_acc': [], 'noise_acc': []}\n for epoch in range(self.args.epochs):\n writer = {'loss': 0., 'acc': 0., 'step': 0, 'cka': 0, 'clean_acc': 0, 'nclean': 0, 'noise_acc': 0, 'nnoise': 0}\n self.model.train()\n\n if epoch >= self.args.warm_up:\n decision, decision_probs, ensemble_preds, sample_losses = self.estimate_clean_probability(\n self.model, \n pos_train_loader, \n self.prev_sample_losses\n )\n self.prev_sample_losses = sample_losses\n\n for name, param in self.model.named_parameters():\n if 'main' in name:#or 'pool' in name: \n param.requires_grad = True\n else:\n param.requires_grad = False\n\n for batch in tqdm(pos_train_loader):\n\n indexes = batch['id'].to(self.device)\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n noisy_labels = batch['noise_label'].to(self.device)\n\n # decision probability updates\n batch_probs_output = self.apply_stochastic_routing(\n model=self.model,\n input_ids=input_ids,\n clean_probs=decision_probs if epoch >= self.args.warm_up else None,\n indexes=indexes,\n gamma=self.args.r_prob,\n warm_up_period=(epoch < self.args.warm_up)\n )\n\n outputs = self.model(input_ids, attention_mask=attention_mask, output_hidden_states=False)\n logits = outputs.logits\n\n # Model Updates\n optimizer.zero_grad()\n if epoch >= self.args.warm_up:\n loss = self.apply_consistency_regularization(\n logits=logits,\n noisy_labels=noisy_labels,\n ensemble_preds=ensemble_preds if epoch >= self.args.warm_up else None,\n indexes=indexes if epoch >= self.args.warm_up else None,\n temperature=0.5\n )\n\n else:\n loss = (-F.one_hot(noisy_labels, self.num_class) * logits.log_softmax(dim=-1)).sum(dim=-1)\n loss = loss.mean()\n loss.backward(retain_graph=True)\n optimizer.step()\n\n writer['loss'] += loss.mean().item()\n # writer['cka'] += ((fixed_hidden_state - hidden_state) ** 2).mean() # L2 distance\n writer['acc'] += torch.eq(logits.argmax(dim=-1), labels).float().sum()\n \n writer['clean_acc'] += torch.eq(logits[noisy_labels == labels].argmax(dim=-1), labels[noisy_labels == labels]).float().sum()\n writer['nclean'] += (noisy_labels == labels).float().sum()\n \n writer['noise_acc'] += torch.eq(logits[noisy_labels != labels].argmax(dim=-1), noisy_labels[noisy_labels != labels]).float().sum()\n writer['nnoise'] += (noisy_labels != labels).float().sum()\n \n writer['step'] += len(logits)\n\n # Evaluate the global model\n cka = writer['cka'] / writer['step']\n clean_acc = writer['clean_acc'] / writer['nclean']\n noise_acc = writer['noise_acc'] / writer['nnoise']\n test_acc = self.testing_plm(global_loader=test_loader)\n\n training_history['cka'].append(float(cka))\n training_history['clean_acc'].append(float(clean_acc))\n training_history['noise_acc'].append(float(noise_acc))\n training_history['test_acc'].append(float(test_acc))\n\n print('Epoch ({}) Test accuracy {}, avg loss {}, cka {}'.format(epoch, test_acc, writer['loss']/writer['step'], writer['cka'] / writer['step']))\n \n for key in training_history:\n print(f'{key}=', training_history[key])\n\n def load_model(self, file_name):\n model = pickle.load(open(os.path.join(self.args.modeldir, f'{file_name}.pkl'), 'rb'))\n return model\n\n def save_model(self, model, file_name):\n pickle.dump(model, open(os.path.join(self.args.modeldir, f'{file_name}.pkl'), 'wb'))\n" }, { "task_id": 2, "indent": 2, "completion_path": "./solvers/routing_adapter_solver.py", "script": "\npython main.py --dataset SetFit/sst5 --model bert-base-uncased --alg routing_adapter --device 0 --adapter routing_adapter --batch_size 32 --epochs 8\n", "latex_code": "\n\\paragraph{Activating PEFT based on the decision}\nThe routing decisions across different layers are then applied to all PEFT modules. Formally, let the hidden states in the $l$-th layer be denoted as $h^{(l)}$, and the hidden state in the next layer is derived as follows:\n\\begin{equation}\nh^{(l+1)} = \\begin{cases}\n\\text{Trans}^{(l)} (h^{(l)}, \\delta^{(l)} + \\theta^{(l)}),&\\text{if } r^{(l)}=1 \\\\ \\text{Trans}^{(l)} (h^{(l)}, \\theta^{(l)}),&\\text{if }r^{(l)}=0\n\\end{cases} \n\\end{equation}\nwhere $\\delta^{(l)}$ and $\\theta^{(l)}$ represent PEFT module and pre-trained parameters in the $l$-th layer, respectively, and $r^{(l)}$ indicates the routing decision on the layer. $\\text{Trans}^{(l)}(\\cdot)$ denotes the function of the transformer block. Through the above routing decision, CleaR activates a subset of PEFT modules, i.e., $\\boldsymbol{{\\delta}_r} = \\{\\delta^{(l)} | \\delta^{(l)} \\in \\boldsymbol{\\delta}, r^{(l)} = 1\\}$, on each forward pass. \nThis routing scheme ensures that PEFT modules are favorably activated for potentially clean samples and deactivated for noisy ones, thereby reducing the influence of noisy samples. \n", "namespace": "solvers.routing_adapter_solver.RoutingAdapterSolver.apply_routing_decisions_to_adapters", "type": "method", "signature_position": [ 204, 204 ], "body_position": [ 205, 212 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Apply the routing decision to the self-attention adapter in the\n# specified layer. This corresponds to the first case in the equation where\n# r^(l)=1 activates the PEFT module \u03b4^(l) in the attention mechanism.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\n# Assign routing decisions to self-attention adapter\nmodel.bert.encoder.layer[layer_idx].attention.output.main_adapter.routing_probs.data = routing_decisions\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Apply the same routing decision to the feed-forward adapter in\n# the same layer. This ensures consistent PEFT activation across both sub-layers\n# within a single transformer layer, implementing the conditional logic from\n# the equation for the feed-forward network.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\n# Assign routing decisions to feed-forward adapter\nmodel.bert.encoder.layer[layer_idx].output.main_adapter.routing_probs.data = routing_decisions\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Capture references to the routing probability tensors for both\n# adapters. While not explicitly mentioned in the LaTeX, these references\n# allow for monitoring the routing decisions and can be used for debugging\n# or analysis purposes.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nattention_routing_probs = model.bert.encoder.layer[layer_idx].attention.output.main_adapter.routing_probs.data\noutput_routing_probs = model.bert.encoder.layer[layer_idx].output.main_adapter.routing_probs.data\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Return the routing probability references. This allows the\n# calling function to access and potentially track the routing decisions\n# that were applied to this layer's adapters.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nreturn attention_routing_probs, output_routing_probs\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - None\n\n - Mismatched Details:\n - The function explicitly applies routing to both attention and feed-forward adapters in the same\n layer, whereas the LaTeX only generally refers to \"PEFT modules\".\n", "Missing_details": [], "Mismatched_details": [ "\n- The function explicitly applies routing to both attention and feed-forward adapters in the same\n layer, whereas the LaTeX only generally refers to \"PEFT modules\".\n" ] }, "Arguments": { "string": "\nInput Variables:\n - model (BertForSequenceClassification):\n The transformer model with parameter-efficient fine-tuning modules to which routing decisions\n will be applied.\n - routing_decisions (torch.Tensor, dtype=torch.float32, shape=[batch_size]):\n Binary tensor where each element corresponds to the routing decision r^(l) in the equation,\n with 1.0 indicating activation of the adapter (for likely clean samples) and 0.0 indicating\n bypassing the adapter (for likely noisy samples).\n - layer_idx (int):\n The index of the transformer layer to which the routing decisions will be applied,\n corresponding to l in the equation.\n", "Arguments_list": [ { "name": "model", "string": "\n- model (BertForSequenceClassification):\n The transformer model with parameter-efficient fine-tuning modules to which routing decisions\n will be applied.\n", "dependency": "BertForSequenceClassification" }, { "name": "routing_decisions", "string": "\n- routing_decisions (torch.Tensor, dtype=torch.float32, shape=[batch_size]):\n Binary tensor where each element corresponds to the routing decision r^(l) in the equation,\n with 1.0 indicating activation of the adapter (for likely clean samples) and 0.0 indicating\n bypassing the adapter (for likely noisy samples).\n", "dependency": null }, { "name": "layer_idx", "string": "\n- layer_idx (int):\n The index of the transformer layer to which the routing decisions will be applied,\n corresponding to l in the equation.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra File Dependencies: \n - None\n\n Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - None\n", "list": [] }, "Return": { "Return_String": "\nOutput Variables:\n - attention_routing_probs (torch.Tensor, shape=[batch_size]):\n Reference to the routing probability tensor assigned to the attention adapter,\n mainly returned for monitoring or debugging purposes.\n - output_routing_probs (torch.Tensor, shape=[batch_size]):\n Reference to the routing probability tensor assigned to the feed-forward output adapter,\n mainly returned for monitoring or debugging purposes.\n", "Return_list": [ { "name": "attention_routing_probs", "string": "\n- attention_routing_probs (torch.Tensor, shape=[batch_size]):\n Reference to the routing probability tensor assigned to the attention adapter,\n mainly returned for monitoring or debugging purposes.\n", "dependency": null }, { "name": "output_routing_probs", "string": "\n- output_routing_probs (torch.Tensor, shape=[batch_size]):\n Reference to the routing probability tensor assigned to the feed-forward output adapter,\n mainly returned for monitoring or debugging purposes.\n", "dependency": null } ] }, "ori_python_file": "import os\nimport copy\nimport time\nimport pickle\nimport datetime\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.manifold import TSNE\n\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom utils import get_num_classes, initialize_networks, get_dataloader\nfrom sklearn.mixture import GaussianMixture\nfrom blocks import AdaMixAdapter\nfrom loss import GeneralizedCrossEntropy\nimport logging\nlogging.getLogger(\"imported_module\").setLevel(logging.WARNING)\n\nfrom torch.cuda.amp import GradScaler \nfrom loss import FocalLoss\n\nclass RoutingAdapterSolver(object):\n\n def __init__(self, args, dataset):\n \"\"\" Initialize configurations. \"\"\"\n self.args = args\n self.dataset = dataset\n self.num_class = get_num_classes(args.dataset)\n\n # Load training networks\n self.model = initialize_networks(dataset=args.dataset, model=args.model, adapter=args.adapter)\n self.pre_model = initialize_networks(dataset=args.dataset, model=args.model, adapter='none')\n \n # Optimizer\n self.criterion = nn.CrossEntropyLoss().cuda()\n self.device = torch.device('cuda')\n\n def testing_plm(self, global_loader, model=None):\n writer = {'loss': 0., 'acc': 0., 'step': 0}\n if model is None:\n model = self.model\n net = model.to(self.device)\n net.eval()\n\n writer['loss'] = 0.\n writer['acc'] = 0.\n writer['step'] = 0.\n\n predictions = []\n labels = []\n with torch.no_grad():\n for batch in global_loader:\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n\n # decision probability updates\n for layeridx in range(model.config.num_hidden_layers):\n mask = (torch.rand(input_ids.size(0)).cuda() < self.args.r_prob).float()\n model.bert.encoder.layer[layeridx].attention.output.main_adapter.routing_probs.data = mask\n model.bert.encoder.layer[layeridx].output.main_adapter.routing_probs.data = mask\n\n outputs = model(input_ids, attention_mask=attention_mask)\n logits = outputs.logits\n # Summary\n writer['acc'] += torch.eq(logits.argmax(dim=-1), labels).float().mean()\n writer['step'] += 1\n\n return float(writer['acc'] / writer['step'])\n\n def JSdivergence(self, output1, output2):\n divergence = (F.kl_div(output1.log_softmax(dim=-1), output2.softmax(dim=-1), reduce=False) + F.kl_div(output2.log_softmax(dim=-1), output1.softmax(dim=-1), reduce=False))/2\n return divergence.mean(dim=-1)\n \n def estimate_clean_probability(self, model, dataloader, prev_losses=None, loss_momentum=0.9, min_prob=0.5):\n sample_indexes = []\n sample_losses = []\n sample_correct_labels = []\n sample_preds = []\n \n model = model.eval()\n with torch.no_grad():\n for batch in dataloader:\n indexes = batch['id'].to(self.device)\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n noisy_labels = batch['noise_label'].to(self.device)\n\n # Get model predictions with stochastic routing\n preds = []\n probs = []\n for _ in range(1):\n # Apply random routing masks\n for layeridx in range(model.config.num_hidden_layers):\n mask = (torch.rand(input_ids.size(0)).cuda() < self.args.r_prob).float()\n model.bert.encoder.layer[layeridx].attention.output.main_adapter.routing_probs.data = mask\n model.bert.encoder.layer[layeridx].output.main_adapter.routing_probs.data = mask\n\n outputs = model(input_ids, attention_mask=attention_mask)\n logits = outputs.logits\n preds.append(logits.unsqueeze(0))\n probs.append(torch.softmax(logits, dim=-1).unsqueeze(0))\n \n preds = torch.cat(preds, dim=0).mean(dim=0)\n probs = torch.cat(probs, dim=0).mean(dim=0)\n\n # Calculate loss\n loss = (-F.one_hot(noisy_labels, self.num_class) * preds.log_softmax(dim=-1)).sum(dim=-1)\n \n # Apply momentum-based loss smoothing if available\n if prev_losses is not None:\n loss = loss * (1 - loss_momentum) + prev_losses.cuda()[indexes].squeeze() * loss_momentum\n \n sample_indexes.append(indexes)\n sample_losses.append(loss)\n sample_correct_labels.append((labels == noisy_labels).float())\n sample_preds.append(preds)\n \n # Aggregate batch results\n sample_preds = torch.cat(sample_preds, dim=0)\n sample_indexes = torch.cat(sample_indexes, dim=0)\n sample_correct_labels = torch.cat(sample_correct_labels, dim=0).cpu()\n sample_losses = torch.cat(sample_losses, dim=0)\n\n # Convert to numpy for GMM\n sample_losses_np = sample_losses.unsqueeze(-1).detach().cpu().numpy()\n\n # Fit GMM and estimate clean probabilities\n gm = GaussianMixture(n_components=2, random_state=0).fit(sample_losses_np)\n clean_component_idx = np.argmin(gm.means_) # Clean samples have smaller loss\n clean_probs = gm.predict_proba(sample_losses_np)[:, clean_component_idx]\n decision = (clean_probs > min_prob).astype(np.float32)\n \n # Convert to torch tensors\n decision_tensor = torch.from_numpy(decision).float()\n clean_probs_tensor = torch.tensor(clean_probs).float().to(self.device)\n \n # Map results back to original indexes\n decision_tensor[sample_indexes] = copy.deepcopy(decision_tensor)\n clean_probs_tensor[sample_indexes] = copy.deepcopy(clean_probs_tensor)\n sample_preds[sample_indexes] = copy.deepcopy(sample_preds)\n\n # Convert losses to tensor for return\n sample_losses_tensor = torch.tensor(sample_losses_np)\n sample_losses_tensor[sample_indexes] = copy.deepcopy(sample_losses_tensor)\n \n return decision_tensor, clean_probs_tensor, sample_preds, sample_losses_tensor\n\n def modeling_loss_pos_neg(self, pos_model, neg_model, epoch, dataloader):\n\n sample_indexes = []\n sample_losses = []\n sample_correct_labels = []\n sample_preds = []\n pos_model = pos_model.eval()\n neg_model = neg_model.eval()\n with torch.no_grad():\n for batch in dataloader:\n indexes = batch['id'].to(self.device)\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n noisy_labels = batch['noise_label'].to(self.device)\n\n\n outputs = pos_model(input_ids, attention_mask=attention_mask)\n pos_logits = outputs.logits\n \n # outputs = neg_model(input_ids, attention_mask=attention_mask)\n # neg_logits = outputs.logits \n \n # kl_div = self.jenson_shannon_divergence(pos_logits, neg_logits)\n \n # Model Updates\n loss = (-F.one_hot(noisy_labels, self.num_class) * pos_logits.log_softmax(dim=-1)).sum(dim=-1)\n sample_indexes.append(indexes)\n sample_losses.append(loss)\n sample_correct_labels.append((labels == noisy_labels).float())\n # sample_preds.append(probs)\n # sample_preds = torch.cat(sample_preds, dim=0)\n sample_indexes = torch.cat(sample_indexes, dim=0)\n sample_correct_labels = torch.cat(sample_correct_labels, dim=0).cpu()\n sample_losses = torch.cat(sample_losses, dim=0)\n sample_losses = sample_losses.unsqueeze(-1).detach().cpu().numpy()\n\n confidence_decision, decision_probs = self.estimate_MM(sample_losses, min_prob=0.5, is_min_clean=True)\n # sample_losses /= sample_losses.max()\n\n self.plot_MM(clean=sample_losses[sample_correct_labels == 1.0],\n noisy=sample_losses[sample_correct_labels == 0.0], title='{}_Confidence_{}'.format(self.args.dataset, epoch))\n print('[{}]: # of clean samples: {} (acc {})'.format('Confidence', confidence_decision.sum(), sample_correct_labels[confidence_decision == 1].mean()))\n confidence_decision[sample_indexes] = copy.deepcopy(confidence_decision)\n decision_probs[sample_indexes] = copy.deepcopy(decision_probs)\n # sample_preds[sample_indexes] = copy.deepcopy(sample_preds)\n return confidence_decision.float()#, sample_preds\n\n def apply_routing_decisions_to_adapters(self, model, routing_decisions, layer_idx):\n # Assign routing decisions to self-attention adapter\n model.bert.encoder.layer[layer_idx].attention.output.main_adapter.routing_probs.data = routing_decisions\n \n # Assign routing decisions to feed-forward adapter\n model.bert.encoder.layer[layer_idx].output.main_adapter.routing_probs.data = routing_decisions\n attention_routing_probs = model.bert.encoder.layer[layer_idx].attention.output.main_adapter.routing_probs.data\n output_routing_probs = model.bert.encoder.layer[layer_idx].output.main_adapter.routing_probs.data\n return attention_routing_probs, output_routing_probs\n\n def apply_stochastic_routing(self, model, input_ids, clean_probs=None, indexes=None, gamma=None, warm_up_period=False):\n batch_size = input_ids.size(0)\n batch_probs_output = list()\n # Determine routing probability\n if warm_up_period or clean_probs is None:\n # During warm-up, use a fixed probability for all samples\n routing_prob = gamma\n # Sample batch-specific masks once for each layer\n for layer_idx in range(model.config.num_hidden_layers):\n mask = (torch.rand(batch_size).cuda() < routing_prob).float()\n model.bert.encoder.layer[layer_idx].attention.output.main_adapter.routing_probs.data = mask\n model.bert.encoder.layer[layer_idx].output.main_adapter.routing_probs.data = mask\n else:\n # After warm-up, use the estimated clean probability scaled by gamma\n batch_probs = clean_probs[indexes].cuda() * gamma\n batch_probs_output.append(batch_probs)\n # Sample independent masks for each layer (as per the paper)\n for layer_idx in range(model.config.num_hidden_layers):\n # Sample from Bernoulli distribution: r ~ Bernoulli(\u03b3p)\n routing_decisions = (torch.rand(batch_size).cuda() < batch_probs).float()\n # Apply routing decisions to adapters\n attention_routing_probs, output_routing_probs = self.apply_routing_decisions_to_adapters(model, routing_decisions, layer_idx)\n return batch_probs_output\n\n def modeling_robustness(self, model, epoch, dataloader):\n sample_indexes = []\n sample_losses = []\n sample_correct_labels = []\n sample_preds = []\n model = model.eval()\n with torch.no_grad():\n for batch in dataloader:\n indexes = batch['id'].to(self.device)\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n noisy_labels = batch['noise_label'].to(self.device)\n\n outputs = model(input_ids, attention_mask=attention_mask)\n pos_logits = outputs.logits\n\n # Model Updates\n sample_indexes.append(indexes)\n sample_correct_labels.append((labels == noisy_labels).float())\n sample_preds.append(pos_logits)\n \n # sample_preds = torch.cat(sample_preds, dim=0)\n sample_indexes = torch.cat(sample_indexes, dim=0)\n sample_preds = torch.cat(sample_preds, dim=0)#.cpu()\n sample_correct_labels = torch.cat(sample_correct_labels, dim=0).cpu()\n # confidence_decision, decision_probs = self.estimate_MM(sample_losses, min_prob=0.5, is_min_clean=True)\n \n # K-NN\n norm_sample_preds = sample_preds / (torch.norm(sample_preds, dim=-1, keepdim=True) + 1e-8)\n knn_map = norm_sample_preds @ norm_sample_preds.transpose(0, 1)\n knn_values, knn_indices = torch.topk(knn_map, k=30)\n print(knn_values.size(), knn_indices.size()) # NER \ub4f1\uc758 Task\uc5d0 \ubd88\ub9ac\ud568 (Batch, Top-K)\n\n exit()\n\n\n self.plot_MM(clean=sample_losses[sample_correct_labels == 1.0],\n noisy=sample_losses[sample_correct_labels == 0.0], title='{}_Confidence_{}'.format(self.args.dataset, epoch))\n print('[{}]: # of clean samples: {} (acc {})'.format('Confidence', confidence_decision.sum(), sample_correct_labels[confidence_decision == 1].mean()))\n confidence_decision[sample_indexes] = copy.deepcopy(confidence_decision)\n decision_probs[sample_indexes] = copy.deepcopy(decision_probs)\n # sample_preds[sample_indexes] = copy.deepcopy(sample_preds)\n return confidence_decision.float()#, sample_preds\n\n def estimate_MM(self, data, min_prob, is_min_clean=True):\n gm = GaussianMixture(n_components=2, random_state=0).fit(data)\n if is_min_clean:\n clean_label_index = np.argmin(gm.means_)\n else:\n clean_label_index = np.argmax(gm.means_)\n\n probs = gm.predict_proba(data)[:, clean_label_index]\n decision = (probs > min_prob)\n decision = torch.from_numpy(decision).float()\n return decision, torch.tensor(probs).float().to(self.device)\n\n def plot_MM(self, clean, noisy, title):\n import matplotlib.pyplot as plt\n import matplotlib.ticker as mticker\n\n fig = plt.figure(figsize=(9, 3))\n\n plt.style.use('ggplot')\n plt.rcParams['axes.facecolor']='#EAEAF1'\n COLOR = 'black'\n plt.rcParams['text.color'] = COLOR\n plt.rcParams['axes.labelcolor'] = COLOR\n plt.rcParams['xtick.color'] = COLOR\n plt.rcParams['ytick.color'] = COLOR\n plt.rcParams.update({'font.size': 14})\n\n plt.hist(clean, bins=50, density=True, color='blue', alpha=0.65, label='True identification')\n plt.hist(noisy, bins=50, density=True, color='red', alpha=0.65, label='False identification')\n plt.legend()\n plt.xlabel('Predictive Confidence')\n plt.ylabel('Empirical PDF')\n plt.grid(True)\n plt.savefig('./plot/{}.pdf'.format(title.split('/')[-1]), bbox_inches='tight')\n plt.close()\n\n def jenson_shannon_divergence(self, net_1_logits, net_2_logits):\n from torch.functional import F\n net_1_probs = F.softmax(net_1_logits, dim=0)\n net_2_probs = F.softmax(net_2_logits, dim=0)\n \n total_m = 0.5 * (net_1_probs + net_1_probs)\n \n loss = 0.0\n loss += F.kl_div(F.log_softmax(net_1_logits, dim=0), total_m, reduce=False).sum(dim=-1)\n loss += F.kl_div(F.log_softmax(net_2_logits, dim=0), total_m, reduce=False).sum(dim=-1)\n return (0.5 * loss)\n\n def apply_consistency_regularization(self, logits, noisy_labels, ensemble_preds=None, indexes=None, temperature=0.5):\n # Standard cross-entropy loss with noisy labels\n ce_loss = (-F.one_hot(noisy_labels, self.num_class) * logits.log_softmax(dim=-1)).sum(dim=-1)\n \n # Get \"teacher\" predictions from previous ensemble\n teacher_preds = (ensemble_preds[indexes] / temperature).softmax(dim=-1)\n \n # Knowledge distillation loss (student-teacher)\n distillation_loss = (-teacher_preds.detach() * (logits / temperature).log_softmax(dim=-1)).sum(dim=-1)\n \n # Combine losses (implicitly using \u03bb=1 as scaling factor)\n combined_loss = ce_loss.mean() + distillation_loss.mean()\n return combined_loss\n\n def run(self):\n \n \"\"\" Start federated learning scenario \"\"\"\n # Load global validation set\n pos_train_loader, test_loader, _ = get_dataloader(dataset=self.dataset, train_bs=self.args.batch_size, test_bs=self.args.batch_size)\n\n # self.model = self.load_model('sst5_2_0.4281249940395355')\n\n optimizer = torch.optim.AdamW(self.model.parameters(), lr=self.args.lr) \n criterion = nn.CrossEntropyLoss(reduce=False)\n focal_criterion = FocalLoss(alpha=2.0)\n gce = GeneralizedCrossEntropy(self.num_class)\n \n scaler = GradScaler()\n def update_ema_variables(model, ema_model, alpha):\n # Use the true average until the exponential average is more correct\n for ema_param, param in zip(ema_model.parameters(), model.parameters()):\n ema_param.data.mul_(alpha).add_(1 - alpha, param.data)\n \n self.model_hist = []\n self.acc_hist = []\n\n # print(peft_modules)\n # exit()\n self.model = self.model.to(self.device)\n self.pre_model = self.pre_model.to(self.device)\n self.prev_ensemble_preds = None\n self.prev_sample_losses = None\n\n # self.model = copy.deepcopy()\n training_history = {'cka': [], 'test_acc': [], 'clean_acc': [], 'noise_acc': []}\n for epoch in range(self.args.epochs):\n writer = {'loss': 0., 'acc': 0., 'step': 0, 'cka': 0, 'clean_acc': 0, 'nclean': 0, 'noise_acc': 0, 'nnoise': 0}\n self.model.train()\n\n if epoch >= self.args.warm_up:\n decision, decision_probs, ensemble_preds, sample_losses = self.estimate_clean_probability(\n self.model, \n pos_train_loader, \n self.prev_sample_losses\n )\n self.prev_sample_losses = sample_losses\n\n for name, param in self.model.named_parameters():\n if 'main' in name:#or 'pool' in name: \n param.requires_grad = True\n else:\n param.requires_grad = False\n\n for batch in tqdm(pos_train_loader):\n\n indexes = batch['id'].to(self.device)\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n noisy_labels = batch['noise_label'].to(self.device)\n\n # decision probability updates\n batch_probs_output = self.apply_stochastic_routing(\n model=self.model,\n input_ids=input_ids,\n clean_probs=decision_probs if epoch >= self.args.warm_up else None,\n indexes=indexes,\n gamma=self.args.r_prob,\n warm_up_period=(epoch < self.args.warm_up)\n )\n\n outputs = self.model(input_ids, attention_mask=attention_mask, output_hidden_states=False)\n logits = outputs.logits\n\n # Model Updates\n optimizer.zero_grad()\n if epoch >= self.args.warm_up:\n loss = self.apply_consistency_regularization(\n logits=logits,\n noisy_labels=noisy_labels,\n ensemble_preds=ensemble_preds if epoch >= self.args.warm_up else None,\n indexes=indexes if epoch >= self.args.warm_up else None,\n temperature=0.5\n )\n\n else:\n loss = (-F.one_hot(noisy_labels, self.num_class) * logits.log_softmax(dim=-1)).sum(dim=-1)\n loss = loss.mean()\n loss.backward(retain_graph=True)\n optimizer.step()\n\n writer['loss'] += loss.mean().item()\n # writer['cka'] += ((fixed_hidden_state - hidden_state) ** 2).mean() # L2 distance\n writer['acc'] += torch.eq(logits.argmax(dim=-1), labels).float().sum()\n \n writer['clean_acc'] += torch.eq(logits[noisy_labels == labels].argmax(dim=-1), labels[noisy_labels == labels]).float().sum()\n writer['nclean'] += (noisy_labels == labels).float().sum()\n \n writer['noise_acc'] += torch.eq(logits[noisy_labels != labels].argmax(dim=-1), noisy_labels[noisy_labels != labels]).float().sum()\n writer['nnoise'] += (noisy_labels != labels).float().sum()\n \n writer['step'] += len(logits)\n\n # Evaluate the global model\n cka = writer['cka'] / writer['step']\n clean_acc = writer['clean_acc'] / writer['nclean']\n noise_acc = writer['noise_acc'] / writer['nnoise']\n test_acc = self.testing_plm(global_loader=test_loader)\n\n training_history['cka'].append(float(cka))\n training_history['clean_acc'].append(float(clean_acc))\n training_history['noise_acc'].append(float(noise_acc))\n training_history['test_acc'].append(float(test_acc))\n\n print('Epoch ({}) Test accuracy {}, avg loss {}, cka {}'.format(epoch, test_acc, writer['loss']/writer['step'], writer['cka'] / writer['step']))\n \n for key in training_history:\n print(f'{key}=', training_history[key])\n\n def load_model(self, file_name):\n model = pickle.load(open(os.path.join(self.args.modeldir, f'{file_name}.pkl'), 'rb'))\n return model\n\n def save_model(self, model, file_name):\n pickle.dump(model, open(os.path.join(self.args.modeldir, f'{file_name}.pkl'), 'wb'))\n" }, { "task_id": 3, "indent": 2, "completion_path": "./solvers/routing_adapter_solver.py", "script": "\npython main.py --dataset SetFit/sst5 --model bert-base-uncased --alg routing_adapter --device 0 --adapter routing_adapter --batch_size 32 --epochs 8\n", "latex_code": "\"\n\\subsection{Consistency Regularization for CleaR}\\label{subsect:cr}\n\nWhile the routing scheme effectively mitigates the influence of noisy labels, model predictions may end up being overly diverse due to varying activations with each forward pass, potentially resulting in training instability.\nTo address this issue, we introduce a consistency regularization to minimize the model variability. Considering that guiding the model to adhere to past predictions can enhance the stability and consistency of training \\cite{consistency_cvpr, consistency_bert}, we regulate the model by minimizing the distance between its current and previous predictions. Specifically, we make ensemble predictions from multiple forwards to reduce predictive variance and increase stability:\n\\begin{equation}\n f_{\\text{ens}}(x, \\bar{\\boldsymbol{\\delta}}_{r} + \\theta) = \\frac{1}{N} \\sum_{k=1}^{N} f(x, \\bar{\\boldsymbol{\\delta}}_{r,k} + \\boldsymbol{\\theta}),\n\\end{equation}\nwhere $N$ is the number of forwards, and $\\bar{\\boldsymbol{\\delta}}_{r,k}$ represents activated PEFT modules in the $k$-th forward of the previously trained model. It is noteworthy that, for computational efficiency, we reuse the predictions, which were previously used for fitting GMM. With the derived predictions, the model with CleaR is optimized with the following loss:\n\\begin{multline}\n \\underset{{\\delta_r}}{\\text{min}} \\; \\mathcal{L}(x) = \\mathcal{L}_{\\text{CE}}( f(x, \\boldsymbol{\\delta}_r + \\boldsymbol{\\theta}), y) \\\\ + \\lambda \\mathcal{L}_{\\text{CE}}(f(x, \\boldsymbol{\\delta}_r + \\boldsymbol{\\theta}), f_{\\text{ens}}(x, \\bar{\\boldsymbol{\\delta}}_r + \\boldsymbol{\\theta})).\n\\end{multline}\nwhere $\\mathcal{L}_{\\text{CE}}(\\cdot)$ indicates the cross-entropy loss, and $\\lambda$ is a coefficient to control the strength of the regularization.\n", "namespace": "solvers.routing_adapter_solver.RoutingAdapterSolver.apply_consistency_regularization", "type": "method", "signature_position": [ 331, 331 ], "body_position": [ 332, 343 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Compute the standard cross-entropy loss with noisy labels.\n# This implements the first term of the combined loss equation in the LaTeX:\n# L_CE(f(x, \u03b4_r + \u03b8), y)\n# where f(x, \u03b4_r + \u03b8) corresponds to the model's logits, and y to noisy_labels.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\n# Standard cross-entropy loss with noisy labels\nce_loss = (-F.one_hot(noisy_labels, self.num_class) * logits.log_softmax(dim=-1)).sum(dim=-1)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Prepare the \"teacher\" predictions from the ensemble predictions.\n# This implements the concept of using ensemble predictions as a target:\n# f_ens(x, \u03b4\u0304_r + \u03b8) in the LaTeX equation.\n# The temperature scaling sharpens or softens the probability distribution.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\n# Get \"teacher\" predictions from previous ensemble\nteacher_preds = (ensemble_preds[indexes] / temperature).softmax(dim=-1)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Compute the knowledge distillation (consistency) loss.\n# This implements the second term of the combined loss equation in the LaTeX:\n# L_CE(f(x, \u03b4_r + \u03b8), f_ens(x, \u03b4\u0304_r + \u03b8))\n# where detach() prevents gradients from flowing back through the teacher model.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\n# Knowledge distillation loss (student-teacher)\ndistillation_loss = (-teacher_preds.detach() * (logits / temperature).log_softmax(dim=-1)).sum(dim=-1)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Combine both losses with implicit \u03bb=1 as scaling factor.\n# This implements the complete loss function from the LaTeX:\n# L(x) = L_CE(f(x, \u03b4_r + \u03b8), y) + \u03bb * L_CE(f(x, \u03b4_r + \u03b8), f_ens(x, \u03b4\u0304_r + \u03b8))\n# but with \u03bb fixed at 1, and returning the batch average.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\n# Combine losses (implicitly using \u03bb=1 as scaling factor)\ncombined_loss = ce_loss.mean() + distillation_loss.mean()\nreturn combined_loss\n# [End Snippet 4]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - Temperature scaling (0.5) is used in the implementation.\n - Detaching teacher predictions to prevent gradient flow through them is not specified in the LaTeX.\n \n - Mismatched Details:\n - The \u03bb coefficient from the LaTeX equation is implicitly set to 1 in the code, without allowing for adjustment.\n - The LaTeX specifies a variable number of forwards N for ensemble predictions, but this function assumes ensemble predictions have already been computed and averaged externally.\n", "Missing_details": [ "\n- Temperature scaling (0.5) is used in the implementation.\n", "\n- Detaching teacher predictions to prevent gradient flow through them is not specified in the LaTeX.\n" ], "Mismatched_details": [ "\n- The \u03bb coefficient from the LaTeX equation is implicitly set to 1 in the code, without allowing for adjustment.\n", "\n- The LaTeX specifies a variable number of forwards N for ensemble predictions, but this function assumes ensemble predictions have already been computed and averaged externally.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - logits (torch.Tensor, dtype=torch.float32, shape=[batch_size, num_classes]):\n Current model predictions f(x, \u03b4_r + \u03b8) before softmax, corresponding to the output logits\n from the model's forward pass with current routing decisions and parameters.\n - noisy_labels (torch.Tensor, dtype=torch.long, shape=[batch_size]):\n Potentially noisy labels (y) for the standard cross-entropy component of the loss.\n - ensemble_preds (torch.Tensor, optional, dtype=torch.float32, shape=[dataset_size, num_classes]):\n Ensemble predictions f_ens(x, \u03b4\u0304_r + \u03b8) from previous model iterations, stored for all training\n samples. These serve as \"teacher\" signals to stabilize current predictions.\n - indexes (torch.Tensor, optional, dtype=torch.long, shape=[batch_size]):\n Indices to retrieve the corresponding ensemble predictions for current batch samples.\n - temperature (float, optional, default=0.5):\n Temperature parameter for softmax scaling, controlling the sharpness of probability distributions\n when computing knowledge distillation loss.\"\n\n The function also uses the following class attributes:\n - self.num_class (int): The number of classes in the dataset.\n", "Arguments_list": [ { "name": "logits", "string": "\n- logits (torch.Tensor, dtype=torch.float32, shape=[batch_size, num_classes]):\n Current model predictions f(x, \u03b4_r + \u03b8) before softmax, corresponding to the output logits\n from the model's forward pass with current routing decisions and parameters.\n", "dependency": null }, { "name": "noisy_labels", "string": "\n- noisy_labels (torch.Tensor, dtype=torch.long, shape=[batch_size]):\n Potentially noisy labels (y) for the standard cross-entropy component of the loss.\n", "dependency": null }, { "name": "ensemble_preds", "string": "\n- ensemble_preds (torch.Tensor, optional, dtype=torch.float32, shape=[dataset_size, num_classes]):\n", "dependency": null }, { "name": "indexes", "string": "\n- indexes (torch.Tensor, optional, dtype=torch.long, shape=[batch_size]):\n Indices to retrieve the corresponding ensemble predictions for current batch samples.\"\n", "dependency": null }, { "name": "temperature", "string": "\n- temperature (float, optional, default=0.5):\n Temperature parameter for softmax scaling, controlling the sharpness of probability distributions\n when computing knowledge distillation loss.\n", "dependency": null }, { "name": "self.num_class", "string": "\n- self.num_class (int): The number of classes in the dataset.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-file Dependencies:\n - None\n \n - Cross-file Dependencies:\n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.functional.one_hot\n", "list": [ "torch.functional.one_hot" ] }, "Return": { "Return_String": "\nOutput Variables:\n - combined_loss (torch.Tensor, dtype=torch.float32, shape=[]):\n Combined loss including both standard cross-entropy with noisy labels and consistency regularization\n term, averaged across the batch.\n", "Return_list": [ { "name": "combined_loss", "string": "\n- combined_loss (torch.Tensor, dtype=torch.float32, shape=[]):\n Combined loss including both standard cross-entropy with noisy labels and consistency regularization\n term, averaged across the batch.\n", "dependency": null } ] }, "ori_python_file": "import os\nimport copy\nimport time\nimport pickle\nimport datetime\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.manifold import TSNE\n\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom utils import get_num_classes, initialize_networks, get_dataloader\nfrom sklearn.mixture import GaussianMixture\nfrom blocks import AdaMixAdapter\nfrom loss import GeneralizedCrossEntropy\nimport logging\nlogging.getLogger(\"imported_module\").setLevel(logging.WARNING)\n\nfrom torch.cuda.amp import GradScaler \nfrom loss import FocalLoss\n\nclass RoutingAdapterSolver(object):\n\n def __init__(self, args, dataset):\n \"\"\" Initialize configurations. \"\"\"\n self.args = args\n self.dataset = dataset\n self.num_class = get_num_classes(args.dataset)\n\n # Load training networks\n self.model = initialize_networks(dataset=args.dataset, model=args.model, adapter=args.adapter)\n self.pre_model = initialize_networks(dataset=args.dataset, model=args.model, adapter='none')\n \n # Optimizer\n self.criterion = nn.CrossEntropyLoss().cuda()\n self.device = torch.device('cuda')\n\n def testing_plm(self, global_loader, model=None):\n writer = {'loss': 0., 'acc': 0., 'step': 0}\n if model is None:\n model = self.model\n net = model.to(self.device)\n net.eval()\n\n writer['loss'] = 0.\n writer['acc'] = 0.\n writer['step'] = 0.\n\n predictions = []\n labels = []\n with torch.no_grad():\n for batch in global_loader:\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n\n # decision probability updates\n for layeridx in range(model.config.num_hidden_layers):\n mask = (torch.rand(input_ids.size(0)).cuda() < self.args.r_prob).float()\n model.bert.encoder.layer[layeridx].attention.output.main_adapter.routing_probs.data = mask\n model.bert.encoder.layer[layeridx].output.main_adapter.routing_probs.data = mask\n\n outputs = model(input_ids, attention_mask=attention_mask)\n logits = outputs.logits\n # Summary\n writer['acc'] += torch.eq(logits.argmax(dim=-1), labels).float().mean()\n writer['step'] += 1\n\n return float(writer['acc'] / writer['step'])\n\n def JSdivergence(self, output1, output2):\n divergence = (F.kl_div(output1.log_softmax(dim=-1), output2.softmax(dim=-1), reduce=False) + F.kl_div(output2.log_softmax(dim=-1), output1.softmax(dim=-1), reduce=False))/2\n return divergence.mean(dim=-1)\n \n def estimate_clean_probability(self, model, dataloader, prev_losses=None, loss_momentum=0.9, min_prob=0.5):\n sample_indexes = []\n sample_losses = []\n sample_correct_labels = []\n sample_preds = []\n \n model = model.eval()\n with torch.no_grad():\n for batch in dataloader:\n indexes = batch['id'].to(self.device)\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n noisy_labels = batch['noise_label'].to(self.device)\n\n # Get model predictions with stochastic routing\n preds = []\n probs = []\n for _ in range(1):\n # Apply random routing masks\n for layeridx in range(model.config.num_hidden_layers):\n mask = (torch.rand(input_ids.size(0)).cuda() < self.args.r_prob).float()\n model.bert.encoder.layer[layeridx].attention.output.main_adapter.routing_probs.data = mask\n model.bert.encoder.layer[layeridx].output.main_adapter.routing_probs.data = mask\n\n outputs = model(input_ids, attention_mask=attention_mask)\n logits = outputs.logits\n preds.append(logits.unsqueeze(0))\n probs.append(torch.softmax(logits, dim=-1).unsqueeze(0))\n \n preds = torch.cat(preds, dim=0).mean(dim=0)\n probs = torch.cat(probs, dim=0).mean(dim=0)\n\n # Calculate loss\n loss = (-F.one_hot(noisy_labels, self.num_class) * preds.log_softmax(dim=-1)).sum(dim=-1)\n \n # Apply momentum-based loss smoothing if available\n if prev_losses is not None:\n loss = loss * (1 - loss_momentum) + prev_losses.cuda()[indexes].squeeze() * loss_momentum\n \n sample_indexes.append(indexes)\n sample_losses.append(loss)\n sample_correct_labels.append((labels == noisy_labels).float())\n sample_preds.append(preds)\n \n # Aggregate batch results\n sample_preds = torch.cat(sample_preds, dim=0)\n sample_indexes = torch.cat(sample_indexes, dim=0)\n sample_correct_labels = torch.cat(sample_correct_labels, dim=0).cpu()\n sample_losses = torch.cat(sample_losses, dim=0)\n\n # Convert to numpy for GMM\n sample_losses_np = sample_losses.unsqueeze(-1).detach().cpu().numpy()\n\n # Fit GMM and estimate clean probabilities\n gm = GaussianMixture(n_components=2, random_state=0).fit(sample_losses_np)\n clean_component_idx = np.argmin(gm.means_) # Clean samples have smaller loss\n clean_probs = gm.predict_proba(sample_losses_np)[:, clean_component_idx]\n decision = (clean_probs > min_prob).astype(np.float32)\n \n # Convert to torch tensors\n decision_tensor = torch.from_numpy(decision).float()\n clean_probs_tensor = torch.tensor(clean_probs).float().to(self.device)\n \n # Map results back to original indexes\n decision_tensor[sample_indexes] = copy.deepcopy(decision_tensor)\n clean_probs_tensor[sample_indexes] = copy.deepcopy(clean_probs_tensor)\n sample_preds[sample_indexes] = copy.deepcopy(sample_preds)\n\n # Convert losses to tensor for return\n sample_losses_tensor = torch.tensor(sample_losses_np)\n sample_losses_tensor[sample_indexes] = copy.deepcopy(sample_losses_tensor)\n \n return decision_tensor, clean_probs_tensor, sample_preds, sample_losses_tensor\n\n def modeling_loss_pos_neg(self, pos_model, neg_model, epoch, dataloader):\n\n sample_indexes = []\n sample_losses = []\n sample_correct_labels = []\n sample_preds = []\n pos_model = pos_model.eval()\n neg_model = neg_model.eval()\n with torch.no_grad():\n for batch in dataloader:\n indexes = batch['id'].to(self.device)\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n noisy_labels = batch['noise_label'].to(self.device)\n\n\n outputs = pos_model(input_ids, attention_mask=attention_mask)\n pos_logits = outputs.logits\n \n # outputs = neg_model(input_ids, attention_mask=attention_mask)\n # neg_logits = outputs.logits \n \n # kl_div = self.jenson_shannon_divergence(pos_logits, neg_logits)\n \n # Model Updates\n loss = (-F.one_hot(noisy_labels, self.num_class) * pos_logits.log_softmax(dim=-1)).sum(dim=-1)\n sample_indexes.append(indexes)\n sample_losses.append(loss)\n sample_correct_labels.append((labels == noisy_labels).float())\n # sample_preds.append(probs)\n # sample_preds = torch.cat(sample_preds, dim=0)\n sample_indexes = torch.cat(sample_indexes, dim=0)\n sample_correct_labels = torch.cat(sample_correct_labels, dim=0).cpu()\n sample_losses = torch.cat(sample_losses, dim=0)\n sample_losses = sample_losses.unsqueeze(-1).detach().cpu().numpy()\n\n confidence_decision, decision_probs = self.estimate_MM(sample_losses, min_prob=0.5, is_min_clean=True)\n # sample_losses /= sample_losses.max()\n\n self.plot_MM(clean=sample_losses[sample_correct_labels == 1.0],\n noisy=sample_losses[sample_correct_labels == 0.0], title='{}_Confidence_{}'.format(self.args.dataset, epoch))\n print('[{}]: # of clean samples: {} (acc {})'.format('Confidence', confidence_decision.sum(), sample_correct_labels[confidence_decision == 1].mean()))\n confidence_decision[sample_indexes] = copy.deepcopy(confidence_decision)\n decision_probs[sample_indexes] = copy.deepcopy(decision_probs)\n # sample_preds[sample_indexes] = copy.deepcopy(sample_preds)\n return confidence_decision.float()#, sample_preds\n\n def apply_routing_decisions_to_adapters(self, model, routing_decisions, layer_idx):\n # Assign routing decisions to self-attention adapter\n model.bert.encoder.layer[layer_idx].attention.output.main_adapter.routing_probs.data = routing_decisions\n \n # Assign routing decisions to feed-forward adapter\n model.bert.encoder.layer[layer_idx].output.main_adapter.routing_probs.data = routing_decisions\n attention_routing_probs = model.bert.encoder.layer[layer_idx].attention.output.main_adapter.routing_probs.data\n output_routing_probs = model.bert.encoder.layer[layer_idx].output.main_adapter.routing_probs.data\n return attention_routing_probs, output_routing_probs\n\n def apply_stochastic_routing(self, model, input_ids, clean_probs=None, indexes=None, gamma=None, warm_up_period=False):\n batch_size = input_ids.size(0)\n batch_probs_output = list()\n # Determine routing probability\n if warm_up_period or clean_probs is None:\n # During warm-up, use a fixed probability for all samples\n routing_prob = gamma\n # Sample batch-specific masks once for each layer\n for layer_idx in range(model.config.num_hidden_layers):\n mask = (torch.rand(batch_size).cuda() < routing_prob).float()\n model.bert.encoder.layer[layer_idx].attention.output.main_adapter.routing_probs.data = mask\n model.bert.encoder.layer[layer_idx].output.main_adapter.routing_probs.data = mask\n else:\n # After warm-up, use the estimated clean probability scaled by gamma\n batch_probs = clean_probs[indexes].cuda() * gamma\n batch_probs_output.append(batch_probs)\n # Sample independent masks for each layer (as per the paper)\n for layer_idx in range(model.config.num_hidden_layers):\n # Sample from Bernoulli distribution: r ~ Bernoulli(\u03b3p)\n routing_decisions = (torch.rand(batch_size).cuda() < batch_probs).float()\n # Apply routing decisions to adapters\n attention_routing_probs, output_routing_probs = self.apply_routing_decisions_to_adapters(model, routing_decisions, layer_idx)\n return batch_probs_output\n\n def modeling_robustness(self, model, epoch, dataloader):\n sample_indexes = []\n sample_losses = []\n sample_correct_labels = []\n sample_preds = []\n model = model.eval()\n with torch.no_grad():\n for batch in dataloader:\n indexes = batch['id'].to(self.device)\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n noisy_labels = batch['noise_label'].to(self.device)\n\n outputs = model(input_ids, attention_mask=attention_mask)\n pos_logits = outputs.logits\n\n # Model Updates\n sample_indexes.append(indexes)\n sample_correct_labels.append((labels == noisy_labels).float())\n sample_preds.append(pos_logits)\n \n # sample_preds = torch.cat(sample_preds, dim=0)\n sample_indexes = torch.cat(sample_indexes, dim=0)\n sample_preds = torch.cat(sample_preds, dim=0)#.cpu()\n sample_correct_labels = torch.cat(sample_correct_labels, dim=0).cpu()\n # confidence_decision, decision_probs = self.estimate_MM(sample_losses, min_prob=0.5, is_min_clean=True)\n \n # K-NN\n norm_sample_preds = sample_preds / (torch.norm(sample_preds, dim=-1, keepdim=True) + 1e-8)\n knn_map = norm_sample_preds @ norm_sample_preds.transpose(0, 1)\n knn_values, knn_indices = torch.topk(knn_map, k=30)\n print(knn_values.size(), knn_indices.size()) # NER \ub4f1\uc758 Task\uc5d0 \ubd88\ub9ac\ud568 (Batch, Top-K)\n\n exit()\n\n\n self.plot_MM(clean=sample_losses[sample_correct_labels == 1.0],\n noisy=sample_losses[sample_correct_labels == 0.0], title='{}_Confidence_{}'.format(self.args.dataset, epoch))\n print('[{}]: # of clean samples: {} (acc {})'.format('Confidence', confidence_decision.sum(), sample_correct_labels[confidence_decision == 1].mean()))\n confidence_decision[sample_indexes] = copy.deepcopy(confidence_decision)\n decision_probs[sample_indexes] = copy.deepcopy(decision_probs)\n # sample_preds[sample_indexes] = copy.deepcopy(sample_preds)\n return confidence_decision.float()#, sample_preds\n\n def estimate_MM(self, data, min_prob, is_min_clean=True):\n gm = GaussianMixture(n_components=2, random_state=0).fit(data)\n if is_min_clean:\n clean_label_index = np.argmin(gm.means_)\n else:\n clean_label_index = np.argmax(gm.means_)\n\n probs = gm.predict_proba(data)[:, clean_label_index]\n decision = (probs > min_prob)\n decision = torch.from_numpy(decision).float()\n return decision, torch.tensor(probs).float().to(self.device)\n\n def plot_MM(self, clean, noisy, title):\n import matplotlib.pyplot as plt\n import matplotlib.ticker as mticker\n\n fig = plt.figure(figsize=(9, 3))\n\n plt.style.use('ggplot')\n plt.rcParams['axes.facecolor']='#EAEAF1'\n COLOR = 'black'\n plt.rcParams['text.color'] = COLOR\n plt.rcParams['axes.labelcolor'] = COLOR\n plt.rcParams['xtick.color'] = COLOR\n plt.rcParams['ytick.color'] = COLOR\n plt.rcParams.update({'font.size': 14})\n\n plt.hist(clean, bins=50, density=True, color='blue', alpha=0.65, label='True identification')\n plt.hist(noisy, bins=50, density=True, color='red', alpha=0.65, label='False identification')\n plt.legend()\n plt.xlabel('Predictive Confidence')\n plt.ylabel('Empirical PDF')\n plt.grid(True)\n plt.savefig('./plot/{}.pdf'.format(title.split('/')[-1]), bbox_inches='tight')\n plt.close()\n\n def jenson_shannon_divergence(self, net_1_logits, net_2_logits):\n from torch.functional import F\n net_1_probs = F.softmax(net_1_logits, dim=0)\n net_2_probs = F.softmax(net_2_logits, dim=0)\n \n total_m = 0.5 * (net_1_probs + net_1_probs)\n \n loss = 0.0\n loss += F.kl_div(F.log_softmax(net_1_logits, dim=0), total_m, reduce=False).sum(dim=-1)\n loss += F.kl_div(F.log_softmax(net_2_logits, dim=0), total_m, reduce=False).sum(dim=-1)\n return (0.5 * loss)\n\n def apply_consistency_regularization(self, logits, noisy_labels, ensemble_preds=None, indexes=None, temperature=0.5):\n # Standard cross-entropy loss with noisy labels\n ce_loss = (-F.one_hot(noisy_labels, self.num_class) * logits.log_softmax(dim=-1)).sum(dim=-1)\n \n # Get \"teacher\" predictions from previous ensemble\n teacher_preds = (ensemble_preds[indexes] / temperature).softmax(dim=-1)\n \n # Knowledge distillation loss (student-teacher)\n distillation_loss = (-teacher_preds.detach() * (logits / temperature).log_softmax(dim=-1)).sum(dim=-1)\n \n # Combine losses (implicitly using \u03bb=1 as scaling factor)\n combined_loss = ce_loss.mean() + distillation_loss.mean()\n return combined_loss\n\n def run(self):\n \n \"\"\" Start federated learning scenario \"\"\"\n # Load global validation set\n pos_train_loader, test_loader, _ = get_dataloader(dataset=self.dataset, train_bs=self.args.batch_size, test_bs=self.args.batch_size)\n\n # self.model = self.load_model('sst5_2_0.4281249940395355')\n\n optimizer = torch.optim.AdamW(self.model.parameters(), lr=self.args.lr) \n criterion = nn.CrossEntropyLoss(reduce=False)\n focal_criterion = FocalLoss(alpha=2.0)\n gce = GeneralizedCrossEntropy(self.num_class)\n \n scaler = GradScaler()\n def update_ema_variables(model, ema_model, alpha):\n # Use the true average until the exponential average is more correct\n for ema_param, param in zip(ema_model.parameters(), model.parameters()):\n ema_param.data.mul_(alpha).add_(1 - alpha, param.data)\n \n self.model_hist = []\n self.acc_hist = []\n\n # print(peft_modules)\n # exit()\n self.model = self.model.to(self.device)\n self.pre_model = self.pre_model.to(self.device)\n self.prev_ensemble_preds = None\n self.prev_sample_losses = None\n\n # self.model = copy.deepcopy()\n training_history = {'cka': [], 'test_acc': [], 'clean_acc': [], 'noise_acc': []}\n for epoch in range(self.args.epochs):\n writer = {'loss': 0., 'acc': 0., 'step': 0, 'cka': 0, 'clean_acc': 0, 'nclean': 0, 'noise_acc': 0, 'nnoise': 0}\n self.model.train()\n\n if epoch >= self.args.warm_up:\n decision, decision_probs, ensemble_preds, sample_losses = self.estimate_clean_probability(\n self.model, \n pos_train_loader, \n self.prev_sample_losses\n )\n self.prev_sample_losses = sample_losses\n\n for name, param in self.model.named_parameters():\n if 'main' in name:#or 'pool' in name: \n param.requires_grad = True\n else:\n param.requires_grad = False\n\n for batch in tqdm(pos_train_loader):\n\n indexes = batch['id'].to(self.device)\n input_ids = batch['input_ids'].to(self.device)\n attention_mask = batch['attention_mask'].to(self.device)\n labels = batch['label'].to(self.device)\n noisy_labels = batch['noise_label'].to(self.device)\n\n # decision probability updates\n batch_probs_output = self.apply_stochastic_routing(\n model=self.model,\n input_ids=input_ids,\n clean_probs=decision_probs if epoch >= self.args.warm_up else None,\n indexes=indexes,\n gamma=self.args.r_prob,\n warm_up_period=(epoch < self.args.warm_up)\n )\n\n outputs = self.model(input_ids, attention_mask=attention_mask, output_hidden_states=False)\n logits = outputs.logits\n\n # Model Updates\n optimizer.zero_grad()\n if epoch >= self.args.warm_up:\n loss = self.apply_consistency_regularization(\n logits=logits,\n noisy_labels=noisy_labels,\n ensemble_preds=ensemble_preds if epoch >= self.args.warm_up else None,\n indexes=indexes if epoch >= self.args.warm_up else None,\n temperature=0.5\n )\n\n else:\n loss = (-F.one_hot(noisy_labels, self.num_class) * logits.log_softmax(dim=-1)).sum(dim=-1)\n loss = loss.mean()\n loss.backward(retain_graph=True)\n optimizer.step()\n\n writer['loss'] += loss.mean().item()\n # writer['cka'] += ((fixed_hidden_state - hidden_state) ** 2).mean() # L2 distance\n writer['acc'] += torch.eq(logits.argmax(dim=-1), labels).float().sum()\n \n writer['clean_acc'] += torch.eq(logits[noisy_labels == labels].argmax(dim=-1), labels[noisy_labels == labels]).float().sum()\n writer['nclean'] += (noisy_labels == labels).float().sum()\n \n writer['noise_acc'] += torch.eq(logits[noisy_labels != labels].argmax(dim=-1), noisy_labels[noisy_labels != labels]).float().sum()\n writer['nnoise'] += (noisy_labels != labels).float().sum()\n \n writer['step'] += len(logits)\n\n # Evaluate the global model\n cka = writer['cka'] / writer['step']\n clean_acc = writer['clean_acc'] / writer['nclean']\n noise_acc = writer['noise_acc'] / writer['nnoise']\n test_acc = self.testing_plm(global_loader=test_loader)\n\n training_history['cka'].append(float(cka))\n training_history['clean_acc'].append(float(clean_acc))\n training_history['noise_acc'].append(float(noise_acc))\n training_history['test_acc'].append(float(test_acc))\n\n print('Epoch ({}) Test accuracy {}, avg loss {}, cka {}'.format(epoch, test_acc, writer['loss']/writer['step'], writer['cka'] / writer['step']))\n \n for key in training_history:\n print(f'{key}=', training_history[key])\n\n def load_model(self, file_name):\n model = pickle.load(open(os.path.join(self.args.modeldir, f'{file_name}.pkl'), 'rb'))\n return model\n\n def save_model(self, model, file_name):\n pickle.dump(model, open(os.path.join(self.args.modeldir, f'{file_name}.pkl'), 'wb'))\n" } ] }, { "paper_id": 33, "paper_details": { "title": "Learning to Maximize Mutual Information for Chain-of-Thought Distillation", "url": "https://arxiv.org/pdf/2405.20341" }, "repo_original_url": "https://github.com/xinchen9/cot_distillation_ACL2024", "project_path": "Benchmark/33-COTDistill/cot_disillation_ACL2024-main", "enviorment_name": "distill", "file_organization": "\ncot_disillation_ACL2024-main/\n README.md\n LICENSE\n env.sh\n main.py\n explain_test.py\n data_utils.py\n metrics.py\n model_utils.py\n uncertainty.py\n\n datasets/\n anli1/\n anli1_test.json\n anli1_train.json\n anli1_valid.json\n llm/\n test_CoT_0.json\n train_CoT_0.json\n train_CoT_1.json\n train_CoT_2.json\n train_CoT_3.json\n valid_CoT_0.json\n cqa/\n cqa_test.json\n cqa_train.json\n llm/\n test_CoT_0.json\n test_CoT_1.json\n train_CoT_0.json\n train_CoT_1.json\n train_CoT_2.json\n train_CoT_3.json\n train_CoT_4.json\n train_CoT_5.json\n train_CoT_6.json\n train_CoT_7.json\n train_CoT_8.json\n train_CoT_9.json\n esnli/\n esnli_test.json\n esnli_train.json\n esnli_valid.json\n llm/\n test_CoT_0.json\n test_CoT_1.json\n train_CoT_0.json\n train_CoT_1.json\n train_CoT_2.json\n train_CoT_3.json\n ...\n train_CoT_99.json\n valid_CoT_0.json\n valid_CoT_1.json\n svamp/\n SVAMP.json\n svamp_test.json\n svamp_train.json\n llm/\n test_CoT_0.json\n train_CoT_0.json\n train_CoT_1.json\n", "latex_code_path": "Benchmark/33-COTDistill/arXiv-2403.03348v3", "task_details": [ { "task_id": 0, "indent": 2, "script": "\npython main.py\n", "completion_path": "./model_utils.py", "latex_code": "\n\\subsection{Training Loss}\n\\label{sec:loss}\nThe training loss is given by\n\\begin{equation}\n \\mathcal{L}_{total} \n= \\alpha_1 \\mathcal{L}_{\\mathrm{prediction}} + \\alpha_2 \\mathcal{L}_{\\mathrm{generation}} + \\alpha_3 \\mathcal{L}_{\\mathrm{CE}}\n\\label{eq: dur_los}\n\\end{equation}\nwhere $\\alpha_1$, $\\alpha_2$ and $\\alpha_3$ are regularization parameters, all of which are non-negative. $\\mathcal{L}_{\\mathrm{prediction}}$ represents the loss of the label prediction task, and $\\mathcal{L}_{\\mathrm{generation}}$ represents the loss of the rationale generation task. Both are general cross-entropy loss as defined in~\\cite{hsieh2023distilling}. \nAccording to the last line of Equation~\\ref{eq3}, we define the our MI loss as\n\\begin{equation}\n \\mathcal{L}_{\\mathrm{CE}} = l(f(\\mathbf{Z}),f(\\mathbf{V}))\n\\end{equation}\n$f$ represents our proposed mutual information (MI) loss module, and $l$ denotes the cross-entropy loss. As shown in Figure~\\ref{fig:scheme}, the MI loss module consists of softmax and max reduction layers. The softmax function separately calculates the distributions for the outputs of the vocabulary spaces in the label prediction and rationale generation tasks. Subsequently, a max reduction operation is employed to reduce the dimensionality of the predicted outputs from both tasks to a uniform dimension for the loss calculation. Specifically, in the label prediction task, dimensions are reduced from $\\mathbb{R}^{m \\times d}$ to $\\mathbb{R}^{1 \\times d}$, and in the rationale generation task, from $\\mathbb{R}^{n \\times d}$ to $\\mathbb{R}^{1 \\times d}$.\n", "namespace": "model_utils.TaskPrefixTrainer.compute_loss", "type": "method", "signature_position": [ 55, 55 ], "body_position": [ 56, 71 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Forward pass of the model for both prediction and explanation tasks,\n# corresponding to computing L\u209a\u1d63\u2091d\u1d62ct\u1d62\u2092\u2099 and Lg\u2091\u2099\u2091\u1d63\u2090t\u1d62\u2092\u2099 in the equation\n# L_total = \u03b1\u2081L_prediction + \u03b1\u2082L_generation + \u03b1\u2083L_CE\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\npred_outputs = model(**inputs['pred'])\nexpl_outputs = model(**inputs['expl'])\nloss = self.alpha * pred_outputs.loss + (1. - self.alpha) * expl_outputs.loss\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Implementation of the MI loss module (f) described in the paper,\n# applying softmax to calculate distributions for vocabulary spaces in both tasks.\n# This corresponds to the function f in L_CE = l(f(Z),f(V))\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\npred_logits = (pred_outputs.logits).detach()\nexpl_logits = (expl_outputs.logits)\npred_prob = pred_logits.softmax(dim=-1)\nexpl_prob = expl_logits.softmax(dim=-1)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Max reduction operation to reduce dimensions as described in the paper,\n# where label prediction task dimensions reduce from R^(m\u00d7d) to R^(1\u00d7d) and\n# rationale generation task from R^(n\u00d7d) to R^(1\u00d7d)\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\npred_prob_1 = torch.max(pred_prob, dim=-2)[0]\nexpl_prob_1 = torch.max(expl_prob, dim=-2)[0]\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Computing the mutual information loss L_CE using cross-entropy\n# and combining it with the previous losses to form the total loss.\n# This implements the cross-entropy loss l in L_CE = l(f(Z),f(V))\n# and the total loss L_total = \u03b1\u2081L_prediction + \u03b1\u2082L_generation + \u03b1\u2083L_CE\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nLoss = CrossEntropyLoss()\nms_loss = Loss(expl_prob_1,pred_prob_1)\nloss = loss+ self.beta* ms_loss\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Return the computed total loss to be used for model optimization\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nreturn loss\n# [End Snippet 5]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The LaTeX lacks a description of the subsequent batch-level averaging after the max reduction. The reference code performs an averaging operation over the batch dimension post max-reduction to obtain a unified output shape, a step not mentioned in the LaTeX workflow.\n - The LaTeX description does not specify that the rationale generation loss should be scaled by the complementary factor of the prediction loss weight (i.e., using (1 - prediction loss weight)). The reference code uses this dynamic weighting.\n\n - Mismatched Details:\n - In the LaTeX, parameters are named \u03b1\u2081, \u03b1\u2082, and \u03b1\u2083, while in the code they are self.alpha, (1 - self.alpha), and self.beta respectively.\n - The LaTeX indicates that the mutual information loss is computed via a cross-entropy loss between the processed outputs of both tasks, but it does not specify the exact formulation. The reference code computes this loss by taking the log of the prediction branch\u2019s reduced output and using the argmax of the explanation branch\u2019s reduced probabilities as the target, a formulation that is inconsistent with the LaTeX description.\n", "Missing_details": [ "\n- The LaTeX lacks a description of the subsequent batch-level averaging after the max reduction. The reference code performs an averaging operation over the batch dimension post max-reduction to obtain a unified output shape, a step not mentioned in the LaTeX workflow.\n", "\n- The LaTeX description does not specify that the rationale generation loss should be scaled by the complementary factor of the prediction loss weight (i.e., using (1 - prediction loss weight)). The reference code uses this dynamic weighting.\n" ], "Mismatched_details": [ "\n- In the LaTeX, parameters are named \u03b1\u2081, \u03b1\u2082, and \u03b1\u2083, while in the code they are self.alpha, (1 - self.alpha), and self.beta respectively.\n", "\n- The LaTeX indicates that the mutual information loss is computed via a cross-entropy loss between the processed outputs of both tasks, but it does not specify the exact formulation. The reference code computes this loss by taking the log of the prediction branch\u2019s reduced output and using the argmax of the explanation branch\u2019s reduced probabilities as the target, a formulation that is inconsistent with the LaTeX description.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - model (T5ForConditionalGeneration): The neural network model that performs both label prediction and rationale generation.\n - inputs (Dict): A dictionary containing two keys 'pred' and 'expl', each with model inputs for prediction\n and explanation tasks respectively. Each key contains:\n 'pred': {\n 'input_ids': Tensor of shape [batch_size, seq_length] containing tokenized input sequences\n (typically starts with task prefix token like 9689 for prediction),\n 'attention_mask': Tensor of shape [batch_size, seq_length] with 1s for non-padded tokens and 0s for padding,\n 'labels': Tensor of shape [batch_size, target_length] containing target token IDs with -100 for ignored positions,\n 'decoder_input_ids': Tensor of shape [batch_size, target_length] containing decoder input sequences\n (shifted labels prefixed with 0 token)\n }\n \n 'expl': Similar structure but for the explanation/rationale generation task.\n - return_outputs (bool, optional): Flag to determine if model outputs should be returned alongside loss, not used in the code.\n - num_items_in_batch (int, optional): Number of items in the current batch, added for compatibility with \n parent Seq2SeqTrainer and not used in the code.\n - self.alpha (float): Weighting factor for the prediction loss in the total loss computation.\n - self.beta (float): Weighting factor for the mutual information loss in the total loss computation.\n", "Arguments_list": [ { "name": "cur_trainset", "string": "\n- model (T5ForConditionalGeneration): The neural network model that performs both label prediction and rationale generation.\n", "dependency": "T5ForConditionalGeneration" }, { "name": "inputs", "string": "\n- inputs (Dict): A dictionary containing two keys 'pred' and 'expl', each with model inputs for prediction\n and explanation tasks respectively. Each key contains:\n 'pred': {\n 'input_ids': Tensor of shape [batch_size, seq_length] containing tokenized input sequences\n (typically starts with task prefix token like 9689 for prediction),\n 'attention_mask': Tensor of shape [batch_size, seq_length] with 1s for non-padded tokens and 0s for padding,\n 'labels': Tensor of shape [batch_size, target_length] containing target token IDs with -100 for ignored positions,\n 'decoder_input_ids': Tensor of shape [batch_size, target_length] containing decoder input sequences\n (shifted labels prefixed with 0 token)\n }\n", "dependency": null }, { "name": "return_outputs", "string": "\n- return_outputs (bool, optional): Flag to determine if model outputs should be returned alongside loss, not used in the code.\n", "dependency": null }, { "name": "num_items_in_batch", "string": "\n- num_items_in_batch (int, optional): Number of items in the current batch, added for compatibility with\n parent Seq2SeqTrainer and not used in the code.\n", "dependency": null }, { "name": "self.alpha", "string": "\n- self.alpha (float): Weighting factor for the prediction loss in the total loss computation.\n", "dependency": null }, { "name": "self.beta", "string": "\n- self.beta (float): Weighting factor for the mutual information loss in the total loss computation.\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n Intra File Dependencies: \n - None\n \n Cross File Dependencies: \n - None\n", "intra_file": [], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.nn.CrossEntropyLoss\n - torch.max\n", "list": [ "torch.nn.CrossEntropyLoss", "torch.max" ] }, "Return": { "Return_String": "\nOutput Variables:\n - loss (torch.Tensor): The computed total loss combining prediction loss, generation loss, and MI loss.\n", "Return_list": [ { "name": "loss", "string": "\n- loss (torch.Tensor): The computed total loss combining prediction loss, generation loss, and MI loss.\n", "dependency": null } ] }, "ori_python_file": "# Copyright 2023 The Distilling-step-by-step authors\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# https://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport pandas as pd\nimport torch\nfrom typing import Any, Dict, List, Optional, Tuple, Union\nfrom torch.nn import CrossEntropyLoss, Module\nfrom transformers import DataCollatorForSeq2Seq\nfrom transformers import Seq2SeqTrainer\nimport torch.nn.functional as F\n# from MutualInformation import MutualInformation\n# from torchmetrics.clustering import MutualInfoScore\nimport numpy as np\nfrom torch.autograd import Variable\n\n\"\"\"T5 Multi-Task by Task Prefix\n\"\"\"\nclass TaskPrefixDataCollator(DataCollatorForSeq2Seq):\n def __call__(self, features, return_tensors=None):\n features_df = pd.DataFrame(features)\n pred_features = features_df.loc[:, ~features_df.columns.isin(['aux_labels', 'expl_input_ids', 'expl_attention_mask'])].to_dict('records')\n expl_features = features_df.loc[:, ~features_df.columns.isin(['labels', 'input_ids', 'attention_mask'])].rename(\n columns={'aux_labels': 'labels', 'expl_input_ids': 'input_ids', 'expl_attention_mask': 'attention_mask'}).to_dict('records')\n\n pred_features = super().__call__(pred_features, return_tensors)\n expl_features = super().__call__(expl_features, return_tensors)\n\n\n return {\n 'pred': pred_features,\n 'expl': expl_features,\n }\n\n\nclass TaskPrefixTrainer(Seq2SeqTrainer):\n def __init__(self, alpha, output_rationale, beta, cot_distill,**kwargs):\n super().__init__(**kwargs)\n self.alpha = alpha\n self.output_rationale = output_rationale\n self.beta=beta\n self.cot_distill = cot_distill\n\n def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):\n pred_outputs = model(**inputs['pred'])\n expl_outputs = model(**inputs['expl'])\n loss = self.alpha * pred_outputs.loss + (1. - self.alpha) * expl_outputs.loss\n\n pred_logits = (pred_outputs.logits).detach()\n expl_logits = (expl_outputs.logits)\n pred_prob = pred_logits.softmax(dim=-1)\n expl_prob = expl_logits.softmax(dim=-1)\n \n pred_prob_1 = torch.max(pred_prob, dim=-2)[0]\n expl_prob_1 = torch.max(expl_prob, dim=-2)[0]\n Loss = CrossEntropyLoss()\n ms_loss = Loss(expl_prob_1,pred_prob_1)\n loss = loss+ self.beta* ms_loss\n\n return loss\n\n def prediction_step(\n self,\n model: Module,\n inputs: Dict[str, Union[torch.Tensor, Any]],\n prediction_loss_only: bool,\n ignore_keys: Optional[List[str]] = None\n ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]:\n \n \n pred_outputs = super().prediction_step(model, inputs['pred'], prediction_loss_only=False, ignore_keys=ignore_keys)\n if self.output_rationale:\n expl_outputs = super().prediction_step(model, inputs['expl'], prediction_loss_only=False, ignore_keys=ignore_keys)\n else:\n expl_outputs = pred_outputs # placeholder only\n\n loss = self.alpha * pred_outputs[0] + (1 - self.alpha) * expl_outputs[0]\n return (\n loss,\n [pred_outputs[1], expl_outputs[1]],\n [pred_outputs[2], expl_outputs[2]],\n )\n" } ] }, { "paper_id": 34, "paper_details": { "title": "GLiNER: Generalist Model for Named Entity Recognition using Bidirectional Transformer", "url": "https://aclanthology.org/2024.naacl-long.300/" }, "repo_original_url": "https://github.com/urchade/GLiNER/tree/main", "project_path": "Benchmark/34-GLiNER/GLiNER-main", "enviorment_name": "gliner", "file_organization": "\nGLiNER-main/\n README.md\n README_Extended.md\n RELEASE.md\n LICENSE\n requirements.txt\n pyproject.toml\n main.py\n train.py\n convert_to_onnx.py\n custom_train.py\n demo.py\n eval.py\n\n configs/\n config_biencoder.yaml\n config_span.yaml\n config_token.yaml\n config.yaml\n\n data/\n process_nuner.py\n process_pilener.py\n\n examples/\n convert_to_onnx.ipynb\n exal_example_conll.ipynb\n finetune.ipynb\n gliner_spacy_demo.ipynb\n load_local_model.ipynb\n quickstart.ipynb\n sample_data.json\n synthetic_data_generation.ipynb\n\n gliner/\n config.py\n model.py\n utils.py\n __init__.py\n data_processing/\n collator.py\n dataset.py\n processor.py\n tokenizer.py\n utils.py\n __init__.py\n decoding/\n decoder.py\n utils.py\n __init__.py\n evaluation/\n evaluate.py\n evaluator.py\n __init__.py\n modeling/\n base.py\n encoder.py\n layers.py\n loss_functions.py\n scorers.py\n span_rep.py\n __init__.py\n multitask/\n base.py\n classification.py\n open_extraction.py\n question_answering.py\n relation_extraction.py\n summarization.py\n __init__.py\n onnx/\n model.py\n __init__.py\n training/\n trainer.py\n __init__.py\n\n logo/\n FI_COMPLET_CW.png\n FI Group.png\n\n tests/\n test_features_selection.py\n test_models.py\n\n", "latex_code_path": "Benchmark/34-GLiNER/arXiv-2311.08526v1", "task_details": [ { "task_id": 0, "indent": 2, "script": "\npython main.py\n", "completion_path": "./gliner/modeling/span_rep.py", "latex_code": "\n\\paragraph{Entity and Span Representation} In our model, we aim to encode entity types and span embeddings into a unified latent space. The entity representation is computed by refining the initial representation $\\vp$ using a two-layer feedforward network, resulting in $\\vq=\\{\\vq_i\\}_0^{M-1} \\in \\mathbb{R}^{M\\times D}$. The representation of a span starting at position $i$ and ending at position $j$ in the input text, $\\mS_{ij} \\in \\mathbb{R}^{D}$, is computed as:\n\\begin{equation}\n\\mS_{ij} = \\texttt{FFN}(\\vh_i \\otimes \\vh_j)\n\\end{equation}\n\nHere, \\texttt{FFN} denotes a two-layer feedforward network, and $\\otimes$ represents the concatenation operation. In practice, The computation of all span representations can be easily parallelized. Moreover, we set an upper bound to the length (K=12) of the span in order to keep linear complexity, without harming recall.\n", "namespace": "gliner.modeling.span_rep.SpanMarkerV0.forward", "type": "method", "signature_position": [ 275, 275 ], "body_position": [ 276, 287 ], "ReferenceCode_With_Comments": "\nB, L, D = h.size()\n\n# ---------------------------------------------------------------------------\n# Snippet 1: Transform start/end token embeddings through first FFN layer\n# Implements initial linear transformation from paper's FFN(vh_i \u2297 vh_j)\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nstart_rep = self.project_start(h)\nend_rep = self.project_end(h)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Extract span boundary embeddings using position indices\n# Selects vh_i and vh_j embeddings for span endpoints per Eq.1\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nstart_span_rep = extract_elements(start_rep, span_idx[:, :, 0])\nend_span_rep = extract_elements(end_rep, span_idx[:, :, 1])\ncat = torch.cat([start_span_rep, end_span_rep], dim=-1).relu()\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Apply final linear projection to get span representation\n# Completes FFN transformation from paper's equation\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\noutput = self.out_project(cat).view(B, L, self.max_width, D)\nreturn output\n# [End Snippet 3]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - None\n \n - Mismatched Details:\n - The LaTeX describes the FFN as a single two-layer network applied to concatenated embeddings. However, the reference code splits the FFN into three components: (1) start projection, (2) end projection, and (3) a final linear layer (`out_project`), with ReLU applied *after concatenation* but *before* the final projection.\n", "Missing_details": [], "Mismatched_details": [ "\n- The LaTeX describes the FFN as a single two-layer network applied to concatenated embeddings. However, the reference code splits the FFN into three components: (1) start projection, (2) end projection, and (3) a final linear layer (`out_project`), with ReLU applied *after concatenation* but *before* the final projection.\n" ] }, "Arguments": { "string": "\nInput Variables:\n - h (torch.Tensor, dtype=torch.float32, shape=[batch_size, sequence_length, hidden_size]):\n Contextual token embeddings produced by the token encoder, denoted as \\( \\vh \\) in LaTeX.\n - span_idx (torch.LongTensor, shape=[batch_size, num_spans, 2]): Indices identifying span boundaries (i,j) of shape [batch_size, num_spans, 2] where [:,:,0] contains start indices and [:,:,1] contains end indices\n", "Arguments_list": [ { "name": "h", "string": "\n- h (torch.Tensor, dtype=torch.float32, shape=[batch_size, sequence_length, hidden_size]):\n Contextual token embeddings produced by the token encoder, denoted as \\( \\vh \\) in LaTeX.\n", "dependency": null }, { "name": "span_idx", "string": "\n- span_idx (torch.LongTensor, shape=[batch_size, num_spans, 2]): Indices identifying span boundaries (i,j) of shape [batch_size, num_spans, 2] where [:,:,0] contains start indices and [:,:,1] contains end indices\n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-file Dependencies:\n - extract_elements\n - SpanMarkerV0.project_end\n - SpanMarkerV0.project_start\n - SpanMarkerV0.out_project\n\n - Cross-file Dependencies:\n - None\n", "intra_file": [ "extract_elements", "SpanMarkerV0.project_end", "SpanMarkerV0.project_start", "SpanMarkerV0.out_project" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.cat\n", "list": [ "torch.cat" ] }, "Return": { "Return_String": "\nOutput Variables:\n - output (torch.Tensor, dtype=torch.float32, shape=[batch_size, num_spans, self.max_width, hidden_size]):\n Final span representation after applying transformations, corresponding to \\( \\text{FFN}(\\vh_i \\otimes \\vh_j) \\) in LaTeX.\n", "Return_list": [ { "name": "output", "string": "\n- output (torch.Tensor, dtype=torch.float32, shape=[batch_size, num_spans, self.max_width, hidden_size]):\n Final span representation after applying transformations, corresponding to \\( \\text{FFN}(\\vh_i \\otimes \\vh_j) \\) in LaTeX.\n", "dependency": null } ] }, "ori_python_file": "import torch\nimport torch.nn.functional as F\nfrom torch import nn\n\nfrom .layers import create_projection_layer\n\nclass SpanQuery(nn.Module):\n\n def __init__(self, hidden_size, max_width, trainable=True):\n super().__init__()\n\n self.query_seg = nn.Parameter(torch.randn(hidden_size, max_width))\n\n nn.init.uniform_(self.query_seg, a=-1, b=1)\n\n if not trainable:\n self.query_seg.requires_grad = False\n\n self.project = nn.Sequential(\n nn.Linear(hidden_size, hidden_size),\n nn.ReLU()\n )\n\n def forward(self, h, *args):\n # h of shape [B, L, D]\n # query_seg of shape [D, max_width]\n\n span_rep = torch.einsum('bld, ds->blsd', h, self.query_seg)\n\n return self.project(span_rep)\n\n\nclass SpanMLP(nn.Module):\n\n def __init__(self, hidden_size, max_width):\n super().__init__()\n\n self.mlp = nn.Linear(hidden_size, hidden_size * max_width)\n\n def forward(self, h, *args):\n # h of shape [B, L, D]\n # query_seg of shape [D, max_width]\n\n B, L, D = h.size()\n\n span_rep = self.mlp(h)\n\n span_rep = span_rep.view(B, L, -1, D)\n\n return span_rep.relu()\n\n\nclass SpanCAT(nn.Module):\n\n def __init__(self, hidden_size, max_width):\n super().__init__()\n\n self.max_width = max_width\n\n self.query_seg = nn.Parameter(torch.randn(128, max_width))\n\n self.project = nn.Sequential(\n nn.Linear(hidden_size + 128, hidden_size),\n nn.ReLU()\n )\n\n def forward(self, h, *args):\n # h of shape [B, L, D]\n # query_seg of shape [D, max_width]\n\n B, L, D = h.size()\n\n h = h.view(B, L, 1, D).repeat(1, 1, self.max_width, 1)\n\n q = self.query_seg.view(1, 1, self.max_width, -1).repeat(B, L, 1, 1)\n\n span_rep = torch.cat([h, q], dim=-1)\n\n span_rep = self.project(span_rep)\n\n return span_rep\n\n\nclass SpanConvBlock(nn.Module):\n def __init__(self, hidden_size, kernel_size, span_mode='conv_normal'):\n super().__init__()\n\n if span_mode == 'conv_conv':\n self.conv = nn.Conv1d(hidden_size, hidden_size,\n kernel_size=kernel_size)\n\n # initialize the weights\n nn.init.kaiming_uniform_(self.conv.weight, nonlinearity='relu')\n\n elif span_mode == 'conv_max':\n self.conv = nn.MaxPool1d(kernel_size=kernel_size, stride=1)\n elif span_mode == 'conv_mean' or span_mode == 'conv_sum':\n self.conv = nn.AvgPool1d(kernel_size=kernel_size, stride=1)\n\n self.span_mode = span_mode\n\n self.pad = kernel_size - 1\n\n def forward(self, x):\n\n x = torch.einsum('bld->bdl', x)\n\n if self.pad > 0:\n x = F.pad(x, (0, self.pad), \"constant\", 0)\n\n x = self.conv(x)\n\n if self.span_mode == \"conv_sum\":\n x = x * (self.pad + 1)\n\n return torch.einsum('bdl->bld', x)\n\n\nclass SpanConv(nn.Module):\n def __init__(self, hidden_size, max_width, span_mode):\n super().__init__()\n\n kernels = [i + 2 for i in range(max_width - 1)]\n\n self.convs = nn.ModuleList()\n\n for kernel in kernels:\n self.convs.append(SpanConvBlock(hidden_size, kernel, span_mode))\n\n self.project = nn.Sequential(\n nn.ReLU(),\n nn.Linear(hidden_size, hidden_size)\n )\n\n def forward(self, x, *args):\n\n span_reps = [x]\n\n for conv in self.convs:\n h = conv(x)\n span_reps.append(h)\n\n span_reps = torch.stack(span_reps, dim=-2)\n\n return self.project(span_reps)\n\n\nclass SpanEndpointsBlock(nn.Module):\n def __init__(self, kernel_size):\n super().__init__()\n\n self.kernel_size = kernel_size\n\n def forward(self, x):\n B, L, D = x.size()\n\n span_idx = torch.LongTensor(\n [[i, i + self.kernel_size - 1] for i in range(L)]).to(x.device)\n\n x = F.pad(x, (0, 0, 0, self.kernel_size - 1), \"constant\", 0)\n\n # endrep\n start_end_rep = torch.index_select(x, dim=1, index=span_idx.view(-1))\n\n start_end_rep = start_end_rep.view(B, L, 2, D)\n\n return start_end_rep\n\n\nclass ConvShare(nn.Module):\n def __init__(self, hidden_size, max_width):\n super().__init__()\n\n self.max_width = max_width\n\n self.conv_weigth = nn.Parameter(\n torch.randn(hidden_size, hidden_size, max_width))\n\n nn.init.kaiming_uniform_(self.conv_weigth, nonlinearity='relu')\n\n self.project = nn.Sequential(\n nn.ReLU(),\n nn.Linear(hidden_size, hidden_size)\n )\n\n def forward(self, x, *args):\n span_reps = []\n\n x = torch.einsum('bld->bdl', x)\n\n for i in range(self.max_width):\n pad = i\n x_i = F.pad(x, (0, pad), \"constant\", 0)\n conv_w = self.conv_weigth[:, :, :i + 1]\n out_i = F.conv1d(x_i, conv_w)\n span_reps.append(out_i.transpose(-1, -2))\n\n out = torch.stack(span_reps, dim=-2)\n\n return self.project(out)\n\n\ndef extract_elements(sequence, indices):\n B, L, D = sequence.shape\n K = indices.shape[1]\n\n # Expand indices to [B, K, D]\n expanded_indices = indices.unsqueeze(2).expand(-1, -1, D)\n\n # Gather the elements\n extracted_elements = torch.gather(sequence, 1, expanded_indices)\n\n return extracted_elements\n\n\nclass SpanMarker(nn.Module):\n\n def __init__(self, hidden_size, max_width, dropout=0.4):\n super().__init__()\n\n self.max_width = max_width\n\n self.project_start = nn.Sequential(\n nn.Linear(hidden_size, hidden_size * 2, bias=True),\n nn.ReLU(),\n nn.Dropout(dropout),\n nn.Linear(hidden_size * 2, hidden_size, bias=True),\n )\n\n self.project_end = nn.Sequential(\n nn.Linear(hidden_size, hidden_size * 2, bias=True),\n nn.ReLU(),\n nn.Dropout(dropout),\n nn.Linear(hidden_size * 2, hidden_size, bias=True),\n )\n\n self.out_project = nn.Linear(hidden_size * 2, hidden_size, bias=True)\n\n def forward(self, h, span_idx):\n # h of shape [B, L, D]\n # query_seg of shape [D, max_width]\n\n B, L, D = h.size()\n\n # project start and end\n start_rep = self.project_start(h)\n end_rep = self.project_end(h)\n\n start_span_rep = extract_elements(start_rep, span_idx[:, :, 0])\n end_span_rep = extract_elements(end_rep, span_idx[:, :, 1])\n\n # concat start and end\n cat = torch.cat([start_span_rep, end_span_rep], dim=-1).relu()\n\n # project\n cat = self.out_project(cat)\n\n # reshape\n return cat.view(B, L, self.max_width, D)\n\n\nclass SpanMarkerV0(nn.Module):\n \"\"\"\n Marks and projects span endpoints using an MLP.\n \"\"\"\n\n def __init__(self, hidden_size: int, max_width: int, dropout: float = 0.4):\n super().__init__()\n self.max_width = max_width\n self.project_start = create_projection_layer(hidden_size, dropout)\n self.project_end = create_projection_layer(hidden_size, dropout)\n\n self.out_project = create_projection_layer(hidden_size * 2, dropout, hidden_size)\n\n def forward(self, h: torch.Tensor, span_idx: torch.Tensor) -> torch.Tensor:\n B, L, D = h.size()\n\n start_rep = self.project_start(h)\n end_rep = self.project_end(h)\n\n start_span_rep = extract_elements(start_rep, span_idx[:, :, 0])\n end_span_rep = extract_elements(end_rep, span_idx[:, :, 1])\n\n cat = torch.cat([start_span_rep, end_span_rep], dim=-1).relu()\n\n output = self.out_project(cat).view(B, L, self.max_width, D)\n return output\n\n \n\nclass ConvShareV2(nn.Module):\n def __init__(self, hidden_size, max_width):\n super().__init__()\n\n self.max_width = max_width\n\n self.conv_weigth = nn.Parameter(\n torch.randn(hidden_size, hidden_size, max_width)\n )\n\n nn.init.xavier_normal_(self.conv_weigth)\n\n def forward(self, x, *args):\n span_reps = []\n\n x = torch.einsum('bld->bdl', x)\n\n for i in range(self.max_width):\n pad = i\n x_i = F.pad(x, (0, pad), \"constant\", 0)\n conv_w = self.conv_weigth[:, :, :i + 1]\n out_i = F.conv1d(x_i, conv_w)\n span_reps.append(out_i.transpose(-1, -2))\n\n out = torch.stack(span_reps, dim=-2)\n\n return out\n \n \n\n\nclass SpanRepLayer(nn.Module):\n \"\"\"\n Various span representation approaches\n \"\"\"\n\n def __init__(self, hidden_size, max_width, span_mode, **kwargs):\n super().__init__()\n\n if span_mode == 'marker':\n self.span_rep_layer = SpanMarker(hidden_size, max_width, **kwargs)\n elif span_mode == 'markerV0':\n self.span_rep_layer = SpanMarkerV0(hidden_size, max_width, **kwargs)\n elif span_mode == 'query':\n self.span_rep_layer = SpanQuery(\n hidden_size, max_width, trainable=True)\n elif span_mode == 'mlp':\n self.span_rep_layer = SpanMLP(hidden_size, max_width)\n elif span_mode == 'cat':\n self.span_rep_layer = SpanCAT(hidden_size, max_width)\n elif span_mode == 'conv_conv':\n self.span_rep_layer = SpanConv(\n hidden_size, max_width, span_mode='conv_conv')\n elif span_mode == 'conv_max':\n self.span_rep_layer = SpanConv(\n hidden_size, max_width, span_mode='conv_max')\n elif span_mode == 'conv_mean':\n self.span_rep_layer = SpanConv(\n hidden_size, max_width, span_mode='conv_mean')\n elif span_mode == 'conv_sum':\n self.span_rep_layer = SpanConv(\n hidden_size, max_width, span_mode='conv_sum')\n elif span_mode == 'conv_share':\n self.span_rep_layer = ConvShare(hidden_size, max_width)\n else:\n raise ValueError(f'Unknown span mode {span_mode}')\n\n def forward(self, x, *args):\n\n return self.span_rep_layer(x, *args)\n" }, { "task_id": 1, "indent": 2, "script": "\npython main.py\n", "latex_code": "\n\\paragraph{Entity Type and Span Matching}\nTo evaluate whether a span $(i, j)$ corresponds to entity type $t$, we calculate the following matching score:\n\n\\begin{equation}\n\\phi(i,j,t) = \\sigma(\\mS_{ij}^T \\vq_t) \\in \\mathbb{R}\n\\end{equation}\n\nIn this equation, $\\sigma$ denotes a sigmoid activation function. As we train with binary cross-entropy loss (see next sec. \\ref{train}), $\\phi(i,j,t)$ can be interpreted as the probability of the span $(i,j)$ being of type $t$.\n", "completion_path": "./gliner/modeling/base.py", "namespace": "gliner.modeling.base.SpanModel.entity_type_span_matching", "type": "method", "signature_position": [ 214, 214 ], "body_position": [ 215, 219 ], "ReferenceCode_With_Comments": "\n# ---------------------------------------------------------------------------\n# Snippet 1: Apply span mask to filter out invalid spans. The paper doesn't explicitly\n# mention this filtering step, but it's necessary in practice to handle variable-length\n# sequences and ensure we only consider valid spans.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 1]\nspan_idx = span_idx * span_mask.unsqueeze(-1)\n# [End Snippet 1]\n\n# ---------------------------------------------------------------------------\n# Snippet 2: Compute span representations (S_ij) from word embeddings.\n# This corresponds to the S_ij term in the equation \u03c6(i,j,t) = \u03c3(S_ij^T q_t).\n# The SpanRepLayer implements the span representation computation described in\n# another section of the paper (S_ij = FFN(h_i \u2297 h_j)).\n# ---------------------------------------------------------------------------\n# [Begin Snippet 2]\nspan_rep = self.span_rep_layer(words_embedding, span_idx)\n# [End Snippet 2]\n\n# ---------------------------------------------------------------------------\n# Snippet 3: Process entity type embeddings to produce q_t.\n# This corresponds to the refinement of initial entity representations p\n# using a two-layer feedforward network to get q_t as mentioned in the paper.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 3]\nprompts_embedding = self.prompt_rep_layer(prompts_embedding)\n# [End Snippet 3]\n\n# ---------------------------------------------------------------------------\n# Snippet 4: Compute the matching scores using the dot product S_ij^T q_t.\n# This directly implements the core of the equation \u03c6(i,j,t) = \u03c3(S_ij^T q_t)\n# without the sigmoid activation. The einsum performs batch matrix multiplication\n# between span representations and entity type embeddings.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 4]\nscores = torch.einsum(\"BLKD,BCD->BLKC\", span_rep, prompts_embedding)\n# [End Snippet 4]\n\n# ---------------------------------------------------------------------------\n# Snippet 5: Return the raw matching scores and processed representations.\n# The paper only mentions the final matching score \u03c6(i,j,t), but the function\n# returns intermediate representations as well.\n# ---------------------------------------------------------------------------\n# [Begin Snippet 5]\nreturn scores, span_rep, prompts_embedding\n# [End Snippet 5]\n", "Missing_Mismatched_details": { "string": "\nMissing or Mismatched Details:\n - Missing Details:\n - The LaTeX description does not include a step for filtering or masking invalid span indices. In the reference implementation, there is a specific workflow where the algorithm first eliminates invalid spans by applying a mask.\n \n - Mismatched Details:\n - Application timing of sigmoid activation. The LaTeX equation explicitly includes \\( \\sigma \\) in the matching score, but the reference code defers the activation to the loss function (BCEWithLogitsLoss), returning raw logits. \n", "Missing_details": [ "\n- The LaTeX description does not include a step for filtering or masking invalid span indices. In the reference implementation, there is a specific workflow where the algorithm first eliminates invalid spans by applying a mask.\n" ], "Mismatched_details": [ "\n- Application timing of sigmoid activation. The LaTeX equation explicitly includes \\( \\sigma \\) in the matching score, but the reference code defers the activation to the loss function (BCEWithLogitsLoss), returning raw logits. \n" ] }, "Arguments": { "string": "\nInput Variables:\n - words_embedding (torch.Tensor, shape=[batch_size, sequence_length, hidden_dim]): Word representations (h) \n - span_idx (torch.Tensor, shape=[batch_size, num_spans, 2]): Indices identifying span boundaries (i,j)\n - span_mask (torch.Tensor, shape=[batch_size, num_spans]): Mask for valid spans.\n - prompts_embedding (torch.Tensor, shape=[batch_size, num_entity_types, hidden_dim]): Entity type embeddings (p). \n", "Arguments_list": [ { "name": "words_embedding", "string": "\n- words_embedding (torch.Tensor, shape=[batch_size, sequence_length, hidden_dim]): Word representations (h) \n", "dependency": null }, { "name": "span_idx", "string": "\n- span_idx (torch.Tensor, shape=[batch_size, num_spans, 2]): Indices identifying span boundaries (i,j)\n", "dependency": null }, { "name": "span_mask", "string": "\n- span_mask (torch.Tensor, shape=[batch_size, num_spans]): Mask for valid spans.\n", "dependency": null }, { "name": "prompts_embedding", "string": "\n- prompts_embedding (torch.Tensor, shape=[batch_size, num_entity_types, hidden_dim]): Entity type embeddings (p). \n", "dependency": null } ] }, "dependency": { "string": "\nDependencies:\n - Intra-file Dependencies: \n - SpanModel.span_rep_layer\n - SpanModel.prompt_rep_layer\n\n - Cross-file Dependencies: \n - None\n", "intra_file": [ "SpanModel.span_rep_layer", "SpanModel.prompt_rep_layer" ], "cross_file": [] }, "external_APIs": { "string": "\nExternal APIs:\n - torch.einsum\n", "list": [ "torch.einsum" ] }, "Return": { "Return_String": "\nOutput Variables:\n - scores (torch.Tensor, shape=[batch_size, sequence_length, max_width, num_entity_types]): Raw matching scores between spans and entity types with shape \n - span_rep (torch.Tensor, shape=[batch_size, sequence_length, max_width, hidden_dim]): Processed span representations (S_ij) with shape \n - prompts_embedding (torch.Tensor, shape=[batch_size, num_entity_types, hidden_dim]): Processed entity type embeddings (q_t) with shape \n", "Return_list": [ { "name": "scores", "string": "\n- scores (torch.Tensor, shape=[batch_size, sequence_length, max_width, num_entity_types]): Raw matching scores between spans and entity types with shape \n", "dependency": null }, { "name": "span_rep", "string": "\n- span_rep (torch.Tensor, shape=[batch_size, sequence_length, max_width, hidden_dim]): Processed span representations (S_ij) with shape\n", "dependency": null }, { "name": "prompts_embedding", "string": "\n- prompts_embedding (torch.Tensor, shape=[batch_size, num_entity_types, hidden_dim]): Processed entity type embeddings (q_t) with shape\n", "dependency": null } ] }, "ori_python_file": "from typing import Optional, Tuple\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass\nimport warnings\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn.utils.rnn import pad_sequence\n\nfrom transformers.utils import ModelOutput\n\nfrom .encoder import Encoder, BiEncoder\nfrom .layers import LstmSeq2SeqEncoder, CrossFuser, create_projection_layer\nfrom .scorers import Scorer\nfrom .loss_functions import focal_loss_with_logits\nfrom .span_rep import SpanRepLayer\n\n@dataclass\nclass GLiNERModelOutput(ModelOutput):\n loss: Optional[torch.FloatTensor] = None\n logits: Optional[torch.FloatTensor] = None\n prompts_embedding: Optional[torch.FloatTensor] = None\n prompts_embedding_mask: Optional[torch.LongTensor] = None\n words_embedding: Optional[torch.FloatTensor] = None\n mask: Optional[torch.LongTensor] = None\n\ndef extract_word_embeddings(token_embeds, words_mask, attention_mask, \n batch_size, max_text_length, embed_dim, text_lengths):\n words_embedding = torch.zeros(\n batch_size, max_text_length, embed_dim, dtype=token_embeds.dtype, device=token_embeds.device\n )\n\n batch_indices, word_idx = torch.where(words_mask>0)\n \n target_word_idx = words_mask[batch_indices, word_idx]-1\n\n words_embedding[batch_indices, target_word_idx] = token_embeds[batch_indices, word_idx]\n \n aranged_word_idx = torch.arange(max_text_length, \n dtype=attention_mask.dtype, \n device=token_embeds.device).expand(batch_size, -1)\n mask = aranged_word_idxBLKC\", span_rep, prompts_embedding)\n return scores, span_rep, prompts_embedding\n\n def forward(self, \n input_ids: Optional[torch.FloatTensor] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n labels_embeddings: Optional[torch.FloatTensor] = None,\n labels_input_ids: Optional[torch.FloatTensor] = None,\n labels_attention_mask: Optional[torch.LongTensor] = None,\n words_embedding: Optional[torch.FloatTensor] = None,\n mask: Optional[torch.LongTensor] = None,\n prompts_embedding: Optional[torch.FloatTensor] = None,\n prompts_embedding_mask: Optional[torch.LongTensor] = None,\n words_mask: Optional[torch.LongTensor] = None,\n text_lengths: Optional[torch.Tensor] = None,\n span_idx: Optional[torch.LongTensor] = None,\n span_mask: Optional[torch.LongTensor] = None,\n labels: Optional[torch.FloatTensor] = None,\n **kwargs\n ):\n\n prompts_embedding, prompts_embedding_mask, words_embedding, mask = self.get_representations(input_ids, attention_mask, \n labels_embeddings, labels_input_ids, labels_attention_mask, \n text_lengths, words_mask)\n scores, span_rep, prompts_embedding = self.entity_type_span_matching(\n words_embedding, span_idx, span_mask, prompts_embedding\n )\n\n loss = None\n if labels is not None:\n loss = self.loss(scores, labels, prompts_embedding_mask, span_mask, **kwargs)\n\n output = GLiNERModelOutput(\n logits=scores,\n loss=loss,\n prompts_embedding=prompts_embedding,\n prompts_embedding_mask=prompts_embedding_mask,\n words_embedding=words_embedding,\n mask=mask,\n )\n return output\n \n def loss(self, scores, labels, prompts_embedding_mask, mask_label,\n alpha: float = -1., gamma: float = 0.0, label_smoothing: float = 0.0, \n reduction: str = 'sum', **kwargs):\n \n batch_size = scores.shape[0]\n num_classes = prompts_embedding_mask.shape[-1]\n\n scores = scores.view(-1, num_classes)\n labels = labels.view(-1, num_classes)\n \n all_losses = self._loss(scores, labels, alpha, gamma, label_smoothing)\n\n masked_loss = all_losses.view(batch_size, -1, num_classes) * prompts_embedding_mask.unsqueeze(1)\n all_losses = masked_loss.view(-1, num_classes)\n\n mask_label = mask_label.view(-1, 1)\n \n all_losses = all_losses * mask_label.float()\n\n if reduction == \"mean\":\n loss = all_losses.mean()\n elif reduction == 'sum':\n loss = all_losses.sum()\n else:\n warnings.warn(\n f\"Invalid Value for config 'loss_reduction': '{reduction} \\n Supported reduction modes:\"\n f\" 'none', 'mean', 'sum'. It will be used 'sum' instead.\")\n loss = all_losses.sum()\n return loss\n \nclass TokenModel(BaseModel):\n def __init__(self, config, encoder_from_pretrained):\n super(TokenModel, self).__init__(config, encoder_from_pretrained)\n self.scorer = Scorer(config.hidden_size, config.dropout)\n\n def forward(self, \n input_ids: Optional[torch.FloatTensor] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n labels_embeddings: Optional[torch.FloatTensor] = None,\n labels_input_ids: Optional[torch.FloatTensor] = None,\n labels_attention_mask: Optional[torch.LongTensor] = None,\n words_embedding: Optional[torch.FloatTensor] = None,\n mask: Optional[torch.LongTensor] = None,\n prompts_embedding: Optional[torch.FloatTensor] = None,\n prompts_embedding_mask: Optional[torch.LongTensor] = None,\n words_mask: Optional[torch.LongTensor] = None,\n text_lengths: Optional[torch.Tensor] = None,\n labels: Optional[torch.FloatTensor] = None,\n **kwargs\n ):\n\n prompts_embedding, prompts_embedding_mask, words_embedding, mask = self.get_representations(input_ids, attention_mask,\n labels_embeddings, labels_input_ids, labels_attention_mask,\n text_lengths, words_mask)\n \n scores = self.scorer(words_embedding, prompts_embedding)\n\n loss = None\n if labels is not None:\n loss = self.loss(scores, labels, prompts_embedding_mask, mask, **kwargs)\n \n output = GLiNERModelOutput(\n logits=scores,\n loss=loss,\n prompts_embedding=prompts_embedding,\n prompts_embedding_mask=prompts_embedding_mask,\n words_embedding=words_embedding,\n mask=mask,\n )\n return output\n \n def loss(self, scores, labels, prompts_embedding_mask, mask, \n alpha: float = -1., gamma: float = 0.0, label_smoothing: float = 0.0, \n reduction: str = 'sum', **kwargs):\n all_losses = self._loss(scores, labels, alpha, gamma, label_smoothing)\n\n all_losses = all_losses * prompts_embedding_mask.unsqueeze(1) * mask.unsqueeze(-1)\n\n if reduction == \"mean\":\n loss = all_losses.mean()\n elif reduction == 'sum':\n loss = all_losses.sum()\n else:\n warnings.warn(\n f\"Invalid Value for config 'loss_reduction': '{reduction} \\n Supported reduction modes:\"\n f\" 'none', 'mean', 'sum'. It will be used 'sum' instead.\")\n loss = all_losses.sum()\n return loss" } ] }, { "paper_id": 35, "paper_details": { "title": "End-to-End Beam Retrieval for Multi-Hop Question Answering", "url": "https://arxiv.org/abs/2308.08973" }, "repo_original_url": "https://github.com/canghongjian/beam_retriever", "project_path": "Benchmark/35-beam_retriever/beam_retriever-main", "enviorment_name": "beam", "file_organization": "\nbeam_retriever-main/\n README.md\n LICENSE\n env.sh\n\n data/\n dev_test_singlehop_questions_v1.0.json\n musique_ans_v1.0_dev.jsonl\n musique_ans_v1.0_test.jsonl\n musique_ans_v1.0_train.jsonl\n musique_full_v1.0_dev.jsonl\n musique_full_v1.0_test.jsonl\n musique_full_v1.0_train.jsonl\n\n fullwiki/\n format_data.py\n test_fullwiki_reranker.py\n\n prompts/\n few-shots_2wiki_br.txt\n few-shots_2wiki.txt\n few-shots_hotpot_br.txt\n few-shots_hotpot.txt\n few-shots_iirc_br.txt\n few-shots_iirc.txt\n few-shots_musique_br.txt\n few-shots_musique.txt\n few-shot.txt\n zero-shot.txt\n\n qa/\n config.py\n datasets.py\n reader_model.py\n\n retrieval/\n config.py\n datasets.py\n retriever_model.py\n\n results/\n downstream_llm/\n example_2wiki.jsonl\n example_2wiki_open_source.jsonl\n example_hotpot_open_source.jsonl\n example_musique.jsonl\n example_musique_open_source.jsonl\n retrieval/\n 2wiki_pred_best.json\n hotpot_pred_best_retr.json\n musique_pred_best.json\n\n utils/\n utils.py\n\n scripts/\n run_train_2wiki.sh\n run_train_beam_retr.sh\n run_train_fullwiki_reranker.sh\n run_train_reader.sh\n run_train_retr_musique.sh\n\n experiments/\n gpt_turbo_exp.py\n llm_exp_long.py\n test_model_tmp.py\n train_beam_retriever.py\n train_reader.py\n\n\n", "latex_code_path": "Benchmark/35-beam_retriever/arXiv-2308.08973v2", "task_details": [ { "task_id": 0, "indent": 2, "script": "\npython train_beam_retriever.py --do_train --gradient_checkpointing --prefix deberta_use_two_classier_musique_beam_size2 --model_name microsoft/deberta-v3-base --tokenizer_path microsoft/deberta-v3-base --dataset_type musique --train_file data/musique_ans_v1.0_train.jsonl --predict_file data/musique_ans_v1.0_dev.jsonl --train_batch_size 8 --learning_rate 1e-5 --mean_passage_len 120 --fp16 --beam_size 2 --predict_batch_size 1 --num_train_epochs 20 --warmup-ratio 0.1 --log_period_ratio 0.01 --accumulate_gradients 8 --eval_period_ratio 0.3 \n", "completion_path": "./retrieval/retriever_model.py", "latex_code": "\n\\section{Beam Retrieval}\\label{beam_retrieval_method}\n\nBeam Retrieval is designed to handle a $k$-hop multi-hop question $Q$ and accurately selects the most relevant passages, providing nearly noiseless context for downstream QA tasks. In this section, we clarify how Beam Retrieval infers and trains in an end-to-end manner, which is illustrated in Figure~\\ref{fig:framework}.\n\n\\subsection{Problem Formulation}\\label{score_function}\nGiven a $k$-hop question $Q$ and a candidate set with $n$ passages as $\\mathcal{D} = {\\{p_1, p_2, ..., p_n}\\}$, multi-hop retrieval aims to produce a relevant passages chain ($\\hat{p}_1, \\hat{p}_2, ..., \\hat{p}_k$). Most existing work formulates it as a one-step or two-step sequence labeling task, classifying every passage $p_i \\in \\mathcal{D}$ as relevant or not. However, this method lacks generality and precision.\n\nIn contrast, we align the multi-hop retrieval task with text decoding, proposing a more general retrieval framework with higher precision. Conceptually, a passage $p_i \\in \\mathcal{D}$ corresponds to a token $w_i \\in \\mathcal{V}$ and the question $Q$ corresponds to a special start token ``$<$s$>$''. Similarly, we also denote the output of a multi-hop retriever as $\\acute{z}_t = \\acute{f}(Q, \\hat{p}_1, ..., \\hat{p}_{t-1})$, given the concatenated sequence of question and passages identified so far, ($Q, \\hat{p}_1, ..., \\hat{p}_{t-1}$), which we write as $\\hat{p}_{