From ef1f2e1d72bf284a4b18a191e018fd7fde179a6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A8=80=E6=96=AF?= Date: Thu, 29 Feb 2024 15:09:47 +0800 Subject: [PATCH] Add: attention-buckets --- attention-buckets/README.md | 73 + attention-buckets/base_rag/download_model.py | 4 + attention-buckets/base_rag/merge_result.py | 76 + .../base_rag/prompts/closedbook_qa.prompt | 2 + .../base_rag/prompts/kv_retrieval.prompt | 7 + ..._with_query_aware_contextualization.prompt | 9 + attention-buckets/base_rag/prompts/qa.prompt | 6 + .../prompts/qa_ordered_randomly.prompt | 6 + ..._with_query_aware_contextualization.prompt | 8 + attention-buckets/base_rag/test_nq_kl.py | 168 ++ attention-buckets/basic.py | 541 ++++ attention-buckets/inference/config.py | 8 + attention-buckets/inference/utils.py | 279 ++ attention-buckets/modeling_llama.py | 2498 +++++++++++++++++ attention-buckets/requirements.txt | 31 + attention-buckets/utils.py | 143 + 16 files changed, 3859 insertions(+) create mode 100644 attention-buckets/README.md create mode 100644 attention-buckets/base_rag/download_model.py create mode 100644 attention-buckets/base_rag/merge_result.py create mode 100644 attention-buckets/base_rag/prompts/closedbook_qa.prompt create mode 100644 attention-buckets/base_rag/prompts/kv_retrieval.prompt create mode 100644 attention-buckets/base_rag/prompts/kv_retrieval_with_query_aware_contextualization.prompt create mode 100644 attention-buckets/base_rag/prompts/qa.prompt create mode 100644 attention-buckets/base_rag/prompts/qa_ordered_randomly.prompt create mode 100644 attention-buckets/base_rag/prompts/qa_with_query_aware_contextualization.prompt create mode 100644 attention-buckets/base_rag/test_nq_kl.py create mode 100644 attention-buckets/basic.py create mode 100644 attention-buckets/inference/config.py create mode 100644 attention-buckets/inference/utils.py create mode 100644 attention-buckets/modeling_llama.py create mode 100644 attention-buckets/requirements.txt create mode 100644 attention-buckets/utils.py diff --git a/attention-buckets/README.md b/attention-buckets/README.md new file mode 100644 index 00000000..b05302cd --- /dev/null +++ b/attention-buckets/README.md @@ -0,0 +1,73 @@ +# Fortify the Shortest Stave in Attention: Enhancing Context Awareness of Large Language Models for Effective Tool Use + +The codes is implemented based on pytorch and codes for tool-use is base on [ToolBench](https://github.com/OpenBMB/ToolBench). We appreciate these open-source codes. + +## Install +```bash +https://github.com/AlibabaResearch/DAMO-ConvAI.git +cd attention-buckets +conda create -n your_envs python=3.9 +conda activate your_envs +pip install -r requirment.txt +# repalce "your_env_path/lib/site-packages/transformers/models/llama/modeling-llama.py" with our 'modeling-llama.py' +``` +## Code for tool-use +```bash +git clone git@github.com:OpenBMB/ToolBench.git +cd ToolBench +``` +We only present information about our work, for more information about toolbench please refer to [ToolBench](https://github.com/OpenBMB/ToolBench) + +### Data +Put all dataset in ToolBench/data +- Original data of ToolBench: Download the dataset using the following link: [Google Drive](https://drive.google.com/drive/folders/1yBUQ732mPu-KclJnuQELEhtKakdXFc3J) or [Tsinghua Cloud](https://cloud.tsinghua.edu.cn/f/c9e50625743b40bfbe10/). +- results of our method: Download the dataset using the following link: [Google Drive](https://alibaba-research.oss-cn-beijing.aliyuncs.com/attention-buckets/all_data.zip) + + +### core codes and how to run and how to eval +1.replace "ToolBench/toolbench/inference/utils.py" with our "inference/utils.py" +2.move our "inference/config.py" to "ToolBench/toolbench/inference" +3.replace "ToolBench/toolbench/utils.py" with our "utils.py" +```bash +# run +bash scripts/inference_toolllama_pipeline.sh +# eval, the same to ToolBench +cd tooleval +bash run_convert_answer.sh +bash run_pass_rate.sh +# get pass rate of chatgpt_cot and your method and then run to get preference. +bash run_preference.sh +``` + +## Code for rag +```bash +cd base_rag +``` +### Data +Put the data in ../qa_dataset +Download the dataset using the following link: [Google Drive](https://alibaba-research.oss-cn-beijing.aliyuncs.com/attention-buckets/all_data.zip) + +### how to run and eval +```bash +# run +# bsz >= total bases num +CUDA_VISIBLE_DEVICES=i python test_nq_kl.py --flag i --bsz 8 --num_doc $num_doc --ngpu $n_gpu --data_name $data_name + +# eval +python merge_result.py --ngpu $n_gpu --data_name $data_name --num_doc $num_doc +``` + + +## Citation +Feel free to cite us if you like our work. +```bibtex +@article{Chen2023FortifyTS, + title={Fortify the Shortest Stave in Attention: Enhancing Context Awareness of Large Language Models for Effective Tool Use}, + author={Yuhan Chen and Ang Lv and Ting-En Lin and Chang Heng Chen and Yuchuan Wu and Fei Huang and Yongbin Li and Rui Yan}, + journal={ArXiv}, + year={2023}, + volume={abs/2312.04455}, + url={https://api.semanticscholar.org/CorpusID:266053571} +} +``` + diff --git a/attention-buckets/base_rag/download_model.py b/attention-buckets/base_rag/download_model.py new file mode 100644 index 00000000..673becab --- /dev/null +++ b/attention-buckets/base_rag/download_model.py @@ -0,0 +1,4 @@ +import huggingface_hub +huggingface_hub.login("") +from huggingface_hub import snapshot_download +snapshot_download(repo_id="meta-llama/Llama-2-7b") \ No newline at end of file diff --git a/attention-buckets/base_rag/merge_result.py b/attention-buckets/base_rag/merge_result.py new file mode 100644 index 00000000..22ee355a --- /dev/null +++ b/attention-buckets/base_rag/merge_result.py @@ -0,0 +1,76 @@ +import os +import json +import argparse +import regex +import unicodedata +import string + + +def normalize_answer(s): + def remove_articles(text): + return regex.sub(r'\b(a|an|the)\b', ' ', text) + + def white_space_fix(text): + return ' '.join(text.split()) + + def lower(text): + return text.lower() + return white_space_fix(remove_articles(lower(s))) + + + +def main(args): + data_file = args.data_dir + args.data_name +'-test.jsonl' + # answer_file = args.answer_file #args.result_dir + args.data_name + '_doc_num' + str(args.num_doc) + answer_file = 'answer/nq_doc_num10(10000, 13000, 16000, 19000, 22000, 25000, 28000)' + base_list_file = answer_file +'/base_list.json' + if args.ngpu > 1: + f2 = open(base_list_file, 'w') + for i in range(args.ngpu): + base_list_file_tmp = answer_file +'/base_list'+'_'+str(i) + '.json' + f2_tmp = open(base_list_file_tmp).read() + f2.write(f2_tmp) + f2.close() + + # base_list_file = 'answer/webq_doc_num10/base_(10000,17000,18000,19000,20000,23000,25000).json' + f2 = open(base_list_file, 'r').readlines() + total = len(f2) + + true = 0 + with open(data_file) as fin: + data = json.load(fin) + # assert total == len(data) + for idx, input_example in enumerate(data): + gold_answer = [x.strip() for x in input_example["answers"]] + answer = json.loads(f2[idx])['answer'] + # print(answer) + # print(gold_answer) + + + for x in gold_answer: + if normalize_answer(x).lower() in normalize_answer(answer).lower(): + true += 1 + break + + + print(true) + print(total) + print(true/total) + +if __name__ == "__main__": + + parser = argparse.ArgumentParser() + parser.add_argument('--ckpt_dir', type=str, default='meta-llama/Llama-2-7b-chat-hf') + parser.add_argument('--model_type', type=str, default='llama') + parser.add_argument('--data_dir', type=str, default='../qa_dataset/') + parser.add_argument('--prompt_dir', type=str, default='prompts/qa.prompt') + parser.add_argument('--result_dir', type=str, default='answer/') + parser.add_argument('--answer_file', type=str, default='answer/') + parser.add_argument('--num_doc', type=int, default=10) + parser.add_argument('--bsz', type=int, default=1) + parser.add_argument('--data_name', type=str, default='nq') + parser.add_argument('--ngpu', type=int, default=1) + parser.add_argument('--chosen_base', type=int, default=10000) + args = parser.parse_args() + + main(args) diff --git a/attention-buckets/base_rag/prompts/closedbook_qa.prompt b/attention-buckets/base_rag/prompts/closedbook_qa.prompt new file mode 100644 index 00000000..1058d398 --- /dev/null +++ b/attention-buckets/base_rag/prompts/closedbook_qa.prompt @@ -0,0 +1,2 @@ +Question: {question} +Answer: diff --git a/attention-buckets/base_rag/prompts/kv_retrieval.prompt b/attention-buckets/base_rag/prompts/kv_retrieval.prompt new file mode 100644 index 00000000..67922a73 --- /dev/null +++ b/attention-buckets/base_rag/prompts/kv_retrieval.prompt @@ -0,0 +1,7 @@ +Extract the value corresponding to the specified key in the JSON object below. + +JSON data: +{formatted_kv_records} + +Key: "{key}" +Corresponding value: diff --git a/attention-buckets/base_rag/prompts/kv_retrieval_with_query_aware_contextualization.prompt b/attention-buckets/base_rag/prompts/kv_retrieval_with_query_aware_contextualization.prompt new file mode 100644 index 00000000..2f598a9b --- /dev/null +++ b/attention-buckets/base_rag/prompts/kv_retrieval_with_query_aware_contextualization.prompt @@ -0,0 +1,9 @@ +Extract the value corresponding to the specified key in the JSON object below. + +Key: "{key}" + +JSON data: +{formatted_kv_records} + +Key: "{key}" +Corresponding value: diff --git a/attention-buckets/base_rag/prompts/qa.prompt b/attention-buckets/base_rag/prompts/qa.prompt new file mode 100644 index 00000000..9a2dae34 --- /dev/null +++ b/attention-buckets/base_rag/prompts/qa.prompt @@ -0,0 +1,6 @@ +Write a high-quality answer for the given question using only the provided search results (some of which might be irrelevant). + +{search_results} + +Question: {question} +Answer: \ No newline at end of file diff --git a/attention-buckets/base_rag/prompts/qa_ordered_randomly.prompt b/attention-buckets/base_rag/prompts/qa_ordered_randomly.prompt new file mode 100644 index 00000000..bde0e37d --- /dev/null +++ b/attention-buckets/base_rag/prompts/qa_ordered_randomly.prompt @@ -0,0 +1,6 @@ +Write a high-quality answer for the given question using only the provided search results (some of which might be irrelevant). The search results are ordered randomly. + +{search_results} + +Question: {question} +Answer: \ No newline at end of file diff --git a/attention-buckets/base_rag/prompts/qa_with_query_aware_contextualization.prompt b/attention-buckets/base_rag/prompts/qa_with_query_aware_contextualization.prompt new file mode 100644 index 00000000..17bf88bb --- /dev/null +++ b/attention-buckets/base_rag/prompts/qa_with_query_aware_contextualization.prompt @@ -0,0 +1,8 @@ +Write a high-quality answer for the given question using only the provided search results (some of which might be irrelevant). + +Question: {question} + +{search_results} + +Question: {question} +Answer: diff --git a/attention-buckets/base_rag/test_nq_kl.py b/attention-buckets/base_rag/test_nq_kl.py new file mode 100644 index 00000000..54f38618 --- /dev/null +++ b/attention-buckets/base_rag/test_nq_kl.py @@ -0,0 +1,168 @@ +import argparse +import json +import os +import time + +import numpy as np +import tensor_parallel as tp +import torch +from tqdm import tqdm +from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig +from typing import List, Tuple +import torch.nn.functional as F + + + + +def load(ckpt_dir, model_type): + hub_token = "" + n_gpus = torch.cuda.device_count() + + if model_type == 'llama': + tokenizer = AutoTokenizer.from_pretrained(ckpt_dir, use_fast=False, padding_side="left", use_auth_token=hub_token) #'meta-llama/Llama-2-7b-chat-hf' + + model = AutoModelForCausalLM.from_pretrained(ckpt_dir, low_cpu_mem_usage = True, torch_dtype=torch.float16, use_auth_token=hub_token) + + tokenizer.pad_token_id = 0 if tokenizer.pad_token_id is None else tokenizer.pad_token_id + tokenizer.bos_token_id = 1 + else: + # however, tensor parallel for running falcon will occur bugs + tokenizer = AutoTokenizer.from_pretrained(ckpt_dir, use_fast=False, padding_side="left") + model = AutoModelForCausalLM.from_pretrained(ckpt_dir, device_map = 'balanced_low_0', torch_dtype=torch.bfloat16, trust_remote_code=True) + if tokenizer.pad_token_id is None: + if tokenizer.eos_token_id is not None: + tokenizer.pad_token_id = tokenizer.eos_token_id + else: + tokenizer.pad_token_id = 0 + + model.eval() + model.cuda() + + return model, tokenizer + +def get_nq_retrieval_prompt( + data: List[Tuple[str, str]], + key: str, + prompt_dir:str, + query_aware_contextualization: bool = False, + +): + if not data: + raise ValueError(f"Provided `data` must be truthy, got: {data}") + if not key: + raise ValueError(f"Provided `key` must be truthy, got: {key}") + # if len(data) != len(set([x["text"] for x in data])): + # raise ValueError(f"`data` has duplicate keys: {data}") + if len(data) < 2: + raise ValueError(f"Must have at least 2 items in data: {data}") + + with open(prompt_dir) as f: + prompt_template = f.read().rstrip("\n") + + # Format the KV data into a string + formatted_kv_records = "" + for index, record in enumerate(data): + # start_character = "" if index == 0 else " " + data_string = f'"Document (Title: {record["title"]})": "{record["text"]}"' + end_character = "\n" if index != len(data) - 1 else "" + formatted_kv_records += data_string + end_character #start_character + + + return prompt_template.format(search_results=formatted_kv_records, question=key) + +def batch_infer(model, tokenizer, args): + from xopen import xopen + from copy import deepcopy + + data_file = args.data_dir + args.data_name +'-test.jsonl' + answer_file = args.result_dir + args.data_name + '_doc_num' + str(args.num_doc) + '(10000, 13000, 16000, 19000, 22000, 25000, 28000)' + os.makedirs(answer_file, exist_ok=True) + np.random.seed(0) + torch.manual_seed(0) + base_list = [10000, 13000, 16000, 19000, 22000, 25000, 28000] + + with xopen(data_file) as fin: + # with open('ori_result') + num_doc = args.num_doc + data = json.load(fin) + + pre_true = 0 + true = 0 + model.eval() + if args.ngpu == 1: + base_list_file = answer_file +'/base_list.json' + sub_data = data + left = 0 + else: + base_list_file = answer_file +'/base_list'+'_'+str(args.flag) + '.json' + data_split = int(len(data)/args.ngpu) + left = args.flag * data_split + + if args.flag == args.ngpu-1: + sub_data = data[left:] + else: + sub_data = data[left:left+data_split] + + # chosen_data = [] + base_list_data = [] + # if os.path.exists(chosen_answer_file): + # f1 = open(chosen_answer_file, 'r') + # chosen_data = f1.readlines() + + if os.path.exists(base_list_file): + f2 = open(base_list_file, 'r') + base_list_data = f2.readlines() + + for idx, input_example in enumerate(tqdm(sub_data)): + left_docs = input_example["ctxs"] + question = input_example["question"] + gold_answer = [x.strip() for x in input_example["answers"]] + + + kv_prompt = get_nq_retrieval_prompt( + data=left_docs[:num_doc], key=question, prompt_dir = args.prompt_dir + ) + + inputs = tokenizer.encode(kv_prompt, return_tensors="pt", padding=True).cuda() + prompt_length = inputs.shape[1] + + + bsz = args.bsz + # model._set_best_base(base) # for single base + model.set_base_mean(base_list, bsz) + if idx < len(base_list_data): + answer = json.loads(base_list_data[idx])['answer'] + else: + with torch.no_grad(): + outputs = model.generate(inputs, max_new_tokens=100, do_sample=False, num_beams=1) + answer = tokenizer.batch_decode(outputs[:, prompt_length:], skip_special_tokens=True)[0] + with open(base_list_file, 'a') as f2: + f2.write(json.dumps({'id':idx+left, 'answer': answer})+'\n') + + + + + +def main(args): + model, tokenizer = load(args.ckpt_dir, args.model_type) + start_time = time.time() + batch_infer(model, tokenizer, args) + end_time = time.time() + print("total run time %.2f" % (end_time - start_time)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument('--ckpt_dir', type=str, default='meta-llama/Llama-2-7b-chat-hf') + parser.add_argument('--model_type', type=str, default='llama') + parser.add_argument('--data_dir', type=str, default='../qa_dataset/') + parser.add_argument('--prompt_dir', type=str, default='prompts/qa.prompt') + parser.add_argument('--result_dir', type=str, default='answer/') + parser.add_argument('--num_doc', type=int, default=None) + parser.add_argument('--bsz', type=int, default=1) + parser.add_argument('--data_name', type=str, default='nq') + parser.add_argument('--ngpu', type=int, default=1) + parser.add_argument('--flag', type=int, default=0) + parser.add_argument('--chosen_base', type=int, default=10000) + args = parser.parse_args() + + main(args) diff --git a/attention-buckets/basic.py b/attention-buckets/basic.py new file mode 100644 index 00000000..b6657555 --- /dev/null +++ b/attention-buckets/basic.py @@ -0,0 +1,541 @@ +import numpy as np +import matplotlib.pyplot as plt +from tqdm import tqdm +d = 128 +import json +from xopen import xopen +import random +from scipy.signal import argrelextrema +from matplotlib.pyplot import MultipleLocator +import seaborn as sns +import palettable + +def theta(i, base): + return base ** (-2 * i / d) + + +def qmkn(m, base): + result = 0 + for j in range(int(d / 2)): + result += 2*np.cos(m * theta(j, base)) + return result/np.sqrt(d) + +def diff_qmkn(m, base): + result = 0 + for j in range(int(d/2)): + result += -2 * theta(j, base) * np.sin(m * theta(j, base)) + return result/np.sqrt(d) + +def get_kv_retrieval_prompt( + data, + key: str, + query_aware_contextualization: bool = False, +): + with open('../lost-in-the-middle/src/lost_in_the_middle/prompts/kv_retrieval.prompt') as f: + prompt_template = f.read().rstrip("\n") + + # Format the KV data into a string + formatted_kv_records = "" + for index, record in enumerate(data): + start_character = "{" if index == 0 else " " + data_string = f'"{record[0]}": "{record[1]}"' + end_character = ",\n" if index != len(data) - 1 else "}" + formatted_kv_records += start_character + data_string + end_character + + return prompt_template.format(formatted_kv_records=formatted_kv_records, key=key) + +def get_tokenizer(): + from transformers import AutoTokenizer + tokenizer = AutoTokenizer.from_pretrained('meta-llama/Llama-2-7b-chat-hf', use_fast=False, padding_side="left", cache_dir='../llama-2-7b-hf') + tokenizer.pad_token_id = 0 if tokenizer.pad_token_id is None else tokenizer.pad_token_id + tokenizer.bos_token_id = 1 + return tokenizer + +def get_kv_sample(): + # tokenizer = get_tokenizer() + with xopen('../lost-in-the-middle/kv_retrieval_data/kv-retrieval-75_keys.jsonl') as fin: + data = fin.readlines() + idx = random.choice(range(len(data))) + input_example = json.loads(data[idx]) + key = input_example["key"] + value = input_example["value"] + original_kv_index = input_example["ordered_kv_records"].index([key, value]) + original_kv = input_example["ordered_kv_records"].pop(original_kv_index) + + ordered_kv_records = input_example["ordered_kv_records"][:5] + + ordered_kv_records.insert(12, original_kv) + + kv_prompt = get_kv_retrieval_prompt( + data=ordered_kv_records[:-1], key=key, + ) + print(kv_prompt) + print(value) + +def print_data_len(): + cnt = 0 + min_ = 20000 + max_ = 0 + with xopen('../kv-retrieval-75_keys.jsonl') as fin: + for line in fin: + input_example = json.loads(line) + key = input_example["key"] + value = input_example["value"] + original_kv_index = input_example["ordered_kv_records"].index([key, value]) + original_kv = input_example["ordered_kv_records"].pop(original_kv_index) + + ordered_kv_records = input_example["ordered_kv_records"][:25] + + ordered_kv_records.insert(12, original_kv) + + kv_prompt = get_kv_retrieval_prompt( + data=ordered_kv_records[:-1], key=key, + ) + + kv_prompts = kv_prompt.split( f'"{original_kv[1]}"')[0] + + prompt_input_pre = tokenizer.encode(kv_prompts) #, return_tensors="pt", padding=True + left = len(prompt_input_pre) + prompt_input_pre = tokenizer.encode(kv_prompts+f'"{original_kv[1]}"') #, return_tensors="pt", padding=True + right = len(prompt_input_pre) + prompt_input = tokenizer.encode(kv_prompt) + total = len(prompt_input) + if total-right > max_: + max_ = total-right + if total-right < min_: + min_ = total-right + + print(total) + cnt += 1 + print(min_) + print(max_) + + +def caculate_mid_mse(sample, target): + total = 0 + idx = 0 + idx_target = 0 + mse = 0.0 + while idx_target < len(target) and idx < len(sample)-1: + if sample[idx] <= target[idx_target] <= sample[idx+1]: + mse += np.power(target[idx_target] - (sample[idx] + sample[idx+1])/2, 2) + total += 1 + idx_target += 1 + elif sample[idx] > target[idx_target]: + idx_target += 1 + else: + idx += 1 + mse = np.sqrt(mse/total) if total != 0 else float('inf') + return mse + +def caculate_cover(peak, trough, cover_rand): + cover = 0 + dis = 0.0 + for i in peak: + for j in trough: + if abs(i-j) <= cover_rand: + cover += 1 + dis += np.power((i-j), 2) + return cover, dis + +def merge_peak(ori_peak, new_peak): + # new_peak = [k for k in new_peak if ori_peak[0] < k < ori_peak[-1]] + result = ori_peak + new_peak + result.sort() + return result + +def find_peak_points(mn, base): + all_f_values_short = np.vectorize(qmkn)(mn, base) + # plt.plot(mn, all_f_values_short) + peak_all = [k for k in argrelextrema(all_f_values_short, np.greater)[0]] + p = [all_f_values_short[k] for k in peak_all] + res = [] + node = max(p) + + while len(res) < 6: + if abs(all_f_values_short[peak_all[0]] - node) <= 0.001: + if len(res) < 1 or mn[peak_all[0]] - mn[res[-1]] > 50: + res.append(peak_all[0]) + index = min(peak_all[0]+50, peak_all[1]) + # if len(res) > 2: + # tmp = all_f_values_short[index: int(index+1.5*(res[-1] - res[-2]))] + # else: + tmp = all_f_values_short[index: index+500] + node = max(tmp) + peak_all.pop(0) + else: + peak_all.pop(0) + mn = [mn[k] for k in res] + # plt.plot(mn, np.vectorize(qmkn)(mn, base), marker='o') + # plt.savefig('test3.png') + return mn + +def find_trough_points(mn, base): + all_f_values_short = np.vectorize(qmkn)(mn, base) + # plt.plot(mn[:-500], all_f_values_short[:-500]) + peak_all = [k for k in argrelextrema(all_f_values_short, np.less)[0]] + p = [all_f_values_short[k] for k in peak_all] + res = [] + node = min(p) + while len(res) < 6: + if abs(all_f_values_short[peak_all[-1]] - node) <= 0.001: + if len(res) < 1 or res[-1] - peak_all[-1] > 60: + res.append(peak_all[-1]) + index = min(peak_all[-1]-50, peak_all[-2]) + if index <=0: + break + tmp = all_f_values_short[:index] + node = min(tmp) + peak_all.pop(-1) + else: + peak_all.pop(-1) + # prinst(res) + mn = [mn[k] for k in res][::-1] + # plt.plot(mn, np.vectorize(qmkn)(mn, base), marker='o') + # plt.savefig('test3.png') + return mn + + + +def select_cover_max(mn, base_low, base_high, base_gap, final_base, trough, peak, cover_rand): + max_cover = 0 + min_dis = float('inf') + chosen_base = None + for base in range(base_low, base_high+1, base_gap): + if base in final_base: + continue + peak_ = find_peak_points(mn, base) + trough_ = find_trough_points(mn, base) + cover1, dis1 = caculate_cover(peak_, trough, cover_rand) + cover2, dis2 = caculate_cover(peak, trough_, cover_rand) + cover = cover1 + cover2 + dis = (dis1 + dis2)/cover if cover != 0 else float('inf') + if cover > max_cover: + max_cover = cover + min_dis = dis + chosen_base = base + elif cover == max_cover: + if dis < min_dis: + min_dis = dis + chosen_base = base + return chosen_base, max_cover, min_dis + +def fliter(peak, trough, rand): + # peak_ = [] + # for k in peak: + # flag = 0 + # for i in range(rand): + # if k + i in trough or k - i in trough: + # flag = 1 + # if flag == 0: + # peak_.append(k) + # trough_ = [] + # for k in trough: + # flag = 0 + # for i in range(rand): + # if k + i in peak or k - i in peak: + # flag = 1 + # if flag == 0: + # trough_.append(k) + peak_ = [k for k in peak if k not in trough ] + trough_ = [k for k in trough if k not in peak] + return peak_, trough_ + + +def base_choose_method1(): + word_low = 1000 + word_high = 4090 + total_base_num = 6 + # new_base_num = total_base_num - 2 + base_gap = 500 + base_low = 10000 + base_high = 30000 + ori_base = 10000 + rand = 1 + cover_rand = 3 + final_base = [10000, 18000, 19000] + # final_base = [10000, 17500, 18000, 19000, 20000, 25000] + + + mn = [k for k in range(word_low, word_high+1)] + + if len(final_base) == 0: + total_max_cover = 0 + total_min_dis = float('inf') + for ori_base in range(base_low, base_high+1, base_gap): + trough = find_trough_points(mn, ori_base) + peak = find_peak_points(mn, ori_base) + tmp_base = [] + chosen_base, max_cover, min_dis = select_cover_max(mn, ori_base+base_gap, base_high, base_gap, tmp_base, trough, peak, cover_rand) + if max_cover > total_max_cover: + total_max_cover = max_cover + final_base = [ori_base, chosen_base] + elif max_cover == total_max_cover: + if min_dis < total_min_dis: + total_min_dis = min_dis + final_base = [ori_base, chosen_base] + print(total_max_cover) + print(final_base) + + trough = find_trough_points(mn, final_base[0]) + peak = find_peak_points(mn, final_base[0]) + for i in range(1, len(final_base)): + trough_chosen = find_trough_points(mn, final_base[i]) + peak_chosen = find_peak_points(mn, final_base[i]) + peak = merge_peak(peak, peak_chosen) + trough = merge_peak(trough, trough_chosen) + peak, trough = fliter(peak, trough, rand) + + for time in range(total_base_num - len(final_base)): + chosen_base, max_cover, min_dis = select_cover_max(mn, base_low, base_high, base_gap, final_base, trough, peak, cover_rand) + print(max_cover) + print(chosen_base) + final_base.append(chosen_base) + peak_chosen = find_peak_points(mn, chosen_base) + trough_chosen = find_trough_points(mn, chosen_base) + peak = merge_peak(peak, peak_chosen) + trough = merge_peak(trough, trough_chosen) + peak, trough = fliter(peak, trough, rand) + print(peak) + print(trough) + + final_base.sort() + print(final_base) + print(trough) + print(peak) + + +def plt_base_list(final_base): + base_list = final_base#[10000, 12000, 18000, 28000, 30000] + mn = [k for k in range(900, 4096, 1)] + for base in base_list: + plt.plot(mn, np.vectorize(qmkn)(mn,base)) + plt.savefig('test3.png') + +def find_high_points(mn, base, ratio=1.5): + all_f_values_short = np.vectorize(qmkn)(mn, base) + last_mn = [k for k in mn if qmkn(k, base)/all_f_values_short.mean() > ratio] + return set(last_mn) + + +def plot_introduction(): + plt.figure(figsize=(7,8)) + m_values_short = [1, 5, 10, 15, 20, 25, 30, 35] + f_values_short = [100, 72, 88, 72, 78, 48, 90, 92] + axs0 = plt.subplot(211) + axs0.plot(m_values_short, f_values_short, marker='o', linewidth=3.5, markersize='10', markerfacecolor='none', markeredgewidth='3', + color='yellowgreen', alpha=0.6) + axs0.set_title('(a)',fontsize=20) + axs0.set_xlabel('Target key-value pair index',fontsize=18,labelpad=10) + axs0.set_ylabel('Accuary',fontsize=18) + plt.xlim(-2,38) + plt.ylim(35,110) + x_major_locator=MultipleLocator(5) + axs0.xaxis.set_major_locator(x_major_locator) + + m_values_short = [k for k in range(-1,3005, 1)] + f_values_short = np.vectorize(qmkn)(m_values_short,10000) + axs1 = plt.subplot(212) + axs1.plot(m_values_short, f_values_short,linewidth=2, color='steelblue', alpha=0.8) + axs1.set_title('(b)',fontsize=20) + axs1.set_xlabel('Relative token position',fontsize=18,labelpad=10) + axs1.set_ylabel('Attention score before softmax',fontsize=16, labelpad=5) + axs0.tick_params(labelsize=15, axis="both", which="major", width=1, length=5) + axs1.tick_params(labelsize=15) + # x_major_locator=MultipleLocator(250) + # axs1.xaxis.set_major_locator(x_major_locator) + # # plt.legend() + # fig, axs = plt.subplots(2,1, figsize=(8,10)) + # plt.ylim(40,110) + # axs[1].plot(m_values_short, f_values_short) + # axs[1].set_title('(b)',fontsize=20) + # axs[1].set_xlabel('Distance betwween query and key tokens',fontsize=20,labelpad=10) + # axs[1].set_ylabel('Attention score before softmax',fontsize=16) + # # plt.legend() + + # m_values_short = [1, 5, 10, 15, 20, 25, 30, 35] + # f_values_short = [100, 72, 88, 72, 78, 48, 90, 92] + + # axs[0].plot(m_values_short, f_values_short, marker='s',linewidth=3.0, markersize='12',color='olivedrab') + # axs[0].set_title('(a)',fontsize=20) + # axs[0].set_xlabel('Target key-value pair index',fontsize=20,labelpad=10) + # axs[0].set_ylabel('Accuary',fontsize=18) + # # # plt.legend() + # # plt.savefig('test4.png') + # axs[0].tick_params(labelsize=15, axis="both", which="major", width=1, length=5) + # axs[1].tick_params(labelsize=15) + # plt.tight_layout() + # axs1.grid(True) + axs0.yaxis.grid(color='lightgray', linestyle='--') + bwith = 1.5 #边框宽度设置为2 + # axs0.set_facecolor('aliceblue') + # axs1.set_facecolor('aliceblue') + # #设置边框 + axs0.spines['bottom'].set_linewidth(bwith)#图框下边 + axs0.spines['left'].set_linewidth(bwith)#图框左边 + axs0.spines['top'].set_linewidth(bwith)#图框上边 + axs0.spines['right'].set_linewidth(bwith)#图框右边 + axs1.spines['bottom'].set_linewidth(bwith)#图框下边 + axs1.spines['left'].set_linewidth(bwith)#图框左边 + axs1.spines['top'].set_linewidth(bwith)#图框上边 + axs1.spines['right'].set_linewidth(bwith)#图框右边 + plt.tight_layout() + # plt.savefig('test3.png',dpi=100) + plt.savefig('test3.pdf') + + +def plot_base_selection_sample(): + import mpl_toolkits.axisartist as axisartist + #创建画布 + fig = plt.figure(figsize=(6, 4)) + #使用axisartist.Subplot方法创建一个绘图区对象ax + ax = axisartist.Subplot(fig, 111) + #将绘图区对象添加到画布中 + fig.add_axes(ax) + base_list = [10000, 20000, 30000] + mn = [k for k in range(1, 3000, 1)] + for base in base_list: + plt.plot(mn, np.vectorize(qmkn)(mn,base)) + #给x坐标轴加上箭头 + ax.axis["bottom"].set_axisline_style("->", size = 1.0) + #添加y坐标轴,且加上箭头 + ax.axis["left"].set_axisline_style("->", size = 1.0) + #设置x、y轴上刻度显示方向 + base_list = [10000, 20000, 30000] + ax.axis['top'].set_visible(False) + ax.axis['right'].set_visible(False) + plt.xticks([]) + plt.yticks([]) + ax = plt.gca() + bwith = 2 #边框宽度设置为2 + + # #设置边框 + ax.spines['bottom'].set_linewidth(bwith)#图框下边 + ax.spines['left'].set_linewidth(bwith)#图框左边 + plt.savefig('test3.png') + + +def plot_base_selection(): + # 加图例 + # from scipy.interpolate import make_interp_spline + plt.figure(figsize=(12,5)) + axs0 = plt.subplot(121) + base_list = [10000, 20000] #[10000, 15000, 18000, 19000, 20000] + mn = np.array([k for k in range(1400, 2100, 1)]) + # mn = np.linspace(1500,2000, 10000) + x_sm = mn + + base = 18000 + # peak = find_trough_points(mn, base) + # print(peak) + y_sm0 = np.vectorize(qmkn)(mn,base) + # y_sm = make_interp_spline(mn, np.vectorize(qmkn)(mn,base))(x_sm) + axs0.plot(x_sm, y_sm0, alpha=0.6, color='#1f77b4', label = 'candidate 1') + axs0.scatter([1690,1805], np.vectorize(qmkn)([1690,1805], base), color='#1f77b4')#[1451,1549,1690,1805,1970],1970, 2103 + axs0.set_title('(a)',fontsize=16) + i = 0 + + + # peak = find_peak_points(mn, base) + # print(peak) + buff1 = 6 + buff2 = 10 + # trough = find_peak_points(mn, 10000) + # print(trough) + # trough = find_trough_points(mn, 20000) + # print(trough) + # plt.scatter(trough, np.vectorize(qmkn)(trough, base))W + y_sm1 = np.vectorize(qmkn)(mn,10000) + y_sm2 = np.vectorize(qmkn)(mn,20000) + # y_sm = make_interp_spline(mn, np.vectorize(qmkn)(mn,base))(x_sm) + axs0.plot(x_sm, y_sm1+buff1, alpha=0.6, color='#8467bd', label = '$\mathcal{B}_{c} $') + axs0.plot(x_sm, y_sm2+buff2, alpha=0.6, color='#2ca02c', label = 'candidate 2') + i += 1 + MIN = min(min(y_sm0), min(y_sm1),min(y_sm2)) + MAX = max(max(y_sm0),max(y_sm1),max(y_sm2)) + axs0.scatter([1707,1835], np.vectorize(qmkn)([1707,1835], 10000)+buff1, color='#8467bd') #[1707,1835,1970],1970,2118] + axs0.scatter([1798,1882], np.vectorize(qmkn)([1798,1882], 20000)+buff2, color='#2ca02c') #[1540,1613,1798,1882,2098],2098, 2197] + + axs0.set_ylim((MIN-3, MAX+13)) + axs0.set_yticks([]) + axs0.legend(loc=3) + axs1 = plt.subplot(122) + base_list = [17500, 18000, 19000, 20000, 10000, 25000] #[10000, 15000,17500, 18000, 19000, 20000] + mn = [k for k in range(900, 4200, 1)] + i = 0 + for base in base_list: + + buff = 3.9*i + if base == 10000: + buff += 0.6 + axs1.plot(mn, np.vectorize(qmkn)(mn,base)+buff, alpha=0.8, label = str(base)) + i += 1 + axs1.set_yticks([]) + axs1.legend(loc=3) + axs0.set_xlabel('Relative token position',fontsize=14,labelpad=10) + axs1.set_xlabel('Relative token position',fontsize=14,labelpad=10) + axs1.set_title('(b)',fontsize=16) + plt.tight_layout() + # ax = plt.gca() + # ax.axes.yaxis.set_ticklabels([]) + # plt.grid() + # plt.grid(color='lightgray', linestyle='--') + # plt.savefig('test4.png',dpi=1000) + plt.savefig('test4.pdf') + + +def plot_ablation_heat(): + f = [float(k.strip()) for k in open('heat.txt').readlines()] + n = len(f) + matrix = np.random.random((n, n)) + for i in range(n): + for j in range(n): + matrix[i][j] = (f[i] - f[j]) + + ax = sns.heatmap(matrix, annot=True, annot_kws={"size":6.5}, cmap='summer_r', + vmin=-0.9,vmax=0.9, center=0.05, + cbar=False, + xticklabels=['1.00','1.20','1.40', '1.50', '1.65', '1.80', '1.90', '2.00','2.25','2.50', '3.00', '$\mathcal{B}_{A.S.1}$ ','$\mathcal{B}_{A.S.2}$ ','$\mathcal{B}_{c1} $','$\mathcal{B}_{c2} $','$\mathcal{B}_{c3} $'] , #x轴方向刻度标签开关、赋值,可选“auto”, bool, list-like(传入列表), or int, + yticklabels=['1.00','1.20','1.40', '1.50', '1.65', '1.80', '1.90', '2.00','2.25','2.50', '3.00', '$\mathcal{B}_{A.S.1}$ ','$\mathcal{B}_{A.S.2}$ ','$\mathcal{B}_{c1} $','$\mathcal{B}_{c2} $','$\mathcal{B}_{c3} $']) + #['10000','12000','14000', '15000', '16500', '18000', '19000', '20000','22500','25000', '30000', '$\mathcal{B}_{rand1} $','$\mathcal{B}_{rand2} $','$\mathcal{B}_{c1} $','$\mathcal{B}_{c2} $','$\mathcal{B}_{c3} $'] + # cbar = ax.collections[0].colorbar + # cbar.ax.tick_params(labelsize=9) + # plt.tight_layout() + plt.xticks(fontsize=9) + plt.yticks(fontsize=9) + # plt.savefig('test.png',dpi=1000) + plt.savefig('test.pdf') + +if __name__ == '__main__': + print('run code') + # plot_ablation() + # plot_introduction() + # get_kv_sample() + # plot_introduction() + # plot_base_selection() + # word_low = 1200 + # word_high = 4090 + # l = [k for k in range(word_low, word_high+1)] + # # base = 10500 + # # find_trough_points(mn, base) + # for base in range(10000, 30000, 500): + # l = [k for k in range(word_low, word_high+1)] + # res = find_peak_points(l, base) + # base_choose_method1() + # ## method1 peak+trough cover + # # gap 2000 + # base_list = [10000, 18000, 20000, 22000, 24000, 26000, 30000] + # # gap 1000 + # base_list = [10000, 17000, 18000, 19000, 20000, 23000, 25000] + # # gap 500 + # base_list = [10000, 17500, 18000, 19000, 20000, 22500, 25000] + # ## method2 high_points + # base_list = [10000, 11000, 12000, 13000, 14000, 15000, 16000] + + # plt_base_list(base_list) + + # base_list = [10000, 20000, 30000] + # mn = [k for k in range(1, 3000, 1)] + # for base in base_list: + # plt.plot(mn, np.vectorize(qmkn)(mn,base)) + # plt.savefig('test3.png') \ No newline at end of file diff --git a/attention-buckets/inference/config.py b/attention-buckets/inference/config.py new file mode 100644 index 00000000..a3ecdbc2 --- /dev/null +++ b/attention-buckets/inference/config.py @@ -0,0 +1,8 @@ +base_list = [10000, 17500, 18000, 19000, 20000, 25000] +bsz = 2 # Number of parallel, adjust for memory size +''' +bsz >= len(base_list) means all parallel, +for example: +if base_list = [10000, 17500, 18000, 19000, 20000, 25000] +bsz = 6 same to bsz = 8 +''' \ No newline at end of file diff --git a/attention-buckets/inference/utils.py b/attention-buckets/inference/utils.py new file mode 100644 index 00000000..8ef2edb6 --- /dev/null +++ b/attention-buckets/inference/utils.py @@ -0,0 +1,279 @@ +import gc +import abc +import numpy as np +import math +from typing import Iterable +import torch +from transformers.generation.logits_process import ( + LogitsProcessorList, + RepetitionPenaltyLogitsProcessor, + TemperatureLogitsWarper, + TopKLogitsWarper, + TopPLogitsWarper, +) +from config import base_list, bsz + +# For DFS +def softmax_bias(answers,temperature=1): + + sums = 0.0 + answers = [ 10**((cont/temperature)/400) for cont in answers] + for cont in answers: + assert type(cont) == float or type(cont) == int + sums += cont + answers = [ cont/sums for cont in answers] + return np.array(answers) + +def compute_epsilon_new_node(p_new_node): + ''' + 根据公式换算delta + ''' + delta = 400 * math.log10(p_new_node /(1-p_new_node)) + return 1000 + delta + +# For prediction parsing, into ReACT format +def react_parser(string): + thought = [string[string.find("Thought: ") + len("Thought: "): string.find("\nAction: ")]] + action = [string[string.find("Action: ") + len("Action: "): string.find("\nAction Input: ")]] + action_input = [string[string.find("Action Input: ") + len("Action Input: "):]] + return thought[0], action[0], action_input[0] + +# For toolllama's predictions +def prepare_logits_processor( + temperature: float, repetition_penalty: float, top_p: float, top_k: int +) -> LogitsProcessorList: + processor_list = LogitsProcessorList() + # TemperatureLogitsWarper doesn't accept 0.0, 1.0 makes it a no-op so we skip two cases. + if temperature >= 1e-5 and temperature != 1.0: + processor_list.append(TemperatureLogitsWarper(temperature)) + if repetition_penalty > 1.0: + processor_list.append(RepetitionPenaltyLogitsProcessor(repetition_penalty)) + if 1e-8 <= top_p < 1.0: + processor_list.append(TopPLogitsWarper(top_p)) + if top_k > 0: + processor_list.append(TopKLogitsWarper(top_k)) + return processor_list + +@torch.inference_mode() +def generate_stream( + model, tokenizer, params, device, context_len=8192, stream_interval=2, force_generate=False +): + prompt = params["prompt"] + len_prompt = len(prompt) + + # Attention_buckets + # bsz = 2 + model.cuda() + model.eval() + # base_list = [10000, 15000, 17500, 18000, 19000, 20000] #[10000, 17500, 18000, 19000, 20000, 25000] + model.set_base_mean(base_list, bsz) + temperature = float(params.get("temperature", 1.0)) + repetition_penalty = float(params.get("repetition_penalty", 1.0)) + top_p = float(params.get("top_p", 1.0)) + top_k = int(params.get("top_k", -1)) # -1 means disable + max_new_tokens = int(params.get("max_new_tokens", 256)) + stop_str = params.get("stop", None) + echo = bool(params.get("echo", True)) + stop_token_ids = params.get("stop_token_ids", None) or [] + stop_token_ids.append(tokenizer.eos_token_id) + + logits_processor = prepare_logits_processor( + temperature, repetition_penalty, top_p, top_k + ) + + input_ids = tokenizer(prompt).input_ids + input_echo_len = len(input_ids) + output_ids = list(input_ids) + + if model.config.is_encoder_decoder: + max_src_len = context_len + else: + max_src_len = context_len - max_new_tokens - 8 + + input_ids = input_ids[-max_src_len:] + + if model.config.is_encoder_decoder: + encoder_output = model.encoder( + input_ids=torch.as_tensor([input_ids], device=device) + )[0] + start_ids = torch.as_tensor( + [[model.generation_config.decoder_start_token_id]], + dtype=torch.int64, + device=device, + ) + + past_key_values = out = None + for i in range(max_new_tokens): + if i == 0: + if model.config.is_encoder_decoder: + out = model.decoder( + input_ids=start_ids, + encoder_hidden_states=encoder_output, + use_cache=True, + ) + logits = model.lm_head(out[0]) + else: + with torch.no_grad(): + out = model(torch.as_tensor([input_ids], device=device), use_cache=True) + logits = out.logits + past_key_values = out.past_key_values + else: + if model.config.is_encoder_decoder: + out = model.decoder( + input_ids=torch.as_tensor([[token]], device=device), + encoder_hidden_states=encoder_output, + use_cache=True, + past_key_values=past_key_values, + ) + + logits = model.lm_head(out[0]) + else: + with torch.no_grad(): + out = model( + input_ids=torch.as_tensor([[token]], device=device), + use_cache=True, + past_key_values=past_key_values, + ) + logits = out.logits + past_key_values = out.past_key_values + logit_ = logits[:, -1, :] + # logit_ = logits + if logits_processor: + if repetition_penalty > 1.0: + tmp_output_ids = torch.as_tensor([output_ids], device=logits.device) + else: + tmp_output_ids = None + last_token_logits = logits_processor(tmp_output_ids, logit_)[0] + else: + last_token_logits = logit_ + + if device == "mps": + # Switch to CPU by avoiding some bugs in mps backend. + last_token_logits = last_token_logits.float().to("cpu") + + if temperature < 1e-5 or top_p < 1e-8: # greedy + token = int(torch.argmax(last_token_logits)) + else: + probs = torch.softmax(last_token_logits, dim=-1) + token = int(torch.multinomial(probs, num_samples=1)) + + output_ids.append(token) + + if token in stop_token_ids: + stopped = True + else: + stopped = False + if i == 0 and force_generate: + stopped = False + if i == max_new_tokens - 1 or stopped: + if echo: + tmp_output_ids = output_ids + rfind_start = len_prompt + else: + tmp_output_ids = output_ids[input_echo_len:] + rfind_start = 0 + + output = tokenizer.decode( + tmp_output_ids, + skip_special_tokens=True, + spaces_between_special_tokens=False, + ) + if stop_str: + if isinstance(stop_str, str): + pos = output.rfind(stop_str, rfind_start) + if pos != -1: + output = output[:pos] + stopped = True + elif isinstance(stop_str, Iterable): + for each_stop in stop_str: + pos = output.rfind(each_stop, rfind_start) + if pos != -1: + output = output[:pos] + stopped = True + break + else: + raise ValueError("Invalid stop field type.") + + yield { + "text": output, + "usage": { + "prompt_tokens": input_echo_len, + "completion_tokens": i, + "total_tokens": input_echo_len + i, + }, + "finish_reason": None, + } + + if stopped: + break + + # finish stream event, which contains finish reason + if i == max_new_tokens - 1: + finish_reason = "length" + elif stopped: + finish_reason = "stop" + else: + finish_reason = None + + + yield { + "text": output, + "usage": { + "prompt_tokens": input_echo_len, + "completion_tokens": i, + "total_tokens": input_echo_len + i, + }, + "finish_reason": finish_reason, + } + + # clean + del past_key_values, out + gc.collect() + torch.cuda.empty_cache() + +# For IO presentation +class ChatIO(abc.ABC): + @abc.abstractmethod + def prompt_for_input(self, role: str) -> str: + """Prompt for input from a role.""" + + @abc.abstractmethod + def prompt_for_output(self, role: str): + """Prompt for output from a role.""" + + @abc.abstractmethod + def stream_output(self, output_stream): + """Stream output.""" + + @abc.abstractmethod + def return_output(self, output_stream): + """Return output.""" + +class SimpleChatIO(ChatIO): + def prompt_for_input(self, role) -> str: + return input(f"{role}: ") + + def prompt_for_output(self, role: str): + print(f"{role}: ", end="", flush=True) + + def stream_output(self, output_stream): + pre = 0 + for outputs in output_stream: + output_text = outputs["text"] + output_text = output_text.strip().split(" ") + now = len(output_text) - 1 + if now > pre: + print(" ".join(output_text[pre:now]), end=" ", flush=True) + pre = now + print(" ".join(output_text[pre:]), flush=True) + return " ".join(output_text) + + def return_output(self, output_stream): + pre = 0 + for outputs in output_stream: + output_text = outputs["text"] + output_text = output_text.strip().split(" ") + now = len(output_text) - 1 + if now > pre: + pre = now + return " ".join(output_text) diff --git a/attention-buckets/modeling_llama.py b/attention-buckets/modeling_llama.py new file mode 100644 index 00000000..9f9b390c --- /dev/null +++ b/attention-buckets/modeling_llama.py @@ -0,0 +1,2498 @@ +# coding=utf-8 +# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. +# +# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX +# and OPT implementations in this library. It has been modified from its +# original forms to accommodate minor architectural differences compared +# to GPT-NeoX and OPT used by the Meta AI team that trained the model. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" PyTorch LLaMA model.""" +import math +import random +from typing import List, Optional, Tuple, Union +# from torch.distributions import Categorical #, kl +import torch +import torch.nn.functional as F +import torch.utils.checkpoint +from torch import nn +from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss + +from ...activations import ACT2FN +from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast +from ...modeling_utils import PreTrainedModel +from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings +from .configuration_llama import LlamaConfig + + +logger = logging.get_logger(__name__) + +_CONFIG_FOR_DOC = "LlamaConfig" + + +# Copied from transformers.models.bart.modeling_bart._make_causal_mask +def _make_causal_mask( + input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0 +): + """ + Make causal mask used for bi-directional self-attention. + """ + bsz, tgt_len = input_ids_shape + mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device) + mask_cond = torch.arange(mask.size(-1), device=device) + mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) + mask = mask.to(dtype) + + if past_key_values_length > 0: + mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1) + return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length) + + +# Copied from transformers.models.bart.modeling_bart._expand_mask +def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): + """ + Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. + """ + bsz, src_len = mask.size() + tgt_len = tgt_len if tgt_len is not None else src_len + + expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) + + inverted_mask = 1.0 - expanded_mask + + return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min) + + +class LlamaRMSNorm(nn.Module): + def __init__(self, hidden_size, eps=1e-6): + """ + LlamaRMSNorm is equivalent to T5LayerNorm + """ + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + self.variance_epsilon = eps + + def forward(self, hidden_states): + input_dtype = hidden_states.dtype + hidden_states = hidden_states.to(torch.float32) + variance = hidden_states.pow(2).mean(-1, keepdim=True) + hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) + return self.weight * hidden_states.to(input_dtype) + + +class LlamaRotaryEmbedding(torch.nn.Module): + def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None): + super().__init__() + + self.dim = dim + self.max_position_embeddings = max_position_embeddings + self.base = base + inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)) + self.register_buffer("inv_freq", inv_freq) + + # self.max_seq_len_cached = 0 + # Build here to make `torch.jit.trace` work. + self._set_cos_sin_cache( + seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype() + ) + + def _set_base(self, new_base): + self.base = new_base + self.inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(self.inv_freq.device) / self.dim)) + self._set_cos_sin_cache( + seq_len=self.max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype() + ) + + def _set_cos_sin_cache(self, seq_len, device, dtype): + self.max_seq_len_cached = seq_len + ############leon############ + # base_list = [0, 2470.703125, 4521.484375, 6152.34375, 7539.0625, 8476.5625, 9375.0, 10117.1875, 10781.25, 11523.4375, 12382.8125, 12421.875, 13593.75, 13359.375, 14531.25, 14843.75, 14921.875, 15703.125, 15625.0, 16054.6875, 16796.875, 17031.25, 16718.75, 17500.0, 17812.5, 18125.0, 17773.4375, 18398.4375, 18906.25, 19375.0, 19296.875, 18984.375, 19531.25, 20078.125, 20351.5625, 20781.25, 20625.0, 20312.5, 20703.125, 21093.75, 21328.125, 21875.0, 22031.25, 21718.75, 21484.375, 21757.8125, 22343.75, 22421.875, 22734.375, 23125.0, 23359.375, 23281.25, 22812.5, 22734.375, 23281.25, 23437.5, 23593.75, 23984.375, 24335.9375, 24570.3125, 24921.875, 24687.5, 24140.625, 23984.375, 24531.25, 24687.5, 24765.625, 24921.875, 25312.5, 25703.125, 25859.375, 26171.875, 26562.5, 26406.25, 25937.5, 25390.625, 25859.375, 26015.625, 26171.875, 26093.75, 26093.75] + # base_list = base_list[0::2] + # try: + # self.base = base_list[seq_len // 100] + # except: + # self.base = base_list[-1] + # self.inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(self.inv_freq.device) / self.dim)) + ############leon############ + t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) + + freqs = torch.einsum("i,j->ij", t, self.inv_freq) + # Different from paper, but it uses a different permutation in order to obtain the same calculation + emb = torch.cat((freqs, freqs), dim=-1) + self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False) + self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False) + + def forward(self, x, seq_len=None): + + # x: [bs, num_attention_heads, seq_len, head_size] + if seq_len > self.max_seq_len_cached: + # assert 1==0 + # if seq_len == 1: + # self._set_cos_sin_cache(seq_len=self.max_seq_len_cached+1, device=x.device, dtype=x.dtype) + # else: + self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype) + return ( + self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype), + self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype), + ) + + +class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding): + """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev""" + + def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0): + self.scaling_factor = scaling_factor + super().__init__(dim, max_position_embeddings, base, device) + + def _set_cos_sin_cache(self, seq_len, device, dtype): + self.max_seq_len_cached = seq_len + t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) + t = t / self.scaling_factor + + freqs = torch.einsum("i,j->ij", t, self.inv_freq) + # Different from paper, but it uses a different permutation in order to obtain the same calculation + emb = torch.cat((freqs, freqs), dim=-1) + self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False) + self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False) + + +class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding): + """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla""" + + def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0): + self.scaling_factor = scaling_factor + super().__init__(dim, max_position_embeddings, base, device) + + def _set_cos_sin_cache(self, seq_len, device, dtype): + self.max_seq_len_cached = seq_len + + if seq_len > self.max_position_embeddings: + base = self.base * ( + (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1) + ) ** (self.dim / (self.dim - 2)) + inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)) + self.register_buffer("inv_freq", inv_freq) + + t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) + + freqs = torch.einsum("i,j->ij", t, self.inv_freq) + # Different from paper, but it uses a different permutation in order to obtain the same calculation + emb = torch.cat((freqs, freqs), dim=-1) + self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False) + self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False) + + +def rotate_half(x): + """Rotates half the hidden dims of the input.""" + x1 = x[..., : x.shape[-1] // 2] + x2 = x[..., x.shape[-1] // 2 :] + return torch.cat((-x2, x1), dim=-1) + + +def apply_rotary_pos_emb(q, k, cos, sin, position_ids, past_key_values_length=0, flip_sin=False): + # The first two dimensions of cos and sin are always 1, so we can `squeeze` them. + # cos = cos.squeeze(1).squeeze(0) # [bsz, seq_len, dim] + # sin = sin.squeeze(1).squeeze(0) # [bsz, seq_len, dim] + # cos = cos[:, position_ids].unsqueeze(1) # [bs, 1, seq_len, dim] + # sin = sin[:, position_ids].unsqueeze(1) # [bs, 1, seq_len, dim] + cos = cos.squeeze(1) # [bsz, seq_len, dim] + sin = sin.squeeze(1) # [bsz, seq_len, dim] + q_cos = cos[:, position_ids] # [bs, 1, seq_len, dim] + q_sin = sin[:, position_ids] # [bs, 1, seq_len, dim] + if past_key_values_length != 0: + seq_length = position_ids.shape[-1] + past_key_values_length + key_positon_ids = torch.arange( + 0, seq_length, dtype=torch.long, device=position_ids.device + ) + key_position_ids = key_positon_ids.unsqueeze(0).view(-1, seq_length) + k_cos = cos[:, key_position_ids] + k_sin = sin[:, key_position_ids] + else: + k_cos = q_cos + k_sin = q_sin + # if flip_sin: + # q_sin *= -1 + # k_sin *= -1 + q_embed = (q * q_cos) + (rotate_half(q) * q_sin) + k_embed = (k * k_cos) + (rotate_half(k) * k_sin) + return q_embed, k_embed + + + +class LlamaMLP(nn.Module): + def __init__(self, config): + super().__init__() + self.pretraining_tp = config.pretraining_tp + self.hidden_size = config.hidden_size + self.intermediate_size = config.intermediate_size + self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) + self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) + self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) + self.act_fn = ACT2FN[config.hidden_act] + + def forward(self, x): + if self.pretraining_tp > 1: + slice = self.intermediate_size // self.pretraining_tp + gate_proj_slices = self.gate_proj.weight.split(slice, dim=0) + up_proj_slices = self.up_proj.weight.split(slice, dim=0) + down_proj_slices = self.down_proj.weight.split(slice, dim=1) + + gate_proj = torch.cat([F.linear(x, gate_proj_slices[i]) for i in range(self.pretraining_tp)], dim=-1) + up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.pretraining_tp)], dim=-1) + + intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2) + down_proj = [F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.pretraining_tp)] + down_proj = sum(down_proj) + else: + down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) + + return down_proj + + + +def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: + """ + This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, + num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) + """ + batch, num_key_value_heads, slen, head_dim = hidden_states.shape + if n_rep == 1: + return hidden_states + hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) + return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) + + +class LlamaAttention(nn.Module): + """Multi-headed attention from 'Attention Is All You Need' paper""" + + def __init__(self, config: LlamaConfig): + super().__init__() + self.config = config + self.hidden_size = config.hidden_size + self.num_heads = config.num_attention_heads + self.head_dim = self.hidden_size // self.num_heads + self.num_key_value_heads = config.num_key_value_heads + self.num_key_value_groups = self.num_heads // self.num_key_value_heads + self.pretraining_tp = config.pretraining_tp + self.max_position_embeddings = config.max_position_embeddings + self.set_best_base = True + self.best_base = 10000 + + if (self.head_dim * self.num_heads) != self.hidden_size: + raise ValueError( + f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}" + f" and `num_heads`: {self.num_heads})." + ) + self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False) + self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False) + self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False) + self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False) + self._init_rope() + + + def _init_rope(self): + if self.config.rope_scaling is None: + self.rotary_emb = LlamaRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings) + else: + scaling_type = self.config.rope_scaling["type"] + scaling_factor = self.config.rope_scaling["factor"] + if scaling_type == "linear": + self.rotary_emb = LlamaLinearScalingRotaryEmbedding( + self.head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor + ) + elif scaling_type == "dynamic": + self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding( + self.head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor + ) + else: + raise ValueError(f"Unknown RoPE scaling type {scaling_type}") + + def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): + return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() + + def _set_base_batch(self, base_list:list): + self.set_best_base = False + self.base_list = base_list + + def _set_best_base(self, base): + self.best_base = base + self.set_best_base = True + + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + output_attentions: bool = False, + use_cache: bool = False, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + bsz, q_len, _ = hidden_states.size() + + if self.pretraining_tp > 1: + key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.pretraining_tp + query_slices = self.q_proj.weight.split((self.num_heads * self.head_dim) // self.pretraining_tp, dim=0) + key_slices = self.k_proj.weight.split(key_value_slicing, dim=0) + value_slices = self.v_proj.weight.split(key_value_slicing, dim=0) + + query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.pretraining_tp)] + query_states = torch.cat(query_states, dim=-1) + + key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.pretraining_tp)] + key_states = torch.cat(key_states, dim=-1) + + value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.pretraining_tp)] + value_states = torch.cat(value_states, dim=-1) + + else: + query_states = self.q_proj(hidden_states) + key_states = self.k_proj(hidden_states) + value_states = self.v_proj(hidden_states) + + query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) + key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + + + + + if self.set_best_base: + self.rotary_emb._set_base(new_base=self.best_base) + kv_seq_len = key_states.shape[-2] + if past_key_value is not None: + kv_seq_len += past_key_value[0].shape[-2] + cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) + else: + + kv_seq_len = key_states.shape[-2] + if past_key_value is not None: + kv_seq_len += past_key_value[0].shape[-2] + new_bsz = len(self.base_list) + if bsz == 1: + query_states = query_states.repeat(new_bsz, 1, 1, 1) + key_states = key_states.repeat(new_bsz, 1, 1, 1) + value_states = value_states.repeat(new_bsz,1, 1, 1) + bsz = new_bsz + if attention_mask.size(0) == 1: + attention_mask = attention_mask.repeat(new_bsz,1, 1, 1) + + + cos, sin = [], [] + + for i in range(new_bsz): + self.rotary_emb._set_base(new_base=self.base_list[i]) + cos_, sin_ = self.rotary_emb(value_states[0], seq_len=kv_seq_len) + cos.append(cos_) + sin.append(sin_) + cos = torch.cat(cos, 0) + sin = torch.cat(sin, 0) + + + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) + + + + + if past_key_value is not None: + # reuse k, v, self_attention + key_states = torch.cat([past_key_value[0].to(key_states), key_states], dim=2) + value_states = torch.cat([past_key_value[1].to(value_states), value_states], dim=2) + + past_key_value = (key_states, value_states) if use_cache else None + # past_key_value = (key_states.cuda(1), value_states.cuda(1)) if use_cache else None #random.choice([1,2,3]) + # past_key_value = (key_states.cuda(random.choice([1,2,3])), value_states.cuda(random.choice([1,2,3]))) if use_cache else None #random.choice([1,2,3]) + + # repeat k/v heads if n_kv_heads < n_heads + key_states = repeat_kv(key_states, self.num_key_value_groups) + value_states = repeat_kv(value_states, self.num_key_value_groups) + + attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) + + + if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len): + raise ValueError( + f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is" + f" {attn_weights.size()}" + ) + + if attention_mask is not None: + if attention_mask.size() != (bsz, 1, q_len, kv_seq_len): + raise ValueError( + f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" + ) + + attn_weights = attn_weights + attention_mask + + # upcast attention to fp32 + #input(torch.nn.functional.kl_div(torch.nn.functional.log_softmax(attn_weights[0,0,-1,:], dim=-1, dtype=torch.float32), torch.ones_like(attn_weights[0,0,-1,:]) / q_len)) + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) + + attn_output = torch.matmul(attn_weights, value_states) + + if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim): + raise ValueError( + f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is" + f" {attn_output.size()}" + ) + + attn_output = attn_output.transpose(1, 2).contiguous() + attn_output = attn_output.reshape(bsz, q_len, self.hidden_size) + + if self.pretraining_tp > 1: + attn_output = attn_output.split(self.hidden_size // self.pretraining_tp, dim=2) + o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.pretraining_tp, dim=1) + attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.pretraining_tp)]) + else: + attn_output = self.o_proj(attn_output) + + if not output_attentions: + attn_weights = None + + return attn_output, attn_weights, past_key_value + + +class LlamaDecoderLayer(nn.Module): + def __init__(self, config: LlamaConfig): + super().__init__() + self.hidden_size = config.hidden_size + self.self_attn = LlamaAttention(config=config) + self.mlp = LlamaMLP(config) + self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + """ + Args: + hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` + attention_mask (`torch.FloatTensor`, *optional*): attention mask of size + `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states + """ + + residual = hidden_states + + hidden_states = self.input_layernorm(hidden_states) + + # Self Attention + hidden_states, self_attn_weights, present_key_value = self.self_attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + ) + hidden_states = residual + hidden_states + + # Fully Connected + residual = hidden_states + hidden_states = self.post_attention_layernorm(hidden_states) + hidden_states = self.mlp(hidden_states) + hidden_states = residual + hidden_states + + outputs = (hidden_states,) + + if output_attentions: + outputs += (self_attn_weights,) + + if use_cache: + outputs += (present_key_value,) + + return outputs + + +LLAMA_START_DOCSTRING = r""" + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`LlamaConfig`]): + Model configuration class with all the parameters of the model. Initializing with a config file does not + load the weights associated with the model, only the configuration. Check out the + [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" + + +@add_start_docstrings( + "The bare LLaMA Model outputting raw hidden-states without any specific head on top.", + LLAMA_START_DOCSTRING, +) +class LlamaPreTrainedModel(PreTrainedModel): + config_class = LlamaConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["LlamaDecoderLayer"] + _skip_keys_device_placement = "past_key_values" + + def _init_weights(self, module): + std = self.config.initializer_range + if isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=std) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=std) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + + def _set_gradient_checkpointing(self, module, value=False): + if isinstance(module, LlamaModel): + module.gradient_checkpointing = value + + +LLAMA_INPUTS_DOCSTRING = r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide + it. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see + `past_key_values`). + + If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] + and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more + information on the default strategy. + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, + config.n_positions - 1]`. + + [What are position IDs?](../glossary#position-ids) + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape + `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape + `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention + blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that + don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all + `decoder_input_ids` of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. +""" + + +@add_start_docstrings( + "The bare LLaMA Model outputting raw hidden-states without any specific head on top.", + LLAMA_START_DOCSTRING, +) +class LlamaModel(LlamaPreTrainedModel): + """ + Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`] + + Args: + config: LlamaConfig + """ + + def __init__(self, config: LlamaConfig): + super().__init__(config) + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)]) + self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + + self.gradient_checkpointing = False + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.embed_tokens + + def set_input_embeddings(self, value): + self.embed_tokens = value + + # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask + def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length): + # create causal mask + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + combined_attention_mask = None + if input_shape[-1] > 1: + combined_attention_mask = _make_causal_mask( + input_shape, + inputs_embeds.dtype, + device=inputs_embeds.device, + past_key_values_length=past_key_values_length, + ) + + if attention_mask is not None: + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to( + inputs_embeds.device + ) + combined_attention_mask = ( + expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask + ) + + + return combined_attention_mask + + @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") + elif input_ids is not None: + batch_size, seq_length = input_ids.shape + elif inputs_embeds is not None: + batch_size, seq_length, _ = inputs_embeds.shape + else: + raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") + + seq_length_with_past = seq_length + past_key_values_length = 0 + + if past_key_values is not None: + past_key_values_length = past_key_values[0][0].shape[2] + seq_length_with_past = seq_length_with_past + past_key_values_length + + if position_ids is None: + device = input_ids.device if input_ids is not None else inputs_embeds.device + position_ids = torch.arange( + past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device + ) + position_ids = position_ids.unsqueeze(0).view(-1, seq_length) + else: + position_ids = position_ids.view(-1, seq_length).long() + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + # embed positions + + if attention_mask is None: + attention_mask = torch.ones( + (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device + ) + attention_mask = self._prepare_decoder_attention_mask( + attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length + ) + + hidden_states = inputs_embeds + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning_once( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + # all_self_attns = None + next_decoder_cache = () if use_cache else None + + for idx, decoder_layer in enumerate(self.layers): + if idx == 31: + output_attentions = True + else: + output_attentions = False + + # print(f'layer {idx}') + if output_hidden_states: + all_hidden_states += (hidden_states,) + + past_key_value = past_key_values[idx] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + + def create_custom_forward(module): + def custom_forward(*inputs): + # None for past_key_value + return module(*inputs, output_attentions, None) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(decoder_layer), + hidden_states, + attention_mask, + position_ids, + None, + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) + + # if output_attentions: + # all_self_attns += (layer_outputs[1],) + # if output_attentions: + # if all_self_attns == None: + # all_self_attns = layer_outputs[1] + # else: + # all_self_attns += layer_outputs[1] + if output_attentions: + all_self_attns = layer_outputs[1] + + hidden_states = self.norm(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + next_cache = next_decoder_cache if use_cache else None + if not return_dict: + return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_self_attns, + ) + + +class LlamaForCausalLM(LlamaPreTrainedModel): + _tied_weights_keys = ["lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = LlamaModel(config) + self.pretraining_tp = config.pretraining_tp + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + # Initialize weights and apply final processing + self.post_init() + self.base_mean = False + + def get_input_embeddings(self): + return self.model.embed_tokens + + def set_base_mean(self, base_list, bsz): + self.base_mean = True + self.base_list = base_list + self.bsz = bsz + + def set_input_embeddings(self, value): + self.model.embed_tokens = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model = decoder + + def get_decoder(self): + return self.model + + @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING) + @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + r""" + Args: + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, LlamaForCausalLM + + >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS) + >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER) + + >>> prompt = "Hey, are you conscious? Can you talk to me?" + >>> inputs = tokenizer(prompt, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(inputs.input_ids, max_length=30) + >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." + ```""" + + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + if self.base_mean == True: + all_logits = [] + all_past_key_values = [] + batch_times = int(len(self.base_list)/self.bsz) + for i in range(batch_times): + tmp_base_list = self.base_list[i*self.bsz:(i+1)*self.bsz] + for layer in self.model.layers: + layer.self_attn._set_base_batch(tmp_base_list) + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values[i] if past_key_values is not None else None, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + hidden_states = outputs[0][:, -1] + if self.pretraining_tp > 1: + lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.pretraining_tp, dim=0) + logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.pretraining_tp)] + logits = torch.cat(logits, dim=-1) + else: + logits = self.lm_head(hidden_states) + + + all_logits.append(logits) # bsz vocab_dim + # logits = nn.functional.softmax(logits[:, -1], dim=-1, dtype=torch.float32)#.to(hidden_states.dtype) + # kl = (logits * torch.log(logits)).sum(-1) #-Categorical(logits).entropy() + + # logits = nn.functional.log_softmax(logits[:, -1], dim=-1, dtype=torch.float32).to(hidden_states.dtype) + # target = nn.functional.softmax((torch.ones([1, logits.size(-1)], dtype=torch.float32)).to(logits), dim=-1) + # kl = nn.functional.kl_div(logits, target, reduction='none').sum(-1) + del outputs.hidden_states + + + # all_logits.append(kl) #bsz + # all_logits.append(torch.max(logits, dim=-1).values) # bsz + # all_last_hidden.append(hidden_states[:,-1]) # bsz hidden_dim + # all_last_hidden.append(logits[:, -1]) # bsz hidden_dim + all_past_key_values.append(outputs.past_key_values) + + + last_batch_base = batch_times*self.bsz + if last_batch_base < len(self.base_list): + tmp_base_list = self.base_list[last_batch_base:] + for layer in self.model.layers: + layer.self_attn._set_base_batch(tmp_base_list) + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values[-1] if past_key_values is not None else None, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + hidden_states = outputs[0][:, -1] + if self.pretraining_tp > 1: + lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.pretraining_tp, dim=0) + logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.pretraining_tp)] + logits = torch.cat(logits, dim=-1) + else: + logits = self.lm_head(hidden_states) + # logits = nn.functional.softmax(logits[:, -1], dim=-1, dtype=torch.float32)#.to(hidden_states.dtype) + # kl = (logits * torch.log(logits)).sum(-1) #-Categorical(logits).entropy() + # logits = nn.functional.log_softmax(logits[:, -1], dim=-1, dtype=torch.float32).to(hidden_states.dtype) + # target = nn.functional.softmax((torch.ones([1, logits.size(-1)], dtype=torch.float32)).to(logits), dim=-1) + # kl = nn.functional.kl_div(logits, target, reduction='none').sum(-1) + del outputs.hidden_states + + # all_logits.append(kl) #bsz + all_logits.append(logits) # bsz vocab_dim + # all_logits.append(torch.max(logits, dim=-1).values) # bsz + # all_last_hidden.append(hidden_states[:,-1]) # bsz hidden_dim + # all_last_hidden.append(logits[:, -1]) # bsz hidden_dim + all_past_key_values.append(outputs.past_key_values) + + outputs.past_key_values = all_past_key_values + all_logits = torch.cat(all_logits, 0) + # all_last_hidden = torch.cat(all_last_hidden, 0) + + weight = nn.functional.softmax(torch.max(all_logits, dim=-1).values, dim=-1, dtype=torch.float32) # bsz + # weight = nn.functional.softmax(all_logits, dim=-1, dtype=torch.float32).to(hidden_states.dtype) + # weight = nn.functional.softmax(all_logits[:, -1], dim=-1, dtype=torch.float32).to(hidden_states.dtype) + logits = torch.mm(weight.unsqueeze(0), all_logits) + + + # print(weight) + # import pdb + # pdb.set_trace() + + # last_hidden_states = torch.mm(weight.unsqueeze(0), all_last_hidden)# + # max_index = torch.max(all_logits, dim=0).indices + # logits = all_last_hidden[max_index].unsqueeze(0) + # all_last_hidden[max_index] + # print(max_index) + # torch.mm(weight.unsqueeze(0), all_last_hidden) + # hidden_states = hidden_states[0].unsqueeze(0) + # hidden_states[:, -1] = last_hidden_states + + # if self.pretraining_tp > 1: + # lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.pretraining_tp, dim=0) + # logits = [F.linear(last_hidden_states, lm_head_slices[i]) for i in range(self.pretraining_tp)] + # logits = torch.cat(logits, dim=-1) + # else: + # logits = self.lm_head(last_hidden_states) + + + logits = logits.unsqueeze(1) + logits = logits.float() + + + # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) + else: + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + hidden_states = outputs[0]#[:, -1] + if self.pretraining_tp > 1: + lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.pretraining_tp, dim=0) + logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.pretraining_tp)] + logits = torch.cat(logits, dim=-1) + else: + logits = self.lm_head(hidden_states) + logits = logits.float() + + loss = None + bsz = logits.size(0) + # labels = labels.repeat(bsz, 1) + if labels is not None: + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = CrossEntropyLoss()#reduction='none') + shift_logits = shift_logits.view(-1, self.config.vocab_size) + shift_labels = shift_labels.view(-1) + # Enable model parallelism + shift_labels = shift_labels.to(shift_logits.device) + loss = loss_fct(shift_logits, shift_labels) + # loss = loss.view(bsz, -1).sum(-1) #(bsz, ) + + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + def prepare_inputs_for_generation( + self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs + ): + if past_key_values: + input_ids = input_ids[:, -1:] + + position_ids = kwargs.get("position_ids", None) + if attention_mask is not None and position_ids is None: + # create position_ids on the fly for batch generation + position_ids = attention_mask.long().cumsum(-1) - 1 + position_ids.masked_fill_(attention_mask == 0, 1) + if past_key_values: + position_ids = position_ids[:, -1].unsqueeze(-1) + + # if `inputs_embeds` are passed, we only want to use them in the 1st generation step + if inputs_embeds is not None and past_key_values is None: + model_inputs = {"inputs_embeds": inputs_embeds} + else: + model_inputs = {"input_ids": input_ids} + + model_inputs.update( + { + "position_ids": position_ids, + "past_key_values": past_key_values, + "use_cache": kwargs.get("use_cache"), + "attention_mask": attention_mask, + } + ) + + return model_inputs + + @staticmethod + def _reorder_cache(past_key_values, beam_idx): + reordered_past = () + for layer_past in past_key_values: + reordered_past += ( + tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past), + ) + return reordered_past + + +@add_start_docstrings( + """ + The LLaMa Model transformer with a sequence classification head on top (linear layer). + + [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models + (e.g. GPT-2) do. + + Since it does classification on the last token, it requires to know the position of the last token. If a + `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If + no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the + padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in + each row of the batch). + """, + LLAMA_START_DOCSTRING, +) +class LlamaForSequenceClassification(LlamaPreTrainedModel): + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + self.model = LlamaModel(config) + self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embed_tokens + + def set_input_embeddings(self, value): + self.model.embed_tokens = value + + @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, SequenceClassifierOutputWithPast]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + transformer_outputs = self.model( + input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = transformer_outputs[0] + logits = self.score(hidden_states) + + if input_ids is not None: + batch_size = input_ids.shape[0] + else: + batch_size = inputs_embeds.shape[0] + + if self.config.pad_token_id is None and batch_size != 1: + raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") + if self.config.pad_token_id is None: + sequence_lengths = -1 + else: + if input_ids is not None: + sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device) + else: + sequence_lengths = -1 + + pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] + + loss = None + if labels is not None: + labels = labels.to(logits.device) + if self.config.problem_type is None: + if self.num_labels == 1: + self.config.problem_type = "regression" + elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): + self.config.problem_type = "single_label_classification" + else: + self.config.problem_type = "multi_label_classification" + + if self.config.problem_type == "regression": + loss_fct = MSELoss() + if self.num_labels == 1: + loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) + else: + loss = loss_fct(pooled_logits, labels) + elif self.config.problem_type == "single_label_classification": + loss_fct = CrossEntropyLoss() + loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) + elif self.config.problem_type == "multi_label_classification": + loss_fct = BCEWithLogitsLoss() + loss = loss_fct(pooled_logits, labels) + if not return_dict: + output = (pooled_logits,) + transformer_outputs[1:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutputWithPast( + loss=loss, + logits=pooled_logits, + past_key_values=transformer_outputs.past_key_values, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) + +# # coding=utf-8 +# # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. +# # +# # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX +# # and OPT implementations in this library. It has been modified from its +# # original forms to accommodate minor architectural differences compared +# # to GPT-NeoX and OPT used by the Meta AI team that trained the model. +# # +# # Licensed under the Apache License, Version 2.0 (the "License"); +# # you may not use this file except in compliance with the License. +# # You may obtain a copy of the License at +# # +# # http://www.apache.org/licenses/LICENSE-2.0 +# # +# # Unless required by applicable law or agreed to in writing, software +# # distributed under the License is distributed on an "AS IS" BASIS, +# # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# # See the License for the specific language governing permissions and +# # limitations under the License. +# """ PyTorch LLaMA model.""" +# import math +# import warnings +# from typing import List, Optional, Tuple, Union + +# import torch +# import torch.nn.functional as F +# import torch.utils.checkpoint +# from torch import nn +# from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss + +# from ...activations import ACT2FN +# from ...modeling_attn_mask_utils import AttentionMaskConverter, _prepare_4d_causal_attention_mask +# from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast +# from ...modeling_utils import PreTrainedModel +# from ...pytorch_utils import ALL_LAYERNORM_LAYERS +# from ...utils import ( +# add_start_docstrings, +# add_start_docstrings_to_model_forward, +# is_flash_attn_2_available, +# logging, +# replace_return_docstrings, +# ) +# from ...utils.import_utils import is_torch_fx_available +# from .configuration_llama import LlamaConfig + + +# if is_flash_attn_2_available(): +# from flash_attn import flash_attn_func, flash_attn_varlen_func +# from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa + + +# # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph. +# # It means that the function will not be traced through and simply appear as a node in the graph. +# if is_torch_fx_available(): +# _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask) + + +# logger = logging.get_logger(__name__) + +# _CONFIG_FOR_DOC = "LlamaConfig" + + +# def _get_unpad_data(attention_mask): +# seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) +# indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten() +# max_seqlen_in_batch = seqlens_in_batch.max().item() +# cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)) +# return ( +# indices, +# cu_seqlens, +# max_seqlen_in_batch, +# ) + + +# def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): +# warnings.warn( +# "Calling `transformers.models.llama.modeling_llama._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils.AttentionMaskConverter._prepare_4d_attention_mask" +# ) +# return AttentionMaskConverter._prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len) + + +# def _make_causal_mask( +# input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0 +# ): +# warnings.warn( +# "Calling `transformers.models.llama.modeling_llama._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.llama.modeling_llama.AttentionMaskConverter._make_causal_mask" +# ) +# return AttentionMaskConverter._make_causal_mask( +# input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length +# ) + + +# class LlamaRMSNorm(nn.Module): +# def __init__(self, hidden_size, eps=1e-6): +# """ +# LlamaRMSNorm is equivalent to T5LayerNorm +# """ +# super().__init__() +# self.weight = nn.Parameter(torch.ones(hidden_size)) +# self.variance_epsilon = eps + +# def forward(self, hidden_states): +# input_dtype = hidden_states.dtype +# hidden_states = hidden_states.to(torch.float32) +# variance = hidden_states.pow(2).mean(-1, keepdim=True) +# hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) +# return self.weight * hidden_states.to(input_dtype) + + +# ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm) + + +# class LlamaRotaryEmbedding(nn.Module): +# def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None): +# super().__init__() + +# self.dim = dim +# self.max_position_embeddings = max_position_embeddings +# self.base = base +# inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)) +# self.register_buffer("inv_freq", inv_freq, persistent=False) + +# # Build here to make `torch.jit.trace` work. +# self._set_cos_sin_cache( +# seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype() +# ) + +# def _set_cos_sin_cache(self, seq_len, device, dtype): +# self.max_seq_len_cached = seq_len +# t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) + +# freqs = torch.einsum("i,j->ij", t, self.inv_freq) +# # Different from paper, but it uses a different permutation in order to obtain the same calculation +# emb = torch.cat((freqs, freqs), dim=-1) +# self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) +# self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) + +# def forward(self, x, seq_len=None): +# # x: [bs, num_attention_heads, seq_len, head_size] +# if seq_len > self.max_seq_len_cached: +# self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype) + +# return ( +# self.cos_cached[:seq_len].to(dtype=x.dtype), +# self.sin_cached[:seq_len].to(dtype=x.dtype), +# ) + + +# class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding): +# """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev""" + +# def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0): +# self.scaling_factor = scaling_factor +# super().__init__(dim, max_position_embeddings, base, device) + +# def _set_cos_sin_cache(self, seq_len, device, dtype): +# self.max_seq_len_cached = seq_len +# t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) +# t = t / self.scaling_factor + +# freqs = torch.einsum("i,j->ij", t, self.inv_freq) +# # Different from paper, but it uses a different permutation in order to obtain the same calculation +# emb = torch.cat((freqs, freqs), dim=-1) +# self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) +# self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) + + +# class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding): +# """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla""" + +# def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0): +# self.scaling_factor = scaling_factor +# super().__init__(dim, max_position_embeddings, base, device) + +# def _set_cos_sin_cache(self, seq_len, device, dtype): +# self.max_seq_len_cached = seq_len + +# if seq_len > self.max_position_embeddings: +# base = self.base * ( +# (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1) +# ) ** (self.dim / (self.dim - 2)) +# inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)) +# self.register_buffer("inv_freq", inv_freq, persistent=False) + +# t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) + +# freqs = torch.einsum("i,j->ij", t, self.inv_freq) +# # Different from paper, but it uses a different permutation in order to obtain the same calculation +# emb = torch.cat((freqs, freqs), dim=-1) +# self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) +# self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) + + +# def rotate_half(x): +# """Rotates half the hidden dims of the input.""" +# x1 = x[..., : x.shape[-1] // 2] +# x2 = x[..., x.shape[-1] // 2 :] +# return torch.cat((-x2, x1), dim=-1) + + +# def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1): +# """Applies Rotary Position Embedding to the query and key tensors. + +# Args: +# q (`torch.Tensor`): The query tensor. +# k (`torch.Tensor`): The key tensor. +# cos (`torch.Tensor`): The cosine part of the rotary embedding. +# sin (`torch.Tensor`): The sine part of the rotary embedding. +# position_ids (`torch.Tensor`): +# The position indices of the tokens corresponding to the query and key tensors. For example, this can be +# used to pass offsetted position ids when working with a KV-cache. +# unsqueeze_dim (`int`, *optional*, defaults to 1): +# The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and +# sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note +# that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and +# k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes +# cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have +# the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. +# Returns: +# `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. +# """ +# cos = cos[position_ids].unsqueeze(unsqueeze_dim) +# sin = sin[position_ids].unsqueeze(unsqueeze_dim) +# q_embed = (q * cos) + (rotate_half(q) * sin) +# k_embed = (k * cos) + (rotate_half(k) * sin) +# return q_embed, k_embed + + +# class LlamaMLP(nn.Module): +# def __init__(self, config): +# super().__init__() +# self.config = config +# self.hidden_size = config.hidden_size +# self.intermediate_size = config.intermediate_size +# self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) +# self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) +# self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) +# self.act_fn = ACT2FN[config.hidden_act] + +# def forward(self, x): +# if self.config.pretraining_tp > 1: +# slice = self.intermediate_size // self.config.pretraining_tp +# gate_proj_slices = self.gate_proj.weight.split(slice, dim=0) +# up_proj_slices = self.up_proj.weight.split(slice, dim=0) +# down_proj_slices = self.down_proj.weight.split(slice, dim=1) + +# gate_proj = torch.cat( +# [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1 +# ) +# up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1) + +# intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2) +# down_proj = [ +# F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp) +# ] +# down_proj = sum(down_proj) +# else: +# down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) + +# return down_proj + + +# def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: +# """ +# This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, +# num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) +# """ +# batch, num_key_value_heads, slen, head_dim = hidden_states.shape +# if n_rep == 1: +# return hidden_states +# hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) +# return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) + + +# class LlamaAttention(nn.Module): +# """Multi-headed attention from 'Attention Is All You Need' paper""" + +# def __init__(self, config: LlamaConfig): +# super().__init__() +# self.config = config +# self.hidden_size = config.hidden_size +# self.num_heads = config.num_attention_heads +# self.head_dim = self.hidden_size // self.num_heads +# self.num_key_value_heads = config.num_key_value_heads +# self.num_key_value_groups = self.num_heads // self.num_key_value_heads +# self.max_position_embeddings = config.max_position_embeddings +# self.rope_theta = config.rope_theta +# self.is_causal = True + +# if (self.head_dim * self.num_heads) != self.hidden_size: +# raise ValueError( +# f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}" +# f" and `num_heads`: {self.num_heads})." +# ) +# self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias) +# self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias) +# self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias) +# self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias) +# self._init_rope() + +# def _init_rope(self): +# if self.config.rope_scaling is None: +# self.rotary_emb = LlamaRotaryEmbedding( +# self.head_dim, +# max_position_embeddings=self.max_position_embeddings, +# base=self.rope_theta, +# ) +# else: +# scaling_type = self.config.rope_scaling["type"] +# scaling_factor = self.config.rope_scaling["factor"] +# if scaling_type == "linear": +# self.rotary_emb = LlamaLinearScalingRotaryEmbedding( +# self.head_dim, +# max_position_embeddings=self.max_position_embeddings, +# scaling_factor=scaling_factor, +# base=self.rope_theta, +# ) +# elif scaling_type == "dynamic": +# self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding( +# self.head_dim, +# max_position_embeddings=self.max_position_embeddings, +# scaling_factor=scaling_factor, +# base=self.rope_theta, +# ) +# else: +# raise ValueError(f"Unknown RoPE scaling type {scaling_type}") + +# def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): +# return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() + +# def forward( +# self, +# hidden_states: torch.Tensor, +# attention_mask: Optional[torch.Tensor] = None, +# position_ids: Optional[torch.LongTensor] = None, +# past_key_value: Optional[Tuple[torch.Tensor]] = None, +# output_attentions: bool = False, +# use_cache: bool = False, +# **kwargs, +# ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: +# if "padding_mask" in kwargs: +# warnings.warn( +# "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" +# ) + +# bsz, q_len, _ = hidden_states.size() + +# if self.config.pretraining_tp > 1: +# key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp +# query_slices = self.q_proj.weight.split( +# (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0 +# ) +# key_slices = self.k_proj.weight.split(key_value_slicing, dim=0) +# value_slices = self.v_proj.weight.split(key_value_slicing, dim=0) + +# query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)] +# query_states = torch.cat(query_states, dim=-1) + +# key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)] +# key_states = torch.cat(key_states, dim=-1) + +# value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)] +# value_states = torch.cat(value_states, dim=-1) + +# else: +# query_states = self.q_proj(hidden_states) +# key_states = self.k_proj(hidden_states) +# value_states = self.v_proj(hidden_states) + +# query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) +# key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) +# value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + +# kv_seq_len = key_states.shape[-2] +# if past_key_value is not None: +# kv_seq_len += past_key_value[0].shape[-2] +# cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) +# query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) + +# if past_key_value is not None: +# # reuse k, v, self_attention +# key_states = torch.cat([past_key_value[0], key_states], dim=2) +# value_states = torch.cat([past_key_value[1], value_states], dim=2) + +# past_key_value = (key_states, value_states) if use_cache else None + +# key_states = repeat_kv(key_states, self.num_key_value_groups) +# value_states = repeat_kv(value_states, self.num_key_value_groups) + +# attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) + +# if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len): +# raise ValueError( +# f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is" +# f" {attn_weights.size()}" +# ) + +# if attention_mask is not None: +# if attention_mask.size() != (bsz, 1, q_len, kv_seq_len): +# raise ValueError( +# f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" +# ) +# attn_weights = attn_weights + attention_mask + +# # upcast attention to fp32 +# attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) +# attn_output = torch.matmul(attn_weights, value_states) + +# if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim): +# raise ValueError( +# f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is" +# f" {attn_output.size()}" +# ) + +# attn_output = attn_output.transpose(1, 2).contiguous() + +# attn_output = attn_output.reshape(bsz, q_len, self.hidden_size) + +# if self.config.pretraining_tp > 1: +# attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2) +# o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1) +# attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)]) +# else: +# attn_output = self.o_proj(attn_output) + +# if not output_attentions: +# attn_weights = None + +# return attn_output, attn_weights, past_key_value + + +# class LlamaFlashAttention2(LlamaAttention): +# """ +# Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays +# untouched. The only required change would be on the forward pass where it needs to correctly call the public API of +# flash attention and deal with padding tokens in case the input contains any of them. +# """ + +# def forward( +# self, +# hidden_states: torch.Tensor, +# attention_mask: Optional[torch.LongTensor] = None, +# position_ids: Optional[torch.LongTensor] = None, +# past_key_value: Optional[Tuple[torch.Tensor]] = None, +# output_attentions: bool = False, +# use_cache: bool = False, +# **kwargs, +# ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: +# # LlamaFlashAttention2 attention does not support output_attentions +# if "padding_mask" in kwargs: +# warnings.warn( +# "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" +# ) + +# # overwrite attention_mask with padding_mask +# attention_mask = kwargs.pop("padding_mask") + +# output_attentions = False + +# bsz, q_len, _ = hidden_states.size() + +# query_states = self.q_proj(hidden_states) +# key_states = self.k_proj(hidden_states) +# value_states = self.v_proj(hidden_states) + +# # Flash attention requires the input to have the shape +# # batch_size x seq_length x head_dim x hidden_dim +# # therefore we just need to keep the original shape +# query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) +# key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) +# value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + +# kv_seq_len = key_states.shape[-2] +# if past_key_value is not None: +# kv_seq_len += past_key_value[0].shape[-2] + +# cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) + +# query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) + +# if past_key_value is not None: +# # reuse k, v, self_attention +# key_states = torch.cat([past_key_value[0], key_states], dim=2) +# value_states = torch.cat([past_key_value[1], value_states], dim=2) + +# past_key_value = (key_states, value_states) if use_cache else None + +# query_states = query_states.transpose(1, 2) +# key_states = key_states.transpose(1, 2) +# value_states = value_states.transpose(1, 2) + +# # TODO: llama does not have dropout in the config?? +# # It is recommended to use dropout with FA according to the docs +# # when training. +# dropout_rate = 0.0 # if not self.training else self.attn_dropout + +# # In PEFT, usually we cast the layer norms in float32 for training stability reasons +# # therefore the input hidden states gets silently casted in float32. Hence, we need +# # cast them back in the correct dtype just to be sure everything works as expected. +# # This might slowdown training & inference so it is recommended to not cast the LayerNorms +# # in fp32. (LlamaRMSNorm handles it correctly) + +# input_dtype = query_states.dtype +# if input_dtype == torch.float32: +# # Handle the case where the model is quantized +# if hasattr(self.config, "_pre_quantization_dtype"): +# target_dtype = self.config._pre_quantization_dtype +# else: +# target_dtype = self.q_proj.weight.dtype + +# logger.warning_once( +# f"The input hidden states seems to be silently casted in float32, this might be related to" +# f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" +# f" {target_dtype}." +# ) + +# query_states = query_states.to(target_dtype) +# key_states = key_states.to(target_dtype) +# value_states = value_states.to(target_dtype) + +# attn_output = self._flash_attention_forward( +# query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate +# ) + +# attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous() +# attn_output = self.o_proj(attn_output) + +# if not output_attentions: +# attn_weights = None + +# return attn_output, attn_weights, past_key_value + +# def _flash_attention_forward( +# self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None +# ): +# """ +# Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token +# first unpad the input, then computes the attention scores and pad the final attention scores. + +# Args: +# query_states (`torch.Tensor`): +# Input query states to be passed to Flash Attention API +# key_states (`torch.Tensor`): +# Input key states to be passed to Flash Attention API +# value_states (`torch.Tensor`): +# Input value states to be passed to Flash Attention API +# attention_mask (`torch.Tensor`): +# The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the +# position of padding tokens and 1 for the position of non-padding tokens. +# dropout (`int`, *optional*): +# Attention dropout +# softmax_scale (`float`, *optional*): +# The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim) +# """ +# # Contains at least one padding token in the sequence +# if attention_mask is not None: +# batch_size = query_states.shape[0] +# query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input( +# query_states, key_states, value_states, attention_mask, query_length +# ) + +# cu_seqlens_q, cu_seqlens_k = cu_seq_lens +# max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens + +# attn_output_unpad = flash_attn_varlen_func( +# query_states, +# key_states, +# value_states, +# cu_seqlens_q=cu_seqlens_q, +# cu_seqlens_k=cu_seqlens_k, +# max_seqlen_q=max_seqlen_in_batch_q, +# max_seqlen_k=max_seqlen_in_batch_k, +# dropout_p=dropout, +# softmax_scale=softmax_scale, +# causal=self.is_causal, +# ) + +# attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length) +# else: +# attn_output = flash_attn_func( +# query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=self.is_causal +# ) + +# return attn_output + +# def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length): +# indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask) +# batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape + +# key_layer = index_first_axis( +# key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k +# ) +# value_layer = index_first_axis( +# value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k +# ) +# if query_length == kv_seq_len: +# query_layer = index_first_axis( +# query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k +# ) +# cu_seqlens_q = cu_seqlens_k +# max_seqlen_in_batch_q = max_seqlen_in_batch_k +# indices_q = indices_k +# elif query_length == 1: +# max_seqlen_in_batch_q = 1 +# cu_seqlens_q = torch.arange( +# batch_size + 1, dtype=torch.int32, device=query_layer.device +# ) # There is a memcpy here, that is very bad. +# indices_q = cu_seqlens_q[:-1] +# query_layer = query_layer.squeeze(1) +# else: +# # The -q_len: slice assumes left padding. +# attention_mask = attention_mask[:, -query_length:] +# query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask) + +# return ( +# query_layer, +# key_layer, +# value_layer, +# indices_q, +# (cu_seqlens_q, cu_seqlens_k), +# (max_seqlen_in_batch_q, max_seqlen_in_batch_k), +# ) + + +# class LlamaDecoderLayer(nn.Module): +# def __init__(self, config: LlamaConfig): +# super().__init__() +# self.hidden_size = config.hidden_size +# self.self_attn = ( +# LlamaAttention(config=config) +# if not getattr(config, "_flash_attn_2_enabled", False) +# else LlamaFlashAttention2(config=config) +# ) +# self.mlp = LlamaMLP(config) +# self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) +# self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + +# def forward( +# self, +# hidden_states: torch.Tensor, +# attention_mask: Optional[torch.Tensor] = None, +# position_ids: Optional[torch.LongTensor] = None, +# past_key_value: Optional[Tuple[torch.Tensor]] = None, +# output_attentions: Optional[bool] = False, +# use_cache: Optional[bool] = False, +# **kwargs, +# ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: +# """ +# Args: +# hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` +# attention_mask (`torch.FloatTensor`, *optional*): +# attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1, +# query_sequence_length, key_sequence_length)` if default attention is used. +# output_attentions (`bool`, *optional*): +# Whether or not to return the attentions tensors of all attention layers. See `attentions` under +# returned tensors for more detail. +# use_cache (`bool`, *optional*): +# If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding +# (see `past_key_values`). +# past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states +# """ +# if "padding_mask" in kwargs: +# warnings.warn( +# "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" +# ) + +# residual = hidden_states + +# hidden_states = self.input_layernorm(hidden_states) + +# # Self Attention +# hidden_states, self_attn_weights, present_key_value = self.self_attn( +# hidden_states=hidden_states, +# attention_mask=attention_mask, +# position_ids=position_ids, +# past_key_value=past_key_value, +# output_attentions=output_attentions, +# use_cache=use_cache, +# **kwargs, +# ) +# hidden_states = residual + hidden_states + +# # Fully Connected +# residual = hidden_states +# hidden_states = self.post_attention_layernorm(hidden_states) +# hidden_states = self.mlp(hidden_states) +# hidden_states = residual + hidden_states + +# outputs = (hidden_states,) + +# if output_attentions: +# outputs += (self_attn_weights,) + +# if use_cache: +# outputs += (present_key_value,) + +# return outputs + + +# LLAMA_START_DOCSTRING = r""" +# This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the +# library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads +# etc.) + +# This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. +# Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage +# and behavior. + +# Parameters: +# config ([`LlamaConfig`]): +# Model configuration class with all the parameters of the model. Initializing with a config file does not +# load the weights associated with the model, only the configuration. Check out the +# [`~PreTrainedModel.from_pretrained`] method to load the model weights. +# """ + + +# @add_start_docstrings( +# "The bare LLaMA Model outputting raw hidden-states without any specific head on top.", +# LLAMA_START_DOCSTRING, +# ) +# class LlamaPreTrainedModel(PreTrainedModel): +# config_class = LlamaConfig +# base_model_prefix = "model" +# supports_gradient_checkpointing = True +# _no_split_modules = ["LlamaDecoderLayer"] +# _skip_keys_device_placement = "past_key_values" +# _supports_flash_attn_2 = True + +# def _init_weights(self, module): +# std = self.config.initializer_range +# if isinstance(module, nn.Linear): +# module.weight.data.normal_(mean=0.0, std=std) +# if module.bias is not None: +# module.bias.data.zero_() +# elif isinstance(module, nn.Embedding): +# module.weight.data.normal_(mean=0.0, std=std) +# if module.padding_idx is not None: +# module.weight.data[module.padding_idx].zero_() + + +# LLAMA_INPUTS_DOCSTRING = r""" +# Args: +# input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): +# Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide +# it. + +# Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and +# [`PreTrainedTokenizer.__call__`] for details. + +# [What are input IDs?](../glossary#input-ids) +# attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): +# Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + +# - 1 for tokens that are **not masked**, +# - 0 for tokens that are **masked**. + +# [What are attention masks?](../glossary#attention-mask) + +# Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and +# [`PreTrainedTokenizer.__call__`] for details. + +# If `past_key_values` is used, optionally only the last `input_ids` have to be input (see +# `past_key_values`). + +# If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] +# and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more +# information on the default strategy. + +# - 1 indicates the head is **not masked**, +# - 0 indicates the head is **masked**. +# position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): +# Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, +# config.n_positions - 1]`. + +# [What are position IDs?](../glossary#position-ids) +# past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): +# Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape +# `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape +# `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)`. + +# Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention +# blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + +# If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't +# have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids` +# of shape `(batch_size, sequence_length)`. +# inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): +# Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This +# is useful if you want more control over how to convert `input_ids` indices into associated vectors than the +# model's internal embedding lookup matrix. +# use_cache (`bool`, *optional*): +# If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see +# `past_key_values`). +# output_attentions (`bool`, *optional*): +# Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned +# tensors for more detail. +# output_hidden_states (`bool`, *optional*): +# Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for +# more detail. +# return_dict (`bool`, *optional*): +# Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. +# """ + + +# @add_start_docstrings( +# "The bare LLaMA Model outputting raw hidden-states without any specific head on top.", +# LLAMA_START_DOCSTRING, +# ) +# class LlamaModel(LlamaPreTrainedModel): +# """ +# Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`] + +# Args: +# config: LlamaConfig +# """ + +# def __init__(self, config: LlamaConfig): +# super().__init__(config) +# self.padding_idx = config.pad_token_id +# self.vocab_size = config.vocab_size + +# self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) +# self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)]) +# self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + +# self.gradient_checkpointing = False +# # Initialize weights and apply final processing +# self.post_init() + +# def get_input_embeddings(self): +# return self.embed_tokens + +# def set_input_embeddings(self, value): +# self.embed_tokens = value + +# @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING) +# def forward( +# self, +# input_ids: torch.LongTensor = None, +# attention_mask: Optional[torch.Tensor] = None, +# position_ids: Optional[torch.LongTensor] = None, +# past_key_values: Optional[List[torch.FloatTensor]] = None, +# inputs_embeds: Optional[torch.FloatTensor] = None, +# use_cache: Optional[bool] = None, +# output_attentions: Optional[bool] = None, +# output_hidden_states: Optional[bool] = None, +# return_dict: Optional[bool] = None, +# ) -> Union[Tuple, BaseModelOutputWithPast]: +# output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions +# output_hidden_states = ( +# output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states +# ) +# use_cache = use_cache if use_cache is not None else self.config.use_cache + +# return_dict = return_dict if return_dict is not None else self.config.use_return_dict + +# # retrieve input_ids and inputs_embeds +# if input_ids is not None and inputs_embeds is not None: +# raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") +# elif input_ids is not None: +# batch_size, seq_length = input_ids.shape[:2] +# elif inputs_embeds is not None: +# batch_size, seq_length = inputs_embeds.shape[:2] +# else: +# raise ValueError("You have to specify either input_ids or inputs_embeds") + +# past_key_values_length = 0 +# if past_key_values is not None: +# past_key_values_length = past_key_values[0][0].shape[2] + +# if position_ids is None: +# device = input_ids.device if input_ids is not None else inputs_embeds.device +# position_ids = torch.arange( +# past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device +# ) +# position_ids = position_ids.unsqueeze(0) + +# if inputs_embeds is None: +# inputs_embeds = self.embed_tokens(input_ids) + +# if getattr(self.config, "_flash_attn_2_enabled", False): +# # 2d mask is passed through the layers +# attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None +# else: +# # 4d mask is passed through the layers +# attention_mask = _prepare_4d_causal_attention_mask( +# attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length +# ) + +# # embed positions +# hidden_states = inputs_embeds + +# if self.gradient_checkpointing and self.training: +# if use_cache: +# logger.warning_once( +# "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." +# ) +# use_cache = False + +# # decoder layers +# all_hidden_states = () if output_hidden_states else None +# all_self_attns = () if output_attentions else None +# next_decoder_cache = () if use_cache else None + +# for idx, decoder_layer in enumerate(self.layers): +# if output_hidden_states: +# all_hidden_states += (hidden_states,) + +# past_key_value = past_key_values[idx] if past_key_values is not None else None + +# if self.gradient_checkpointing and self.training: +# layer_outputs = self._gradient_checkpointing_func( +# decoder_layer.__call__, +# hidden_states, +# attention_mask, +# position_ids, +# past_key_value, +# output_attentions, +# use_cache, +# ) +# else: +# layer_outputs = decoder_layer( +# hidden_states, +# attention_mask=attention_mask, +# position_ids=position_ids, +# past_key_value=past_key_value, +# output_attentions=output_attentions, +# use_cache=use_cache, +# ) + +# hidden_states = layer_outputs[0] + +# if use_cache: +# next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) + +# if output_attentions: +# all_self_attns += (layer_outputs[1],) + +# hidden_states = self.norm(hidden_states) + +# # add hidden states from the last decoder layer +# if output_hidden_states: +# all_hidden_states += (hidden_states,) + +# next_cache = next_decoder_cache if use_cache else None +# if not return_dict: +# return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) +# return BaseModelOutputWithPast( +# last_hidden_state=hidden_states, +# past_key_values=next_cache, +# hidden_states=all_hidden_states, +# attentions=all_self_attns, +# ) + + +# class LlamaForCausalLM(LlamaPreTrainedModel): +# _tied_weights_keys = ["lm_head.weight"] + +# def __init__(self, config): +# super().__init__(config) +# self.model = LlamaModel(config) +# self.vocab_size = config.vocab_size +# self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + +# # Initialize weights and apply final processing +# self.post_init() + +# def get_input_embeddings(self): +# return self.model.embed_tokens + +# def set_input_embeddings(self, value): +# self.model.embed_tokens = value + +# def get_output_embeddings(self): +# return self.lm_head + +# def set_output_embeddings(self, new_embeddings): +# self.lm_head = new_embeddings + +# def set_decoder(self, decoder): +# self.model = decoder + +# def get_decoder(self): +# return self.model + +# @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING) +# @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) +# def forward( +# self, +# input_ids: torch.LongTensor = None, +# attention_mask: Optional[torch.Tensor] = None, +# position_ids: Optional[torch.LongTensor] = None, +# past_key_values: Optional[List[torch.FloatTensor]] = None, +# inputs_embeds: Optional[torch.FloatTensor] = None, +# labels: Optional[torch.LongTensor] = None, +# use_cache: Optional[bool] = None, +# output_attentions: Optional[bool] = None, +# output_hidden_states: Optional[bool] = None, +# return_dict: Optional[bool] = None, +# ) -> Union[Tuple, CausalLMOutputWithPast]: +# r""" +# Args: +# labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): +# Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., +# config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored +# (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + +# Returns: + +# Example: + +# ```python +# >>> from transformers import AutoTokenizer, LlamaForCausalLM + +# >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS) +# >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER) + +# >>> prompt = "Hey, are you conscious? Can you talk to me?" +# >>> inputs = tokenizer(prompt, return_tensors="pt") + +# >>> # Generate +# >>> generate_ids = model.generate(inputs.input_ids, max_length=30) +# >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] +# "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." +# ```""" + +# output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions +# output_hidden_states = ( +# output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states +# ) +# return_dict = return_dict if return_dict is not None else self.config.use_return_dict + +# # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) +# outputs = self.model( +# input_ids=input_ids, +# attention_mask=attention_mask, +# position_ids=position_ids, +# past_key_values=past_key_values, +# inputs_embeds=inputs_embeds, +# use_cache=use_cache, +# output_attentions=output_attentions, +# output_hidden_states=output_hidden_states, +# return_dict=return_dict, +# ) + +# hidden_states = outputs[0] +# if self.config.pretraining_tp > 1: +# lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0) +# logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)] +# logits = torch.cat(logits, dim=-1) +# else: +# logits = self.lm_head(hidden_states) +# logits = logits.float() + +# loss = None +# if labels is not None: +# # Shift so that tokens < n predict n +# shift_logits = logits[..., :-1, :].contiguous() +# shift_labels = labels[..., 1:].contiguous() +# # Flatten the tokens +# loss_fct = CrossEntropyLoss() +# shift_logits = shift_logits.view(-1, self.config.vocab_size) +# shift_labels = shift_labels.view(-1) +# # Enable model parallelism +# shift_labels = shift_labels.to(shift_logits.device) +# loss = loss_fct(shift_logits, shift_labels) + +# if not return_dict: +# output = (logits,) + outputs[1:] +# return (loss,) + output if loss is not None else output + +# return CausalLMOutputWithPast( +# loss=loss, +# logits=logits, +# past_key_values=outputs.past_key_values, +# hidden_states=outputs.hidden_states, +# attentions=outputs.attentions, +# ) + +# def prepare_inputs_for_generation( +# self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs +# ): +# if past_key_values is not None: +# past_length = past_key_values[0][0].shape[2] + +# # Some generation methods already pass only the last input ID +# if input_ids.shape[1] > past_length: +# remove_prefix_length = past_length +# else: +# # Default to old behavior: keep only final ID +# remove_prefix_length = input_ids.shape[1] - 1 + +# input_ids = input_ids[:, remove_prefix_length:] + +# position_ids = kwargs.get("position_ids", None) +# if attention_mask is not None and position_ids is None: +# # create position_ids on the fly for batch generation +# position_ids = attention_mask.long().cumsum(-1) - 1 +# position_ids.masked_fill_(attention_mask == 0, 1) +# if past_key_values: +# position_ids = position_ids[:, -input_ids.shape[1] :] + +# # if `inputs_embeds` are passed, we only want to use them in the 1st generation step +# if inputs_embeds is not None and past_key_values is None: +# model_inputs = {"inputs_embeds": inputs_embeds} +# else: +# model_inputs = {"input_ids": input_ids} + +# model_inputs.update( +# { +# "position_ids": position_ids, +# "past_key_values": past_key_values, +# "use_cache": kwargs.get("use_cache"), +# "attention_mask": attention_mask, +# } +# ) +# return model_inputs + +# @staticmethod +# def _reorder_cache(past_key_values, beam_idx): +# reordered_past = () +# for layer_past in past_key_values: +# reordered_past += ( +# tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past), +# ) +# return reordered_past + + +# @add_start_docstrings( +# """ +# The LLaMa Model transformer with a sequence classification head on top (linear layer). + +# [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models +# (e.g. GPT-2) do. + +# Since it does classification on the last token, it requires to know the position of the last token. If a +# `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If +# no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the +# padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in +# each row of the batch). +# """, +# LLAMA_START_DOCSTRING, +# ) +# class LlamaForSequenceClassification(LlamaPreTrainedModel): +# def __init__(self, config): +# super().__init__(config) +# self.num_labels = config.num_labels +# self.model = LlamaModel(config) +# self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False) + +# # Initialize weights and apply final processing +# self.post_init() + +# def get_input_embeddings(self): +# return self.model.embed_tokens + +# def set_input_embeddings(self, value): +# self.model.embed_tokens = value + +# @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING) +# def forward( +# self, +# input_ids: torch.LongTensor = None, +# attention_mask: Optional[torch.Tensor] = None, +# position_ids: Optional[torch.LongTensor] = None, +# past_key_values: Optional[List[torch.FloatTensor]] = None, +# inputs_embeds: Optional[torch.FloatTensor] = None, +# labels: Optional[torch.LongTensor] = None, +# use_cache: Optional[bool] = None, +# output_attentions: Optional[bool] = None, +# output_hidden_states: Optional[bool] = None, +# return_dict: Optional[bool] = None, +# ) -> Union[Tuple, SequenceClassifierOutputWithPast]: +# r""" +# labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): +# Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., +# config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If +# `config.num_labels > 1` a classification loss is computed (Cross-Entropy). +# """ +# return_dict = return_dict if return_dict is not None else self.config.use_return_dict + +# transformer_outputs = self.model( +# input_ids, +# attention_mask=attention_mask, +# position_ids=position_ids, +# past_key_values=past_key_values, +# inputs_embeds=inputs_embeds, +# use_cache=use_cache, +# output_attentions=output_attentions, +# output_hidden_states=output_hidden_states, +# return_dict=return_dict, +# ) +# hidden_states = transformer_outputs[0] +# logits = self.score(hidden_states) + +# if input_ids is not None: +# batch_size = input_ids.shape[0] +# else: +# batch_size = inputs_embeds.shape[0] + +# if self.config.pad_token_id is None and batch_size != 1: +# raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") +# if self.config.pad_token_id is None: +# sequence_lengths = -1 +# else: +# if input_ids is not None: +# sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).long().argmax(-1) - 1).to( +# logits.device +# ) +# else: +# sequence_lengths = -1 + +# pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] + +# loss = None +# if labels is not None: +# labels = labels.to(logits.device) +# if self.config.problem_type is None: +# if self.num_labels == 1: +# self.config.problem_type = "regression" +# elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): +# self.config.problem_type = "single_label_classification" +# else: +# self.config.problem_type = "multi_label_classification" + +# if self.config.problem_type == "regression": +# loss_fct = MSELoss() +# if self.num_labels == 1: +# loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) +# else: +# loss = loss_fct(pooled_logits, labels) +# elif self.config.problem_type == "single_label_classification": +# loss_fct = CrossEntropyLoss() +# loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) +# elif self.config.problem_type == "multi_label_classification": +# loss_fct = BCEWithLogitsLoss() +# loss = loss_fct(pooled_logits, labels) +# if not return_dict: +# output = (pooled_logits,) + transformer_outputs[1:] +# return ((loss,) + output) if loss is not None else output + +# return SequenceClassifierOutputWithPast( +# loss=loss, +# logits=pooled_logits, +# past_key_values=transformer_outputs.past_key_values, +# hidden_states=transformer_outputs.hidden_states, +# attentions=transformer_outputs.attentions, +# ) diff --git a/attention-buckets/requirements.txt b/attention-buckets/requirements.txt new file mode 100644 index 00000000..0901ef64 --- /dev/null +++ b/attention-buckets/requirements.txt @@ -0,0 +1,31 @@ +--find-links https://download.pytorch.org/whl/torch_stable.html +torch==1.12.1+cu113 +accelerate==0.20.3 +fastapi==0.95.1 +gradio==3.23.0 +httpx==0.24.0 +markdown-it-py==2.2.0 +numpy==1.24.3 +prompt-toolkit==3.0.38 +pydantic==1.10.7 +requests==2.30.0 +rich==13.3.5 +rouge==1.0.1 +sentencepiece==0.1.99 +shortuuid==1.0.11 +tiktoken==0.4.0 +tokenizers==0.13.3 +transformers==4.28.1 +uvicorn==0.22.0 +bitsandbytes==0.38.1 +peft==0.3.0 +langchain==0.0.229 +deepspeed==0.9.2 +sentence_transformers==2.2.2 +tensorboard +openai +scipy +termcolor +flask +flask_cors +sentence_transformers diff --git a/attention-buckets/utils.py b/attention-buckets/utils.py new file mode 100644 index 00000000..f0673619 --- /dev/null +++ b/attention-buckets/utils.py @@ -0,0 +1,143 @@ +import json +import re +import torch +import transformers +import transformers.models.llama.modeling_llama +from functools import partial + + +def process_system_message(system_message, functions): + assert "with a function call to actually excute your step." in system_message + # we find that following ReACT format and merging the thought node and function call node is easier for model to learn to integrate the action input json string in its prediction than learn to predict a json string directly. + system_message = system_message.replace("with a function call to actually excute your step.", "with a function call to actually excute your step. Your output should follow this format:\nThought:\nAction\nAction Input:\n") + # add all the function dicts in the prompt. + system_message = system_message + "\nSpecifically, you have access to the following APIs: " + str(functions) + return system_message + +def get_gpu_memory(max_gpus=None): + """Get available memory for each GPU.""" + gpu_memory = [] + num_gpus = ( + torch.cuda.device_count() + if max_gpus is None + else min(max_gpus, torch.cuda.device_count()) + ) + + for gpu_id in range(num_gpus): + with torch.cuda.device(gpu_id): + device = torch.cuda.current_device() + gpu_properties = torch.cuda.get_device_properties(device) + total_memory = gpu_properties.total_memory / (1024**3) + allocated_memory = torch.cuda.memory_allocated() / (1024**3) + available_memory = total_memory - allocated_memory + gpu_memory.append(available_memory) + return gpu_memory + + +def standardize_category(category): + save_category = category.replace(" ", "_").replace(",", "_").replace("/", "_") + while " " in save_category or "," in save_category: + save_category = save_category.replace(" ", "_").replace(",", "_") + save_category = save_category.replace("__", "_") + return save_category + +def standardize(string): + res = re.compile("[^\\u4e00-\\u9fa5^a-z^A-Z^0-9^_]") + string = res.sub("_", string) + string = re.sub(r"(_)\1+","_", string).lower() + while True: + if len(string) == 0: + return string + if string[0] == "_": + string = string[1:] + else: + break + while True: + if len(string) == 0: + return string + if string[-1] == "_": + string = string[:-1] + else: + break + if string[0].isdigit(): + string = "get_" + string + return string + +def change_name(name): + change_list = ["from", "class", "return", "false", "true", "id", "and"] + if name in change_list: + name = "is_" + name + return name + +# code adapted from https://huggingface.co/kaiokendev/superhot-13b-8k-no-rlhf-test/blob/main/llama_rope_scaled_monkey_patch.py +class CondenseRotaryEmbedding(torch.nn.Module): + def __init__(self, dim, ratio, max_position_embeddings=2048, base=10000, device=None): + super().__init__() + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim)) + self.register_buffer("inv_freq", inv_freq) + self.dim = dim + # Build here to make `torch.jit.trace` work. + self.ratio = ratio + max_position_embeddings *= ratio + print(f"Condensing Positional embeddings from {max_position_embeddings} to {max_position_embeddings // ratio}") + self.max_seq_len_cached = max_position_embeddings + t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype) / ratio + freqs = torch.einsum("i,j->ij", t, self.inv_freq) + # Different from paper, but it uses a different permutation in order to obtain the same calculation + emb = torch.cat((freqs, freqs), dim=-1) + dtype = torch.get_default_dtype() + self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False) + self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False) + + def _set_base(self, new_base): + self.base = new_base + self.inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(self.inv_freq.device) / self.dim)) + self._set_cos_sin_cache( + seq_len=self.max_seq_len_cached, device=self.inv_freq.device, dtype=torch.get_default_dtype() + ) + + def _set_cos_sin_cache(self, seq_len, device, dtype): + self.max_seq_len_cached = seq_len + t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) / self.ratio + freqs = torch.einsum("i,j->ij", t, self.inv_freq) + # Different from paper, but it uses a different permutation in order to obtain the same calculation + emb = torch.cat((freqs, freqs), dim=-1).to(device) + self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False) + self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False) + + + def forward(self, x, seq_len=None): + # x: [bs, num_attention_heads, seq_len, head_size] + # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case. + if seq_len > self.max_seq_len_cached: + self._set_cos_sin_cache(self, seq_len, x.device, x.dtype) + return ( + self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype), + self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype), + ) + +def replace_llama_with_condense(ratio): + transformers.models.llama.modeling_llama.LlamaRotaryEmbedding = partial(CondenseRotaryEmbedding, ratio=ratio) + + +def process_retrieval_ducoment(documents_df): + ir_corpus = {} + corpus2tool = {} + for row in documents_df.itertuples(): + doc = json.loads(row.document_content) + ir_corpus[row.docid] = (doc.get('category_name', '') or '') + ', ' + \ + (doc.get('tool_name', '') or '') + ', ' + \ + (doc.get('api_name', '') or '') + ', ' + \ + (doc.get('api_description', '') or '') + \ + ', required_params: ' + json.dumps(doc.get('required_parameters', '')) + \ + ', optional_params: ' + json.dumps(doc.get('optional_parameters', '')) + \ + ', return_schema: ' + json.dumps(doc.get('template_response', '')) + corpus2tool[(doc.get('category_name', '') or '') + ', ' + \ + (doc.get('tool_name', '') or '') + ', ' + \ + (doc.get('api_name', '') or '') + ', ' + \ + (doc.get('api_description', '') or '') + \ + ', required_params: ' + json.dumps(doc.get('required_parameters', '')) + \ + ', optional_params: ' + json.dumps(doc.get('optional_parameters', '')) + \ + ', return_schema: ' + json.dumps(doc.get('template_response', ''))] = doc['category_name'] + '\t' + doc['tool_name'] + '\t' + doc['api_name'] + return ir_corpus, corpus2tool + \ No newline at end of file