├── assets └── img │ ├── baseline_vs_cllm_gsm8k_best_acc_demo_legacy.gif │ ├── logo.png │ ├── cllm_speedup.png │ ├── baseline_vs_cllm_spider_acc_demo.gif │ └── baseline_vs_cllm_gsm8k_best_acc_demo.gif ├── applications ├── run_chat_cllm.sh └── chat_cli_cllm.py ├── scripts ├── generate_trajectory.sh └── train_cllm.sh ├── eval ├── gsm8k │ ├── speedup.sh │ ├── math_normalization.py │ ├── acc.py │ └── speedup.py └── mt-bench │ └── gen_model_answer_jacobi.py ├── requirements.txt ├── cllm ├── utils.py ├── cllm_trainer_global.py ├── train_cllm_global.py └── cllm_llama_modeling.py ├── README.md ├── LICENSE └── data └── generate_trajectory.py /assets/img/baseline_vs_cllm_gsm8k_best_acc_demo_legacy.gif: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assets/img/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hao-ai-lab/Consistency_LLM/HEAD/assets/img/logo.png -------------------------------------------------------------------------------- /assets/img/cllm_speedup.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hao-ai-lab/Consistency_LLM/HEAD/assets/img/cllm_speedup.png -------------------------------------------------------------------------------- /assets/img/baseline_vs_cllm_spider_acc_demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hao-ai-lab/Consistency_LLM/HEAD/assets/img/baseline_vs_cllm_spider_acc_demo.gif -------------------------------------------------------------------------------- /assets/img/baseline_vs_cllm_gsm8k_best_acc_demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hao-ai-lab/Consistency_LLM/HEAD/assets/img/baseline_vs_cllm_gsm8k_best_acc_demo.gif -------------------------------------------------------------------------------- /applications/run_chat_cllm.sh: -------------------------------------------------------------------------------- 1 | model_path=$1 2 | cllm_type=$2 3 | 4 | python3 applications/chat_cli_cllm.py --model_path ${model_path} --cllm_type ${cllm_type} --chat --debug 5 | -------------------------------------------------------------------------------- /scripts/generate_trajectory.sh: -------------------------------------------------------------------------------- 1 | filename=$1 2 | model_path=$2 3 | max_new_tokens=$3 4 | max_new_seq_len=$4 5 | 6 | python3 data/generate_trajectory.py \ 7 | --filename ${filename} \ 8 | --model ${model_path} \ 9 | --max_new_tokens ${max_new_tokens} \ 10 | --max_new_seq_len ${max_new_seq_len} 11 | -------------------------------------------------------------------------------- /eval/gsm8k/speedup.sh: -------------------------------------------------------------------------------- 1 | model_path=$1 2 | target_model_path=$2 3 | max_new_tokens=$3 4 | 5 | # test model is tested and we use the tokenizer of teacher model because the tokenizer of test model has something to fix 6 | python3 eval/gsm8k/speedup.py \ 7 | --test_model_path ${model_path} \ 8 | --teacher_model_path ${target_model_path} \ 9 | --max_new_tokens ${max_new_tokens} -------------------------------------------------------------------------------- /scripts/train_cllm.sh: -------------------------------------------------------------------------------- 1 | export CUDA_VISIBLE_DEVICES=0,1,2,3 2 | export WANDB_PROJECT=consistency_llm 3 | 4 | model_path=$1 5 | trajectory_file=$2 6 | output_path=$3 7 | n_token_seq_size=$4 8 | qlora=$5 9 | 10 | torchrun --nnodes=1 --nproc_per_node=4 --rdzv_id=101 --rdzv_endpoint='localhost:5666' \ 11 | --master_port 10000 \ 12 | cllm/train_cllm_global.py \ 13 | --target_model_path ${model_path} \ 14 | --data_path ${trajectory_file} \ 15 | --output_dir ${output_path} \ 16 | --max_new_tokens ${n_token_seq_size} \ 17 | --bf16 True \ 18 | --report_to wandb \ 19 | --do_train \ 20 | --num_train_epochs 1 \ 21 | --per_device_train_batch_size 1 \ 22 | --gradient_accumulation_steps 1 \ 23 | --gradient_checkpointing True \ 24 | --save_strategy "steps" \ 25 | --save_steps 100 \ 26 | --save_total_limit 50 \ 27 | --learning_rate 2e-5 \ 28 | --weight_decay 0. \ 29 | --warmup_ratio 0.03 \ 30 | --lr_scheduler_type "cosine" \ 31 | --logging_steps 10 \ 32 | --model_max_length 2048 \ 33 | --lazy_preprocess True \ 34 | --fsdp "full_shard auto_wrap" \ 35 | --fsdp_transformer_layer_cls_to_wrap 'LlamaDecoderLayer' \ 36 | --qlora ${qlora} 37 | -------------------------------------------------------------------------------- /eval/gsm8k/math_normalization.py: -------------------------------------------------------------------------------- 1 | # Part of the code is modified from the code snippets provided in "Solving Quantitative Reasoning Problems with Language Models" by Lewkowycz et al. 2 | import pdb 3 | import re 4 | import sympy 5 | import threading 6 | from sympy.parsing.latex import parse_latex 7 | 8 | SUBSTITUTIONS = [ 9 | ('an ', ''), ('a ', ''), ('.$', '$'), ('\\$', ''), (r'\ ', ''), ('\%', '%'), 10 | (' ', ''), ('mbox', 'text'), (',\\text{and}', ','), 11 | ('\\text{and}', ','), ('\\text{m}', '\\text{}') 12 | ] 13 | REMOVED_EXPRESSIONS = [ 14 | 'square', 'ways', 'integers', 'dollars', 'mph', 'inches', 'ft', 15 | 'hours', 'km', 'units', '\\ldots', 'sue', 'points', 'feet', 16 | 'minutes', 'digits', 'cents', 'degrees', 'cm', 'gm', 'pounds', 17 | 'meters', 'meals', 'edges', 'students', 'childrentickets', 'multiples', 18 | '\\text{s}', '\\text{.}', '\\text{\ns}', '\\text{}^2', 19 | '\\text{}^3', '\\text{\n}', '\\text{}', r'\mathrm{th}', 20 | r'^\circ', r'^{\circ}', r'\;', r',\!', '{,}', '"', '\\dots' 21 | ] 22 | 23 | def normalize_final_answer(final_answer: str) -> str: 24 | """Normalize a final answer to a quantitative reasoning question.""" 25 | final_answer = final_answer.split('=')[-1] 26 | 27 | for before, after in SUBSTITUTIONS: 28 | final_answer = final_answer.replace(before, after) 29 | for expr in REMOVED_EXPRESSIONS: 30 | final_answer = final_answer.replace(expr, '') 31 | 32 | # Extract answer that is in LaTeX math, is bold, 33 | # is surrounded by a box, etc. 34 | final_answer = re.sub(r'(.*?)(\$)(.*?)(\$)(.*)', '$\\3$', final_answer) 35 | final_answer = re.sub(r'(\\text\{)(.*?)(\})', '\\2', final_answer) 36 | final_answer = re.sub(r'(\\textbf\{)(.*?)(\})', '\\2', final_answer) 37 | final_answer = re.sub(r'(\\overline\{)(.*?)(\})', '\\2', final_answer) 38 | final_answer = re.sub(r'(\\boxed\{)(.*)(\})', '\\2', final_answer) 39 | 40 | # Normalize shorthand TeX: 41 | # \fracab -> \frac{a}{b} 42 | # \frac{abc}{bef} -> \frac{abc}{bef} 43 | # \fracabc -> \frac{a}{b}c 44 | # \sqrta -> \sqrt{a} 45 | # \sqrtab -> sqrt{a}b 46 | final_answer = re.sub( 47 | r'(frac)([^{])(.)', 'frac{\\2}{\\3}', final_answer) 48 | final_answer = re.sub( 49 | r'(sqrt)([^{])', 'sqrt{\\2}', final_answer) 50 | final_answer = final_answer.replace('$', '') 51 | 52 | # Normalize 100,000 -> 100000 53 | if final_answer.replace(',', '').isdigit(): 54 | final_answer = final_answer.replace(',', '') 55 | 56 | return final_answer 57 | 58 | def check_sympy_equivalence(formatted_target_str, formatted_prediction_str): 59 | flag = False 60 | try: 61 | target_expr = parse_latex(formatted_target_str) 62 | except: 63 | target_expr = formatted_target_str 64 | flag = True 65 | 66 | try: 67 | prediction_expr = parse_latex(formatted_prediction_str) 68 | except: 69 | prediction_expr = formatted_prediction_str 70 | flag = True 71 | 72 | if flag == True: 73 | return formatted_target_str == formatted_prediction_str 74 | 75 | try: 76 | return sympy.simplify(target_expr - prediction_expr) == 0 77 | except: 78 | return False 79 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | absl-py==0.15.0 2 | accelerate==0.25.0 3 | aiohttp==3.9.1 4 | aiosignal==1.3.1 5 | annotated-types==0.6.0 6 | annoy==1.17.3 7 | anthropic==0.8.1 8 | anyio==3.7.1 9 | appdirs==1.4.4 10 | asttokens==2.4.1 11 | astunparse==1.6.3 12 | async-timeout==4.0.3 13 | attrdict==2.0.1 14 | attrs==23.1.0 15 | azure-core==1.29.7 16 | azure-identity==1.15.0 17 | azure-storage-blob==12.19.0 18 | backcall==0.2.0 19 | beautifulsoup4==4.12.3 20 | bitsandbytes==0.42.0 21 | bleach==6.1.0 22 | cachetools==5.3.2 23 | certifi==2023.11.17 24 | cffi==1.16.0 25 | charset-normalizer==3.3.2 26 | click==8.1.7 27 | cryptography==41.0.7 28 | datasets==2.15.0 29 | decorator==5.1.1 30 | deepspeed==0.12.5 31 | defusedxml==0.7.1 32 | dill==0.3.7 33 | distro==1.9.0 34 | docker-pycreds==0.4.0 35 | docopt==0.6.2 36 | dpu-utils==0.6.1 37 | einops==0.7.0 38 | exceptiongroup==1.2.0 39 | executing==2.0.1 40 | fastapi==0.105.0 41 | fastjsonschema==2.19.1 42 | filelock==3.13.1 43 | fire==0.5.0 44 | flatbuffers==1.12 45 | frozenlist==1.4.1 46 | fschat==0.2.34 47 | fsspec==2023.10.0 48 | gast==0.4.0 49 | gitdb==4.0.11 50 | GitPython==3.1.40 51 | google-auth==2.26.2 52 | google-auth-oauthlib==0.4.6 53 | google-pasta==0.2.0 54 | h11==0.14.0 55 | httpcore==1.0.2 56 | httpx==0.25.2 57 | huggingface-hub==0.19.4 58 | idna==3.6 59 | importlib-metadata==7.0.1 60 | ipython==8.12.3 61 | isodate==0.6.1 62 | jedi==0.19.1 63 | Jinja2==3.1.2 64 | jsonschema==4.21.1 65 | jsonschema-specifications==2023.12.1 66 | jupyter_client==8.6.0 67 | jupyter_core==5.7.1 68 | jupyterlab_pygments==0.3.0 69 | keras==2.15.0 70 | keras-nightly==2.5.0.dev2021032900 71 | Keras-Preprocessing==1.1.2 72 | libclang==16.0.6 73 | Markdown==3.5.2 74 | markdown-it-py==3.0.0 75 | markdown2==2.4.12 76 | MarkupSafe==2.1.3 77 | matplotlib-inline==0.1.6 78 | mdurl==0.1.2 79 | mistune==3.0.2 80 | ml-dtypes==0.2.0 81 | mpmath==1.3.0 82 | msal==1.26.0 83 | msal-extensions==1.1.0 84 | multidict==6.0.4 85 | multiprocess==0.70.15 86 | nbclient==0.9.0 87 | nbconvert==7.16.2 88 | nbformat==5.9.2 89 | networkx==3.2.1 90 | nh3==0.2.15 91 | ninja==1.11.1.1 92 | numpy==1.26.3 93 | oauthlib==3.2.2 94 | openai==0.28.0 95 | opt-einsum==3.3.0 96 | packaging==23.2 97 | pandas==2.2.0 98 | pandocfilters==1.5.1 99 | parso==0.8.3 100 | Pebble==5.0.5 101 | pexpect==4.9.0 102 | pickleshare==0.7.5 103 | pipreqs==0.5.0 104 | platformdirs==4.2.0 105 | portalocker==2.8.2 106 | prompt-toolkit==3.0.43 107 | protobuf==3.20.3 108 | psutil==5.9.6 109 | ptyprocess==0.7.0 110 | pure-eval==0.2.2 111 | py-cpuinfo==9.0.0 112 | pyarrow==14.0.1 113 | pyarrow-hotfix==0.6 114 | pyasn1==0.5.1 115 | pyasn1-modules==0.3.0 116 | pycparser==2.21 117 | pydantic==1.10.13 118 | pydantic_core==2.14.5 119 | Pygments==2.17.2 120 | PyJWT==2.8.0 121 | pynvml==11.5.0 122 | python-dateutil==2.8.2 123 | pytz==2023.3.post1 124 | PyYAML==6.0.1 125 | pyzmq==25.1.2 126 | referencing==0.33.0 127 | regex==2023.10.3 128 | requests==2.31.0 129 | requests-oauthlib==1.3.1 130 | rich==13.7.0 131 | rpds-py==0.18.0 132 | rsa==4.9 133 | safetensors==0.4.1 134 | scipy==1.12.0 135 | sentencepiece==0.1.99 136 | sentry-sdk==1.39.1 137 | setproctitle==1.3.3 138 | SetSimilaritySearch==1.0.1 139 | shortuuid==1.0.11 140 | six==1.15.0 141 | smmap==5.0.1 142 | sniffio==1.3.0 143 | soupsieve==2.5 144 | stack-data==0.6.3 145 | starlette==0.27.0 146 | svgwrite==1.4.3 147 | sympy==1.12 148 | tensorboard==2.11.2 149 | tensorboard-data-server==0.6.1 150 | tensorboard-plugin-wit==1.8.1 151 | tensorboardX==2.6.2.2 152 | tensorflow-estimator==2.5.0 153 | tensorflow-hub==0.15.0 154 | tensorflow-io-gcs-filesystem==0.35.0 155 | termcolor==1.1.0 156 | tiktoken==0.5.2 157 | timeout-decorator==0.5.0 158 | tinycss2==1.2.1 159 | tokenizers==0.15.0 160 | toolz==0.12.0 161 | torch==2.1.2 162 | tornado==6.4 163 | tqdm==4.66.1 164 | traitlets==5.14.1 165 | transformers==4.36.2 166 | triton==2.1.0 167 | typing_extensions==4.9.0 168 | tzdata==2023.3 169 | urllib3==2.1.0 170 | uvicorn==0.24.0.post1 171 | wandb==0.16.1 172 | wavedrom==2.0.3.post3 173 | wcwidth==0.2.12 174 | webencodings==0.5.1 175 | Werkzeug==3.0.1 176 | wrapt==1.12.1 177 | xxhash==3.4.1 178 | yarg==0.1.9 179 | yarl==1.9.4 180 | zipp==3.17.0 181 | -------------------------------------------------------------------------------- /cllm/utils.py: -------------------------------------------------------------------------------- 1 | import json 2 | from transformers import AutoTokenizer, LlamaForCausalLM 3 | import torch 4 | from tqdm import tqdm 5 | import random 6 | import argparse 7 | import transformers 8 | import json 9 | from typing import Optional, Dict, Sequence 10 | import os, sys 11 | import json 12 | import argparse 13 | import numpy as np 14 | 15 | def get_default_question(cllm_type): 16 | if cllm_type == 'sharegpt': 17 | return "Which methods did Socrates employ to challenge the prevailing thoughts of his time?" 18 | elif cllm_type == 'spider': 19 | return "The SQL database has table named vehicle with columns ['Vehicle_ID', 'Model', 'Build_Year', 'Top_Speed', 'Power', 'Builder', 'Total_Production'], table named driver with columns ['Driver_ID', 'Name', 'Citizenship', 'Racing_Series'], table named vehicle_driver with columns ['Driver_ID', 'Vehicle_ID'], Question: What are the vehicle ids and models which have been driven by more than 2 drivers or been driven by the driver named 'Jeff Gordon'?" 20 | elif cllm_type == 'python': 21 | return "Implement the Conway's Game of Life. You should start with a 2D grid initialized with some configuration of live and dead cells. 1 for live cell and -1 for dead cell. The simulation should update the grid state by applying the rules for each cell simultaneously: any live cell with fewer than two live neighbors dies, as if by underpopulation. Any live cell with two or three live neighbors lives on to the next generation. Any live cell with more than three live neighbors dies, as if by overpopulation. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. initial_grid = [[0, 1, 0], [0, 0, 1], [1, 1, 1], [0, 0, 0]]" 22 | elif cllm_type == 'gsm8k': 23 | return "Poppy is solving a 1000-piece jigsaw puzzle. She places a quarter of the pieces on the board, then her mom places a third of the remaining pieces. How many jigsaw pieces are left to be placed?" 24 | else: 25 | return "Tell me a short story." 26 | 27 | def get_system_prompt(cllm_type): 28 | if cllm_type == 'sharegpt': 29 | return "Answer in English unless other language is used. A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.\n" 30 | elif cllm_type == 'spider': 31 | return "Could you translate the following question into SQL. Please only generate SQL, don't include explanation in the answer.\n" 32 | elif cllm_type == 'python': 33 | return "Please generate code based on the following doc:\n" 34 | elif cllm_type == 'gsm8k': 35 | return "" 36 | else: 37 | return "A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.\n" 38 | 39 | def get_instruction_template(system_prompt, roles, model_input, cllm_type): 40 | if cllm_type == 'sharegpt': 41 | return system_prompt + f"{roles[0]}: " + f"{model_input}\n{roles[1]}: " 42 | if cllm_type == 'spider' or 'python': 43 | return f"### Instruction:\n" + system_prompt + f"{model_input}\n" + f"### Response:\n" 44 | if cllm_type == 'gsm8k': 45 | prompt_mapping = "Question:\n{input}\nAnswer:\nLet's think step by step.\n" 46 | return prompt_mapping.format(input=model_input) 47 | else: 48 | return system_prompt + f"{roles[0]}: " + f"{model_input}\n{roles[1]}: " 49 | 50 | 51 | def detect_repetitive_patterns(tokenizer, prompt_ids, repeat_ngram_size): 52 | 53 | if len(prompt_ids.shape)==1: 54 | prompt_ids = prompt_ids 55 | elif len(prompt_ids.shape)==2: 56 | prompt_ids = prompt_ids[0] 57 | elif len(prompt_ids.shape)==3: 58 | prompt_ids = prompt_ids[0][0] 59 | else: 60 | print(f'Unexpected shape {prompt_ids.shape}! Please check prompt ids') 61 | assert False 62 | 63 | count = 1 64 | for i in range(1, len(prompt_ids)): 65 | if prompt_ids[i] == tokenizer.eos_token_id: 66 | break 67 | if prompt_ids[i] == prompt_ids[i - 1]: 68 | count += 1 69 | if count == repeat_ngram_size: 70 | return True 71 | else: 72 | count = 1 73 | 74 | return False 75 | 76 | def jacobian_generated_data_postprocessed(generated_data, model_path): 77 | tokenizer = AutoTokenizer.from_pretrained(model_path) 78 | low_quality_data_id_lst = [] 79 | # delete low quality data with repetitive pattern 80 | for i, d in enumerate(generated_data): 81 | if detect_repetitive_patterns(tokenizer, np.array(d['teacher_output_ids']), repeat_ngram_size=10): 82 | prompt_ids = np.array(d['teacher_output_ids']) 83 | if len(prompt_ids.shape)==2: 84 | prompt_ids = prompt_ids[0] 85 | elif len(prompt_ids.shape)==3: 86 | prompt_ids = prompt_ids[0][0] 87 | print(f'Low quality generation detected: {tokenizer.decode(prompt_ids)}') 88 | low_quality_data_id_lst.append(i) 89 | print(f'{len(low_quality_data_id_lst)} low quality data detected. {len(low_quality_data_id_lst)/len(generated_data)} percent of low quality data.') 90 | 91 | # add complete teacher outputs 92 | teacher_output_inspector = {} 93 | for d in generated_data: 94 | data_id = d["data_id"] 95 | if data_id in teacher_output_inspector.keys(): 96 | all_teacher_output_map = teacher_output_inspector[data_id] 97 | else: 98 | all_teacher_output_map = {} 99 | #print(data_id) 100 | itr = d["jacobian_itr_id"] 101 | # handle bsz=1 case only 102 | all_teacher_output_map[itr] = d["teacher_output_ids"][0] 103 | teacher_output_inspector[data_id] = all_teacher_output_map 104 | 105 | teacher_output_collector = {} 106 | for d_id in teacher_output_inspector.keys(): 107 | all_teacher_output_map = teacher_output_inspector[d_id] 108 | all_itr = [int(s.split('_')[1]) for s in all_teacher_output_map.keys()] 109 | print(all_itr) 110 | max_itr = max(all_itr) 111 | max_itr_s = "itr_" + str(max_itr) 112 | complete_teacher_output = all_teacher_output_map[max_itr_s] 113 | teacher_output_collector[d_id] = complete_teacher_output 114 | 115 | f_result = [] 116 | for d in generated_data: 117 | data_id = d["data_id"] 118 | complete_teacher_output = teacher_output_collector[data_id] 119 | d["complete_teacher_output_ids"] = complete_teacher_output 120 | f_result.append(d) 121 | 122 | cleaned_f_result = [] 123 | for i, d in enumerate(generated_data): 124 | if i in low_quality_data_id_lst: 125 | continue 126 | cleaned_f_result.append(d) 127 | 128 | 129 | return cleaned_f_result -------------------------------------------------------------------------------- /cllm/cllm_trainer_global.py: -------------------------------------------------------------------------------- 1 | import transformers 2 | import torch 3 | from transformers import Trainer 4 | from transformers.trainer_pt_utils import LabelSmoother 5 | import wandb 6 | import random 7 | from torch.utils.data import DataLoader 8 | 9 | IGNORE_TOKEN_ID = LabelSmoother.ignore_index 10 | 11 | class CllmTrainer(Trainer): 12 | def __init__(self, *args, **kwargs): 13 | super().__init__(*args, **kwargs) 14 | args = kwargs["args"] 15 | self.train_step_cnt = 0 16 | self.max_new_tokens = args.max_new_tokens 17 | self.use_gt_labels = args.use_gt_labels 18 | 19 | def training_step(self, model, inputs): 20 | self.train_step_cnt += 1 21 | return self.consistency_training_step(model, inputs) 22 | 23 | def consistency_training_step(self, model, inputs): 24 | 25 | max_new_tokens = self.max_new_tokens 26 | 27 | jacobian_trajectory = inputs["jacobian_trajectory"] 28 | input_masks = inputs["attention_mask"] 29 | bsz = jacobian_trajectory[0].shape[0] 30 | eos_reached = torch.tensor([False] * bsz).to(model.device) 31 | 32 | ### tokens generated after are set to 33 | for i in range(len(jacobian_trajectory)): 34 | for j in range(bsz): 35 | trajectory_len = torch.sum(input_masks, dim=-1) 36 | # find the first accurate 37 | eos_positions = torch.where(jacobian_trajectory[i][j, :(trajectory_len[j]-max_new_tokens)]==self.tokenizer.eos_token_id)[0] 38 | if len(eos_positions)==0: 39 | continue 40 | # otherwise, set tokens coming after the accurate as pad 41 | eos_reached[j] = True 42 | trajectory_copy = jacobian_trajectory[i].clone().detach() 43 | eos_pos = eos_positions[0] 44 | trajectory_copy[j, int(eos_pos)+1:] = self.tokenizer.pad_token_id 45 | jacobian_trajectory[i] = trajectory_copy 46 | 47 | ### compute AutoRegression loss ### 48 | # use labels to avoid pattern collapse 49 | if self.use_gt_labels: 50 | labels = inputs['labels_ids'] 51 | else: 52 | labels = inputs['teacher_output_ids'] 53 | # TODO: check if it's right when batch size > 1 54 | labels = torch.tensor(labels).to(model.device) 55 | attention_mask = torch.full_like(labels, 1).to(model.device) 56 | label_student_model_output = model(labels, attention_mask) 57 | 58 | attention_mask = torch.full_like(jacobian_trajectory[0], 1).to(model.device) 59 | attention_mask = jacobian_trajectory[-1] != self.tokenizer.pad_token_id 60 | logits_last = self.get_logits(model, jacobian_trajectory[-1].clone().detach(), attention_mask) 61 | 62 | label_smoother = LabelSmoother(epsilon=0.1, ignore_index= -100) 63 | loss_ar = label_smoother(label_student_model_output, labels, shift_labels=True) 64 | loss_ar*=10 65 | if self.args.qlora: 66 | loss_ar.requires_grad = True 67 | print(f'loss ar: {loss_ar} computed! performing backward pass...') 68 | with self.accelerator.accumulate(model): 69 | self.accelerator.backward(loss_ar) 70 | 71 | ### compute Consistency loss (global) ### 72 | # random select one point from trajectory 73 | i = random.choice(range(len(jacobian_trajectory))[:-1]) 74 | 75 | attention_mask = torch.full_like(jacobian_trajectory[0], 1).to(jacobian_trajectory[0].device) 76 | attention_mask = jacobian_trajectory[i] != self.tokenizer.pad_token_id 77 | logits_i = self.get_logits(model, jacobian_trajectory[i].clone().detach(), attention_mask) 78 | 79 | output_mask = jacobian_trajectory[i][..., 1:] == self.tokenizer.pad_token_id 80 | # We do not calculate the cross entrophy of same logits to alleviate misleading gradients 81 | for j in range(bsz): 82 | end_of_mask_position = torch.where(jacobian_trajectory[i][j, 1:] != jacobian_trajectory[-1][j, 1:])[0] 83 | if len(end_of_mask_position)==0: 84 | output_mask[j, :] = True 85 | else: 86 | output_mask[j, :end_of_mask_position[0]] = True 87 | 88 | loss_global = self.soft_cross_entropy( 89 | logits_i[..., :-1, :].float(), # logits generated by the last token is dropped 90 | logits_last[..., :-1, :].to(logits_i.device).clone().detach().float(), 91 | output_mask.to(logits_i.device) 92 | ) 93 | if self.args.qlora: 94 | loss_global.requires_grad = True 95 | print(f'loss global {loss_global} computed! performing backward pass...') 96 | with self.accelerator.accumulate(model): 97 | self.accelerator.backward(loss_global) 98 | 99 | if self.args.local_rank == 0: 100 | wandb.log({"ar loss": loss_ar}) 101 | wandb.log({"consistency loss": loss_global}) 102 | 103 | # sync processes 104 | torch.distributed.barrier() 105 | # total loss = ar_loss + consistency_global_loss 106 | loss = loss_ar.detach() + loss_global.detach() 107 | 108 | return loss 109 | 110 | 111 | def log(self, logs): 112 | # Remove the 'loss' entry with value 0 before calling the superclass method 113 | if 'loss' in logs and logs['loss'] == -1: 114 | del logs['loss'] 115 | 116 | # Call the original `log` method of the `Trainer` class 117 | super().log(logs) 118 | 119 | def get_train_dataloader(self): 120 | # Create custom DataLoader with shuffle set to False 121 | shuffle = True 122 | dataloader_params = { 123 | "batch_size": self.args.per_device_train_batch_size, 124 | "shuffle": shuffle, 125 | "num_workers": self.args.dataloader_num_workers, 126 | "pin_memory": self.args.dataloader_pin_memory, 127 | } 128 | 129 | return self.accelerator.prepare(DataLoader(self.train_dataset, **dataloader_params)) 130 | 131 | ###################### Helper Functions ############################# 132 | def soft_cross_entropy(self, predicts, targets, padding_mask): 133 | # TODO: support batch_size >1 here. 134 | if (~padding_mask).sum() == 0: 135 | return 0*predicts[0][0][0] 136 | predict_log_prob = torch.nn.functional.log_softmax(predicts, dim=-1) 137 | targets_prob = torch.nn.functional.softmax(targets, dim=-1) 138 | entropy = -targets_prob * predict_log_prob 139 | expand_mask = padding_mask.unsqueeze(-1).expand_as(entropy) 140 | entropy.masked_fill_(expand_mask, 0) 141 | mean_entropy = entropy.sum() / (~padding_mask).sum() 142 | return mean_entropy 143 | 144 | def get_logits(self, model, input_ids, attention_mask): 145 | return model( 146 | input_ids=input_ids, 147 | attention_mask=attention_mask, 148 | ).logits 149 | 150 | -------------------------------------------------------------------------------- /applications/chat_cli_cllm.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import argparse 3 | import subprocess 4 | 5 | import time, os 6 | import random 7 | from typing import Dict, Optional, Sequence, List, Tuple 8 | import transformers 9 | from transformers.trainer_pt_utils import LabelSmoother, get_module_class_from_name 10 | from fastchat.model.model_adapter import get_conversation_template 11 | from transformers.cache_utils import Cache, DynamicCache 12 | from transformers import LlamaModel,LlamaForCausalLM 13 | from transformers.generation import GenerationConfig 14 | 15 | import sys 16 | from pathlib import Path 17 | 18 | path_root = Path(__file__).parents[1] 19 | sys.path.append(str(path_root)) 20 | 21 | from cllm.utils import get_default_question, get_system_prompt, get_instruction_template 22 | from cllm.cllm_llama_modeling import delete_false_key_value, jacobi_forward, jacobi_forward_profiling 23 | 24 | DynamicCache.delete_false_key_value = delete_false_key_value 25 | LlamaForCausalLM.jacobi_forward = jacobi_forward 26 | 27 | def jacobi_generate(inputs, model, tokenizer, max_new_tokens, max_new_seq_len): 28 | #converge_step = [] 29 | CHAT = int(os.environ.get("CHAT", 0)) 30 | if CHAT: 31 | chat = True 32 | else: 33 | chat = False 34 | forward_times = 0 35 | 36 | #all_jacobian_trajectory = [] 37 | 38 | prompt_len = torch.sum(inputs['attention_mask'], dim=-1) 39 | generation = inputs['input_ids'] 40 | ### prefill the kv-cache 41 | 42 | past_key_values, first_correct_token = model.jacobi_forward(input_ids=inputs['input_ids'], tokenizer=tokenizer, max_new_tokens=max_new_tokens, past_key_values=None, use_cache = True, prefill_phase = True, chat=chat) 43 | ### generation phase 44 | itr = 0 45 | global_accurate_length = 0 46 | eos_reached = False 47 | while True: 48 | itr+=1 49 | bsz = 1 # only support batch_size = 1 now 50 | # randomly initialize the first point of jacobian trajectory 51 | random_point = torch.tensor(random.choices(generation[0], k=(max_new_tokens-1)), device="cuda").view(1,-1) 52 | input_ids = torch.cat((first_correct_token.view(1,-1), random_point),dim=-1) 53 | n_gram_generation, first_correct_token, iter_steps, accurate_length = model.jacobi_forward(input_ids=input_ids, tokenizer=tokenizer, max_new_tokens=max_new_tokens, past_key_values=past_key_values, use_cache = True, prefill_phase = False, chat=chat) 54 | forward_times += iter_steps 55 | global_accurate_length += accurate_length 56 | #all_jacobian_trajectory.append(jacobian_trajectory) 57 | 58 | eos_positions = torch.where(n_gram_generation[0]==tokenizer.eos_token_id)[0] 59 | 60 | if len(eos_positions)>0: 61 | eos_reached = True 62 | 63 | ### see if next max_new_tokens should be generated & if True, update weights and prepare new input_id 64 | generation = torch.cat((generation, n_gram_generation), dim=-1) 65 | 66 | if eos_reached or itr*max_new_tokens > max_new_seq_len: 67 | break 68 | 69 | return generation, global_accurate_length / forward_times 70 | 71 | if __name__ == "__main__": 72 | parser = argparse.ArgumentParser() 73 | parser.add_argument("--local_rank", type=int, default=0) 74 | parser.add_argument("--model_path", type=str, help="model path", default="meta-llama/Llama-2-7b-chat-hf") #tiiuae/falcon-7b-instruct #"TheBloke/Falcon-180B-Chat-GPTQ" 75 | parser.add_argument("--model_type", type=str, default="llama") 76 | parser.add_argument("--cllm_type", type=str, default="sharegpt") 77 | parser.add_argument("--debug", action="store_true") 78 | parser.add_argument("--chat", action="store_true") 79 | parser.add_argument("--dtype", type=str, default="float16") 80 | parser.add_argument("--device", type=str, default="cuda:0") 81 | parser.add_argument("--cache_dir", type=str, default="") 82 | parser.add_argument( 83 | "--max_new_tokens", 84 | type=int, 85 | default=16, 86 | help="n-token sequence size", 87 | ) 88 | parser.add_argument( 89 | "--max_new_seq_len", 90 | type=int, 91 | default=1024, 92 | help="Maximum new tokens to generate per response", 93 | ) 94 | args = parser.parse_args() 95 | 96 | if args.dtype == "float16": 97 | args.dtype = torch.float16 98 | elif args.dtype == "bfloat16": 99 | args.dtype = torch.bfloat16 100 | 101 | #if args.use_ds: 102 | config = transformers.AutoConfig.from_pretrained( 103 | args.model_path, 104 | cache_dir=args.cache_dir, 105 | ) 106 | model = transformers.AutoModelForCausalLM.from_pretrained( 107 | args.model_path, 108 | config=config, 109 | cache_dir=args.cache_dir, 110 | torch_dtype=torch.bfloat16, 111 | low_cpu_mem_usage=True, 112 | device_map='cuda', 113 | attn_implementation="flash_attention_2", 114 | ) 115 | tokenizer = transformers.AutoTokenizer.from_pretrained( 116 | args.model_path, 117 | cache_dir=args.cache_dir, 118 | model_max_length=2048, 119 | padding_side="right", 120 | ) 121 | 122 | user_input = "" 123 | num_rounds = 0 124 | if args.model_type == "llama": 125 | roles = ("USER", "ASSISTANT") #support vicuna 126 | else: 127 | assert False 128 | 129 | user_input = "" 130 | if args.model_type == "llama": 131 | system_prompt = get_system_prompt(args.cllm_type) 132 | else: 133 | raise NotImplementedError('Only LLaMA or LLaMA2 architecture is supported.') 134 | 135 | while True: 136 | num_rounds += 1 137 | if args.chat: 138 | model_input = input("USER: ") 139 | else: 140 | model_input = get_default_question(args.cllm_type) 141 | print("USER: " + model_input) 142 | 143 | new_inputs = get_instruction_template(system_prompt, roles, model_input, args.cllm_type) 144 | user_input += new_inputs 145 | 146 | print("ASSISTANT: " , flush=True, end="") 147 | inputs = tokenizer(user_input, return_tensors="pt").to(args.device) 148 | 149 | if not args.chat: 150 | tmp_greedy_output, _ = jacobi_generate(inputs, model, tokenizer, args.max_new_tokens, args.max_new_seq_len) #warmup 151 | 152 | os.environ["CHAT"] = "1" 153 | t0 = time.time() 154 | greedy_output, avg_fast_forwward_count = jacobi_generate(inputs, model, tokenizer, args.max_new_tokens, args.max_new_seq_len) 155 | 156 | t1 = time.time() 157 | 158 | os.environ["CHAT"] = "0" 159 | output = tokenizer.decode(greedy_output[0], skip_special_tokens=False) 160 | 161 | # re-initialize user input 162 | # TODO: support multi-turn conversation 163 | user_input = "" 164 | 165 | if args.debug: 166 | generated_tokens = len(greedy_output[0]) - inputs.input_ids.numel() 167 | print() 168 | print("======================================SUMMARY=======================================================") 169 | print("Generated tokens: ", generated_tokens,"Time: ", round(t1 - t0, 2), "s Throughput: ", round(generated_tokens / (t1 - t0), 2), "tokens/s", "Fast forwarding: ", round(avg_fast_forwward_count, 2), "tokens/step") 170 | print("====================================================================================================") 171 | if not args.chat: 172 | break 173 | 174 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | CLLM 3 |

4 | 5 |

 Consistency Large Language Models: A Family of Efficient Parallel Decoders

6 | 7 |

8 | | Paper | Blog | 9 |

10 | 11 |

12 | 13 | License 14 | 15 | 16 | Maintenance 17 | 18 | 19 | Contributions welcome 20 | 21 | 22 | Weights 23 | 24 |

25 | 26 | ## 27 | 28 | Consistency large language models (CLLMs) is a new family of models capable of reducing inference latency by efficiently decoding $n$ tokens in parallel. This decoding method is called [Jacobi decoding](https://arxiv.org/abs/2305.10427), which improves inference efficiency in comparison with conventional auto-regressive (AR) decoding. CLLMs are trained with the objective of performing efficient Jacobi decoding by mapping any randomly initialized $n$-token sequence to the same result as AR decoding in as few steps as possible. 29 | 30 | Experiment results have demonstrated the effectiveness of CLLMs, showing $2.4\times$ to $3.4\times$ improvements in generation speed on a variety of tasks. 31 |

32 | 33 | 34 | 35 |

36 | 37 | A demo of using CLLM to achieve significant improvements ($\sim3\times$) in generation speed to solve a basic math problem is shown below: 38 | 39 |

40 | 41 | 42 | 43 |

44 | 45 | ## Contents 46 | - [News](#news) 47 | - [Introduction](#introduction) 48 | - [Installation](#installation) 49 | - [Model Weights](#model-weights) 50 | - [Usage](#usage) 51 | - [Inference](#inference) 52 | - [Training](#training) 53 | - [Evaluation](#evaluation) 54 | - [Citation](#citation) 55 | 56 | ## News 🔥 57 | 58 | - [2024/3] CLLMs are integrated in [FastChat](https://github.com/lm-sys/FastChat/blob/main/docs/model_support.md)! 59 | - [2024/2] CLLM Paper now available on [arXiv](http://arxiv.org/abs/2403.00835). CLLMs model checkpoints are released on [Huggingface Hub](https://huggingface.co/cllm). 60 | 61 | ## Introduction 62 | Consistency Large Language Models (CLLMs) is a family of efficient parallel decoders refined from pre-trained LLMs. 63 | 64 | Compared with existing fast decoding techniques, CLLMs achieve fast parallel decoding **without the need for**: 65 | - Draft models 66 | - Architectural modifications/auxiliary model components 67 | 68 | This introduces a number of advantages for CLLMs: 69 | - CLLMs don't have to deal with the complexity of obtaining 'good' draft models and managing two different models in a single system. 70 | - CLLMs share the same architecture with target LLMs and require no additional engineering efforts when adopting the technique to different models. 71 | - CLLMs can be integrated seamlessly with other techniques for efficient LLM inference (e.g. Lookahead Decoding) to achieve even more significant speedup. 72 | 73 | ## Installation 74 | 1. Environment setup: 75 | ``` 76 | conda create -n cllm python=3.10 77 | conda activate cllm 78 | ``` 79 | 2. Clone this repository and build from source: 80 | ``` 81 | git clone git@github.com:hao-ai-lab/Consistency_LLM.git 82 | cd Consistency_LLM 83 | ``` 84 | 3. Install dependency: 85 | ``` 86 | pip install -r requirements.txt 87 | pip install flash-attn==2.4.1 88 | ``` 89 | ## Model Weights 90 | #### Target Pre-trained Models 91 | 92 | | Size | Dataset | Huggingface Repo | 93 | | ---- | -------- | --------------------------------------------- | 94 | | 7B | ShareGPT | [cllm/vicuna-7b-sharegpt-gpt4-48k](https://huggingface.co/cllm/vicuna-7b-sharegpt-gpt4-48k) | 95 | | 7B | GSM8K (Math) | [GAIR/Abel-7B-001](https://huggingface.co/GAIR/Abel-7B-001) | 96 | | 7B | Spider (Text-to-SQL) | [cllm/deepseekcoder-7b-instruct-spider](https://huggingface.co/cllm/deepseekcoder-7b-instruct-spider) | 97 | | 7B | Code-Search-Net Python | [cllm/deepseekcoder_7b_codesearch_net_python](https://huggingface.co/cllm/deepseekcoder_7b_codesearch_net_python) | 98 | 99 | #### CLLMs 100 | | Size | Dataset | Huggingface Repo | 101 | | ---- | -------- | --------------------------------------------- | 102 | | 7B | ShareGPT | [cllm/consistency-llm-7b-sharegpt48k](https://huggingface.co/cllm/consistency-llm-7b-sharegpt48k) | 103 | | 7B | GSM8K (Math) | [cllm/consistency-llm-7b-math](https://huggingface.co/cllm/consistency-llm-7b-math) | 104 | | 7B | Spider (Text-to-SQL) | [cllm/consistency-llm-7b-spider](https://huggingface.co/cllm/consistency-llm-7b-spider) | 105 | | 7B | Code-Search-Net Python | [cllm/consistency-llm-7b-codesearchnet](https://huggingface.co/cllm/consistency-llm-7b-codesearchnet) | 106 | 107 | ## Usage 108 | ### Inference 109 | ``` 110 | bash applications/run_chat_cllm.sh {model_path} {cllm_type} 111 | ``` 112 | `cllm_type` can take the value of `spider`, `python`, `gsm8k`, `sharegpt`. 113 | 114 | ### Training 115 | 1. Collect Jacobi trajectory: 116 | - Method 1: Directly download Jacobi trajectory to `data/collected_jacobi_trajectory/` from [our Huggingface Hub page](https://huggingface.co/cllm). 117 | - Method 2 (Generate trajectory suitable to your own target model and dataset): Some raw datasets that contain additional information like database dependency or cannot be directly loaded from Huggingface Hub (for example, [Spider](https://huggingface.co/datasets/cllm/spider) and [ShareGPT](https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered/blob/main/ShareGPT_V3_unfiltered_cleaned_split_no_imsorry.json) are required to be installed in `data/raw_data`). Then run `scripts/generate_trajectory.sh` and the training dataset for a CLLM will be saved in `data/collected_jacobi_trajectory/`. 118 | 119 | For example, for the gsm8k dataset, run: 120 | ``` 121 | # max_new_tokens corresponds to the size of n_token_sequence 122 | CUDA_VISIBLE_DEVICES=0 bash scripts/generate_trajectory.sh {filename} {model_path} {n_token_seq_size} {max_new_seq_len} 123 | ``` 124 | ##### Other command options 125 | ``` 126 | --filename: path to the raw dataset, currently supporting {data/raw_data/spider, code_search_net, data/raw_data/gsm8k_train.jsonl, data/raw_data/ShareGPT_V3_unfiltered_cleaned_split.json} \ 127 | --data_size: maximum number of prompts used to extract Jacobi trajectories \ 128 | --use_aug: use data augmentation technique \ 129 | --use_labels: add dataset's labels to the output file 130 | ``` 131 | 132 | 2. Train a CLLM: 133 | ``` 134 | bash scripts/train_cllm.sh {model_path} {trajectory_file} {output_path} {n_token_seq_size} 135 | ``` 136 | 137 | ### Evaluation 138 | We follow the same settings in [human-eval](https://github.com/openai/human-eval), [Spider](https://github.com/taoyds/spider), [MT-bench](https://github.com/lm-sys/FastChat/tree/main/fastchat/llm_judge) and [GSM8K](https://github.com/openai/grade-school-math) evaluate CLLMs' generation quality. An example code to evaluate CLLMs' throughput measured in tokens/s, fast-forwarded token count, stationary token count can be found in `eval` folder. Take GSM8K dataset as an example: 139 | 140 | To test the speedup, run: 141 | ``` 142 | CUDA_VISIBLE_DEVICES=0 bash eval/gsm8k/speedup.sh {model_path} {target_model_path} {max_new_tokens} 143 | ``` 144 | To test the accuracy, run: 145 | ``` 146 | CUDA_VISIBLE_DEVICES=0 python eval/gsm8k/acc.py --model_dir path_to_cllm --temperature 0.0 --top_p 1.0 --output_file_name 'cllm_generated_gsm8k.jsonl' \ 147 | --dev_set "gsm8k" --prompt_type math-single --max_new_tokens_for_consistency 16 --max_tokens 1024 --use_consistency_decoding 148 | ``` 149 | ## Citation 150 | This is the official project repository for the following paper. If you find this repository helpful, Please kindly cite: 151 | ``` 152 | @misc{kou2024cllms, 153 | title={CLLMs: Consistency Large Language Models}, 154 | author={Siqi Kou and Lanxiang Hu and Zhezhi He and Zhijie Deng and Hao Zhang}, 155 | year={2024}, 156 | eprint={2403.00835}, 157 | archivePrefix={arXiv}, 158 | primaryClass={cs.CL} 159 | } 160 | ``` 161 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /cllm/train_cllm_global.py: -------------------------------------------------------------------------------- 1 | # This code is based on tatsu-lab/stanford_alpaca. Below is the original copyright: 2 | # 3 | # Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from dataclasses import dataclass, field 18 | import json 19 | import math 20 | import pathlib 21 | from typing import Dict, Optional 22 | 23 | import os 24 | import sys 25 | import torch 26 | from torch.utils.data import Dataset 27 | import transformers 28 | from transformers.trainer_pt_utils import LabelSmoother, get_module_class_from_name 29 | import datasets 30 | 31 | from torch.distributed.fsdp import FullyShardedDataParallel as FSDP 32 | 33 | from typing import Dict 34 | 35 | from cllm_trainer_global import CllmTrainer 36 | 37 | from peft import LoraConfig, TaskType, get_peft_model, prepare_model_for_kbit_training 38 | 39 | import logging 40 | logger = logging.getLogger(__name__) 41 | 42 | IGNORE_TOKEN_ID = LabelSmoother.ignore_index 43 | 44 | 45 | @dataclass 46 | class ModelArguments: 47 | target_model_path: Optional[str] = field( 48 | default="models/vicuna-7b-v1.5", metadata={"help": "Path to target model"}) 49 | qlora: Optional[bool] = field(default=False, metadata={"help": "Enable QLoRA processing"}) 50 | 51 | @dataclass 52 | class DataArguments: 53 | data_path: str = field( 54 | default=None, metadata={"help": "Path to the training data."} 55 | ) 56 | lazy_preprocess: bool = False 57 | 58 | @dataclass 59 | class TrainingArguments(transformers.TrainingArguments): 60 | cache_dir: Optional[str] = field(default=None) 61 | optim: str = field(default="adamw_torch") 62 | model_max_length: int = field( 63 | default=512, 64 | metadata={ 65 | "help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)." 66 | }, 67 | ) 68 | max_new_tokens: int = field( 69 | default=16, 70 | metadata={ 71 | "help": "Size of n_token_sequence in Jacobi trajectory." 72 | }, 73 | ) 74 | use_gt_labels: bool = False 75 | report_to: str = field( 76 | default='wandb', 77 | metadata={ 78 | 'help': 'The list of integrations to report the results and logs to.' 79 | } 80 | ) 81 | 82 | def rank0_print(local_rank, *args): 83 | if local_rank == 0: 84 | print(*args) 85 | 86 | def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str): 87 | """Collects the state dict and dump to disk.""" 88 | state_dict = trainer.model.state_dict() 89 | if trainer.args.should_save: 90 | cpu_state_dict = {key: value.cpu() 91 | for key, value in state_dict.items()} 92 | del state_dict 93 | trainer._save(output_dir, state_dict=cpu_state_dict) # noqa 94 | 95 | def preprocess_distill_data( 96 | prompt_ids, 97 | answer_trajectory_ids, 98 | teacher_output_ids, 99 | complete_teacher_output_ids, 100 | tokenizer: transformers.PreTrainedTokenizer, 101 | model: str, 102 | labels_ids=None, 103 | ) -> Dict: 104 | 105 | jacobian_trajectory_ids = [] 106 | # only take batch size 1 for now 107 | # TODO: support bsz > 1 from the generation script. for now, only prompt ids is in (bsz, seq_len) 108 | jacobian_prompt_ids = torch.tensor(prompt_ids[0], dtype=torch.int64) 109 | teacher_output_ids = torch.tensor(teacher_output_ids[0], dtype=torch.int64) 110 | complete_teacher_output_ids = torch.tensor(complete_teacher_output_ids, dtype=torch.int64) 111 | for answer_ids in answer_trajectory_ids: 112 | answer_ids = torch.tensor(answer_ids, dtype=torch.int64) 113 | #print(answer_ids) 114 | #print(jacobian_prompt_ids) 115 | if len(jacobian_prompt_ids.shape) == len(answer_ids.shape): 116 | trajectory_ids = torch.cat((jacobian_prompt_ids, answer_ids), dim=-1) 117 | elif len(jacobian_prompt_ids.shape) > len(answer_ids.shape): 118 | #print(f'prompt: {jacobian_prompt_ids.shape}') 119 | #print(f'answer: {answer_ids.shape}') 120 | trajectory_ids = torch.cat((jacobian_prompt_ids[0], answer_ids), dim=-1) 121 | # print(trajectory_ids.shape) # torch.Size([228]) 122 | jacobian_trajectory_ids.append(trajectory_ids) 123 | 124 | if labels_ids: 125 | return dict( 126 | jacobian_trajectory=jacobian_trajectory_ids, 127 | attention_mask=jacobian_trajectory_ids[0].ne(tokenizer.pad_token_id), 128 | labels_ids=labels_ids, 129 | teacher_output_ids=teacher_output_ids, 130 | complete_teacher_output_ids=complete_teacher_output_ids 131 | ) 132 | else: 133 | return dict( 134 | jacobian_trajectory=jacobian_trajectory_ids, 135 | attention_mask=jacobian_trajectory_ids[0].ne(tokenizer.pad_token_id), 136 | teacher_output_ids=teacher_output_ids, 137 | complete_teacher_output_ids=complete_teacher_output_ids 138 | ) 139 | 140 | class JacobianDataset(Dataset): 141 | """Dataset for consistency training.""" 142 | 143 | def __init__(self, raw_data, 144 | tokenizer: transformers.PreTrainedTokenizer, 145 | model: str, 146 | do_eval: bool = False, 147 | local_rank: int = -1): 148 | super(JacobianDataset, self).__init__() 149 | self.tokenizer = tokenizer 150 | 151 | rank0_print(local_rank, "Formatting inputs...Skip in lazy mode") 152 | self.tokenizer = tokenizer 153 | self.raw_data = raw_data 154 | self.cached_data_dict = {} 155 | self.do_eval = do_eval 156 | self.model = model 157 | 158 | def __len__(self): 159 | return len(self.raw_data) 160 | 161 | def __getitem__(self, i) -> Dict: 162 | if i in self.cached_data_dict: 163 | return self.cached_data_dict[i] 164 | if 'labels_ids' in self.raw_data[i].keys(): 165 | ret = preprocess_distill_data(self.raw_data[i]["prompt_ids"], 166 | self.raw_data[i]["answer_trajectory_ids"], 167 | self.raw_data[i]["teacher_output_ids"], 168 | self.raw_data[i]["complete_teacher_output_ids"], 169 | self.tokenizer, 170 | self.model, 171 | labels_ids=self.raw_data[i]["labels_ids"]) 172 | else: 173 | ret = preprocess_distill_data(self.raw_data[i]["prompt_ids"], 174 | self.raw_data[i]["answer_trajectory_ids"], 175 | self.raw_data[i]["teacher_output_ids"], 176 | self.raw_data[i]["complete_teacher_output_ids"], 177 | self.tokenizer, 178 | self.model) 179 | self.cached_data_dict[i] = ret 180 | 181 | return ret 182 | 183 | 184 | def make_jacobian_data_module( 185 | tokenizer: transformers.PreTrainedTokenizer, 186 | trajectory_path, 187 | data_args, 188 | model: str, 189 | local_rank: int, 190 | ) -> Dict: 191 | """Make dataset and collator for consistency training.""" 192 | assert data_args.lazy_preprocess, "only support lazy process" 193 | dataset_cls = JacobianDataset 194 | rank0_print("Loading data...") 195 | 196 | train_json = json.load(open(trajectory_path, "r")) 197 | truncated_train_json = [] 198 | 199 | for data in train_json: 200 | # take prompt lengths with limited size if necessary 201 | truncated_train_json.append(data) 202 | train_dataset = dataset_cls(truncated_train_json, 203 | tokenizer=tokenizer, 204 | model=model, 205 | local_rank=local_rank) 206 | eval_dataset = None 207 | 208 | return dict(train_dataset=train_dataset, eval_dataset=eval_dataset) 209 | 210 | 211 | def train(): 212 | parser = transformers.HfArgumentParser( 213 | (ModelArguments, DataArguments, TrainingArguments) 214 | ) 215 | model_args, data_args, training_args = parser.parse_args_into_dataclasses() 216 | local_rank = int(os.environ["LOCAL_RANK"]) 217 | training_args.local_rank = local_rank 218 | training_args.qlora = model_args.qlora 219 | 220 | torch.set_default_dtype(torch.float) 221 | 222 | # Setup logging 223 | logging.basicConfig( 224 | format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", 225 | datefmt="%m/%d/%Y %H:%M:%S", 226 | handlers=[logging.StreamHandler(sys.stdout)], 227 | ) 228 | 229 | if training_args.should_log: 230 | # The default of training_args.log_level is passive, so we set log level at info here to have that default. 231 | transformers.utils.logging.set_verbosity_info() 232 | 233 | log_level = training_args.get_process_log_level() 234 | logger.setLevel(log_level) 235 | datasets.utils.logging.set_verbosity(log_level) 236 | transformers.utils.logging.set_verbosity(log_level) 237 | transformers.utils.logging.enable_default_handler() 238 | transformers.utils.logging.enable_explicit_format() 239 | 240 | # Log on each process the small summary: 241 | logger.warning( 242 | f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" 243 | + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" 244 | ) 245 | logger.info(f"Training/evaluation parameters {training_args}") 246 | 247 | # Set RoPE scaling factor 248 | config = transformers.AutoConfig.from_pretrained( 249 | model_args.target_model_path, 250 | cache_dir=training_args.cache_dir, 251 | ) 252 | orig_ctx_len = getattr(config, "max_position_embeddings", None) 253 | if orig_ctx_len and training_args.model_max_length > orig_ctx_len: 254 | scaling_factor = float( 255 | math.ceil(training_args.model_max_length / orig_ctx_len)) 256 | config.rope_scaling = {"type": "linear", "factor": scaling_factor} 257 | config.use_cache = False 258 | 259 | # Load model and tokenizer 260 | model = transformers.AutoModelForCausalLM.from_pretrained( 261 | model_args.target_model_path, 262 | config=config, 263 | cache_dir=training_args.cache_dir, 264 | attn_implementation='flash_attention_2', 265 | device_map='cuda', 266 | torch_dtype=torch.bfloat16, 267 | ) 268 | 269 | tokenizer = transformers.AutoTokenizer.from_pretrained( 270 | model_args.target_model_path, 271 | padding_side="right", 272 | use_fast=False, 273 | ) 274 | if 'vicuna' in model_args.target_model_path: 275 | tokenizer.pad_token = tokenizer.unk_token 276 | 277 | if model_args.qlora: 278 | # Runs w/ qLoRA when qlora tag is enabled is enabled 279 | model = prepare_model_for_kbit_training(model) 280 | config = LoraConfig( 281 | task_type=TaskType.CAUSAL_LM, 282 | r=32, 283 | lora_alpha=16, 284 | lora_dropout=0.05, 285 | ) 286 | 287 | model = get_peft_model(model, config) 288 | model.config.use_cache = False 289 | 290 | # Load data 291 | data_module = make_jacobian_data_module(tokenizer=tokenizer, 292 | trajectory_path=data_args.data_path, 293 | data_args=data_args, 294 | model=model_args.target_model_path, 295 | local_rank=training_args.local_rank) 296 | 297 | trainer = CllmTrainer( 298 | model=model, tokenizer=tokenizer, args=training_args, **data_module 299 | ) 300 | 301 | if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")): 302 | trainer.train(resume_from_checkpoint=False) 303 | else: 304 | trainer.train() 305 | model.config.use_cache = True 306 | trainer.save_state() 307 | safe_save_model_for_hf_trainer( 308 | trainer=trainer, output_dir=training_args.output_dir) 309 | 310 | 311 | if __name__ == "__main__": 312 | train() 313 | -------------------------------------------------------------------------------- /eval/gsm8k/acc.py: -------------------------------------------------------------------------------- 1 | import transformers 2 | import os 3 | import re 4 | import json 5 | import jsonlines 6 | import argparse 7 | import torch 8 | from tqdm import tqdm 9 | import sys 10 | import pdb 11 | import random 12 | from math_normalization import * 13 | 14 | def consistency_generate( 15 | model, 16 | tokenizer, 17 | inputs, 18 | max_new_tokens, 19 | max_new_seq_len 20 | ): 21 | itr = 0 22 | while True: 23 | if itr == 0: 24 | input_ids = inputs['input_ids'] 25 | input_masks = inputs['attention_mask'] 26 | else: 27 | input_masks = torch.ones_like(input_ids).to(input_ids.device) 28 | for j in range(bsz): 29 | input_masks[j][torch.sum(inputs["attention_mask"], dim=-1)[j] + itr*max_new_tokens:] = 0 30 | 31 | bsz = input_ids.shape[0] 32 | eos_reached = torch.tensor([False] * bsz, device="cuda") 33 | generation = get_jacobian_trajectory(model, tokenizer, input_ids, input_masks, max_new_tokens) 34 | ### tokens generated after are set to 35 | for j in range(bsz): 36 | prompt_len = torch.sum(input_masks, dim=-1) 37 | eos_positions = torch.where(generation[j]==tokenizer.eos_token_id)[0] 38 | if len(eos_positions)==0: 39 | # no EOS, continue to the next item in the batch 40 | total_token_len = prompt_len + max_new_tokens 41 | continue 42 | # otherwise, set tokens coming after EOS as pad 43 | eos_reached[j] = True 44 | total_token_len = int(eos_positions[0]) 45 | 46 | ### see if next max_new_tokens should be generated & if True, update weights and prepare new input_ids 47 | itr+=1 48 | if all(eos_reached) or itr*max_new_tokens >= max_new_seq_len: 49 | return generation[0, :total_token_len] 50 | input_ids = generation 51 | 52 | @torch.inference_mode() 53 | def get_jacobian_trajectory( 54 | model, 55 | tokenizer, 56 | input_ids, 57 | attention_mask, 58 | max_new_tokens 59 | ): 60 | 61 | bsz = input_ids.shape[0] 62 | prompt_len = [torch.sum(t) for t in attention_mask] 63 | max_prompt_len = max(prompt_len) 64 | total_len = max_prompt_len + max_new_tokens 65 | 66 | # initialize the first point of jacobian trajectory 67 | tokens = torch.full((bsz, total_len), tokenizer.pad_token_id, dtype=torch.long, device="cuda") 68 | for i in range(bsz): 69 | tokens[i, :] = torch.tensor(random.choices(input_ids[i][attention_mask[i]==1], k=total_len), dtype=torch.long, device="cuda") 70 | tokens[i, : prompt_len[i]] = torch.tensor(input_ids[i][: prompt_len[i]], dtype=torch.long, device="cuda") 71 | itr = 0 72 | next_generation = tokens 73 | generate_attention_mask = torch.full_like(next_generation, 1).to(tokens.device) 74 | while True: 75 | 76 | current_generation = next_generation 77 | with torch.no_grad(): 78 | logits = model(current_generation, generate_attention_mask).logits 79 | next_generation = torch.argmax(torch.nn.functional.softmax(logits, dim=-1), dim=-1) 80 | 81 | # hold prompt unchanged and update generated tokens 82 | for i in range(bsz): 83 | next_generation[i, :] = torch.cat((tokens[i, :prompt_len[i]], next_generation[i, prompt_len[i]-1:total_len-1]), dim=0) 84 | if torch.all(torch.eq(next_generation, current_generation)).item(): 85 | print(f"Iteration steps: {itr}") 86 | return next_generation # right generation is saved twice so we delete the last element of trajectory list 87 | itr+=1 88 | 89 | def get_results(pred_file, dev_set): 90 | def test_answer(pred_str, ans_str): 91 | pattern = "#### (.*)$" 92 | 93 | if "Question" in pred_str: 94 | pred_str = pred_str.split("Question")[0] 95 | 96 | preds = re.findall(pattern, pred_str) 97 | pred = preds[-1] if len(preds) >= 1 else "" 98 | if "" in pred: 99 | pred = pred[:-4] 100 | 101 | gold = ans_str 102 | pred = normalize_final_answer(pred) 103 | gold = normalize_final_answer(gold) 104 | return check_sympy_equivalence(gold, pred), pred, gold 105 | 106 | def parse_pred_ans(preds_str, golds_str, properties_list): 107 | num_q = 0 108 | acc = 0 109 | results = [] 110 | preds = [] 111 | golds = [] 112 | correct_table = {} 113 | cnt_table = {} 114 | source_set = set() 115 | for pred_str, gold_str, properties in tqdm(zip(preds_str, golds_str, properties_list), total=len(preds_str)): 116 | num_q += 1 117 | result, pred, gold = test_answer(pred_str, gold_str) 118 | results.append(result) 119 | preds.append(pred) 120 | golds.append(gold) 121 | if result: 122 | acc += 1 123 | source = properties['source'] 124 | tag = properties['tag'] 125 | source_set.add(source) 126 | if source not in correct_table.keys(): 127 | correct_table[source] = 1 if result else 0 128 | cnt_table[source] = 1 129 | else: 130 | correct_table[source] = (correct_table[source] + 1) if result else correct_table[source] 131 | cnt_table[source] += 1 132 | for key in tag.keys(): 133 | value = tag[key] 134 | value = source+","+key+"__"+value 135 | if value not in correct_table.keys(): 136 | correct_table[value] = 1 if result else 0 137 | cnt_table[value] = 1 138 | else: 139 | correct_table[value] = (correct_table[value] + 1) if result else correct_table[value] 140 | cnt_table[value] += 1 141 | print('num_q %d correct %d ratio %.4f' % (num_q, acc, float(acc / num_q))) 142 | acc_table = {} 143 | for key in correct_table.keys(): 144 | acc_table[key] = correct_table[key] / cnt_table[key] 145 | acc_table = list(zip(acc_table.keys(), acc_table.values())) 146 | acc_table.sort(key=lambda x: x[0]) 147 | for key, acc in acc_table: 148 | if key in source_set: 149 | print(key+" : "+str(acc)) 150 | else: 151 | print(" " + key.split(",")[-1]+ " : " + str(acc)) 152 | return results, preds, golds 153 | 154 | if dev_set in ['all', 'gsm8k', 'math', 'mathgpt', 'gsm8k_robust']: 155 | golds_str = [] 156 | properties = [] 157 | with open(f'test.jsonl', 'r', encoding='utf-8') as f: 158 | for line in f: 159 | if dev_set != "all": 160 | if json.loads(line)['source'].lower() == dev_set: 161 | golds_str.append(json.loads(line)['target']) 162 | properties.append({"source": json.loads(line)['source'], "tag": json.loads(line)['tag']}) 163 | else: 164 | golds_str.append(json.loads(line)['target']) 165 | properties.append({"source": json.loads(line)['source'], "tag": json.loads(line)['tag']}) 166 | preds_str = [] 167 | with open(pred_file, 'r', encoding='utf-8') as f: 168 | for line in f: 169 | preds_str.append(json.loads(line)['response']) 170 | results, preds, golds = parse_pred_ans(preds_str, golds_str, properties) 171 | with open(pred_file, 'r', encoding='utf-8') as f: 172 | data = [json.loads(line) for line in f] 173 | for i, line in enumerate(data): 174 | line['pred'] = preds[i] 175 | line['gold'] = golds[i] 176 | line['result'] = results[i] 177 | 178 | # Save the updated list of dictionaries back to the jsonl file 179 | with open(pred_file, 'w') as file: 180 | for item in data: 181 | file.write(json.dumps(item) + '\n') 182 | 183 | else: 184 | raise NotImplementedError("Evaluation not supported.") 185 | 186 | 187 | def get_raw_inputs(dev_set): 188 | # in this function, we will get the raw queries for a target dev set 189 | data = [] 190 | if dev_set in ['all', 'gsm8k', 'math', 'mathgpt', 'gsm8k_robust']: 191 | with open(f'test.jsonl') as f: 192 | for line in jsonlines.Reader(f): 193 | data.append(line) 194 | if dev_set != 'all': 195 | data = [line for line in data if line['source'].lower() == dev_set] 196 | else: 197 | raise ValueError 198 | 199 | prompt_list = [line['question'] for line in data] 200 | return prompt_list 201 | 202 | 203 | prompt_mapping = { 204 | "math-single": "Question:\n{input}\nAnswer:\nLet's think step by step.\n", 205 | } 206 | 207 | if __name__ == '__main__': 208 | # set args 209 | parser = argparse.ArgumentParser() 210 | parser.add_argument('--model_dir', type=str, required=True) 211 | parser.add_argument('--max_tokens', type=int, default=2048) 212 | parser.add_argument('--temperature', type=float, default=0.0) 213 | parser.add_argument('--top_p', type=float, default=1.0) 214 | parser.add_argument('--presence_penalty', type=float, default=0.0) 215 | parser.add_argument('--frequency_penalty', type=float, default=0.0) 216 | parser.add_argument('--output_file_name', type=str, default='output.json') 217 | parser.add_argument('--stop', type=str, nargs='+', default=[], help="you can pass one or multiple stop strings to halt the generation process.") 218 | parser.add_argument('--dev_set', type=str, default='all') 219 | parser.add_argument('--prompt_type', type=str, default='math-single') 220 | parser.add_argument('--sample_num', type=int, default=-1, ) 221 | parser.add_argument('--eval_only', action="store_true") 222 | parser.add_argument('--max_num_batched_tokens', type=int, default=2048) 223 | parser.add_argument( 224 | "--use_consistency_decoding", 225 | action="store_true", 226 | help="Whether to use consistency decoding", 227 | ) 228 | parser.add_argument( 229 | "--max_new_tokens_for_consistency", 230 | type=int, 231 | default=16, 232 | help="The n-gram for consistency decoding.", 233 | ) 234 | args = parser.parse_args() 235 | max_new_token = args.max_tokens 236 | if args.eval_only == False: 237 | # part 1 we set the model and tokenizer 238 | model = transformers.AutoModelForCausalLM.from_pretrained( 239 | args.model_dir, 240 | torch_dtype=torch.bfloat16, 241 | low_cpu_mem_usage=True, 242 | device_map='cuda', 243 | ) 244 | tokenizer = transformers.AutoTokenizer.from_pretrained( 245 | args.model_dir, 246 | padding_side="right", 247 | use_fast=False, 248 | ) 249 | print('>>>>>> model and tokenizer loaded') 250 | 251 | # part 2 we prepare raw queries and wrap them with target prompt 252 | raw_queries = get_raw_inputs(args.dev_set) 253 | prompt = prompt_mapping[args.prompt_type] 254 | processed_prompts = [prompt.format(input=query) for query in raw_queries] 255 | processed_prompts = processed_prompts[:args.sample_num] if args.sample_num > 0 else processed_prompts 256 | 257 | outputs = [] 258 | # part 3 we generate answers 259 | for processed_prompt in tqdm(processed_prompts): 260 | 261 | input_ids = tokenizer([processed_prompt]).input_ids 262 | if args.use_consistency_decoding: 263 | output_ids = consistency_generate( 264 | model, 265 | tokenizer, 266 | tokenizer([processed_prompt], return_tensors="pt").to(model.device), 267 | max_new_tokens=args.max_new_tokens_for_consistency, 268 | max_new_seq_len=max_new_token, 269 | ) 270 | output_ids = output_ids.unsqueeze(dim=0) 271 | else: 272 | output_ids = model.generate( 273 | torch.as_tensor(input_ids).cuda(), 274 | do_sample=False, 275 | # temperature=args.temperature, 276 | max_new_tokens=max_new_token, 277 | ) 278 | if model.config.is_encoder_decoder: 279 | output_ids = output_ids[0] 280 | else: 281 | output_ids = output_ids[0][len(input_ids[0]) :] 282 | 283 | output = tokenizer.decode( 284 | output_ids, 285 | spaces_between_special_tokens=False, 286 | ) 287 | for special_token in tokenizer.special_tokens_map.values(): 288 | if isinstance(special_token, list): 289 | for special_tok in special_token: 290 | output = output.replace(special_tok, "") 291 | else: 292 | output = output.replace(special_token, "") 293 | output = output.strip() 294 | outputs.append({'prompt': processed_prompt, 'answer': output}) 295 | print('>>>>>> generation done') 296 | 297 | # part 5 we save the results, always be {'id':id,'response':response} 298 | # if dir of output file is not exist, it will be created automatically 299 | with open(args.output_file_name, "w") as f: 300 | for id, output in enumerate(outputs): 301 | # note that `prompt`s are the wrapped ones 302 | f.write(json.dumps({'id': id, 'prompt': output['prompt'], 'response': output['answer']}) + '\n') 303 | print('>>>>>> writing prediction done') 304 | 305 | # part 6 evaluate, I guess this should be done in a separate script 306 | get_results(args.output_file_name, args.dev_set) 307 | print('>>>>>> evaluation done') 308 | 309 | 310 | # CUDA_VISIBLE_DEVICES=0 acc.py --model_dir path_to_cllm --temperature 0.0 --top_p 1.0 --output_file_name 'cllm_generated_gsm8k.jsonl' --dev_set "gsm8k" --prompt_type math-single --max_new_tokens_for_consistency 16 --max_tokens 1024 --use_consistency_decoding -------------------------------------------------------------------------------- /data/generate_trajectory.py: -------------------------------------------------------------------------------- 1 | import json 2 | from transformers import AutoTokenizer, LlamaForCausalLM 3 | from fastchat.model.model_adapter import get_conversation_template 4 | import torch 5 | from tqdm import tqdm 6 | import random 7 | import argparse 8 | from datasets import load_dataset 9 | import datasets 10 | import transformers 11 | import sqlite3 12 | import json 13 | from dataclasses import dataclass, field 14 | from typing import Optional, Dict, Sequence 15 | import copy 16 | 17 | import numpy as np 18 | 19 | import os 20 | import sys 21 | from pathlib import Path 22 | 23 | path_root = Path(__file__).parents[1] 24 | sys.path.append(str(path_root)) 25 | 26 | from cllm.utils import jacobian_generated_data_postprocessed 27 | 28 | IGNORE_INDEX = -100 29 | EOT_TOKEN = "<|EOT|>" 30 | 31 | def build_instruction_prompt(instruction: str): 32 | return '''### Instruction: 33 | {} 34 | ### Response: 35 | '''.format(instruction.strip()).lstrip() 36 | 37 | def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict: 38 | """Tokenize a list of strings.""" 39 | tokenized_list = [ 40 | tokenizer( 41 | text, 42 | return_tensors="pt", 43 | padding="longest", 44 | max_length=tokenizer.model_max_length, 45 | truncation=True, 46 | ) 47 | for text in strings 48 | ] 49 | 50 | input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list] 51 | input_ids_lens = labels_lens = [ 52 | tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list 53 | ] 54 | 55 | return dict( 56 | input_ids=input_ids, 57 | labels=labels, 58 | input_ids_lens=input_ids_lens, 59 | labels_lens=labels_lens, 60 | ) 61 | 62 | 63 | def preprocess( 64 | sources: Sequence[str], 65 | targets: Sequence[str], 66 | tokenizer: transformers.PreTrainedTokenizer, 67 | ) -> Dict: 68 | """Preprocess the data by tokenizing.""" 69 | 70 | examples = [s + t for s, t in zip(sources, targets)] 71 | examples_tokenized, sources_tokenized = [_tokenize_fn(strings, tokenizer) for strings in (examples, sources)] 72 | input_ids = examples_tokenized["input_ids"] 73 | sources_input_ids = sources_tokenized["input_ids"] 74 | 75 | labels = copy.deepcopy(input_ids) 76 | 77 | return dict(sources_input_ids=sources_input_ids, sources_len=sources_tokenized["input_ids_lens"], labels_ids=labels) 78 | 79 | def preprocess_sharegpt(data, tokenizer): 80 | 81 | train_dataset = [] 82 | for i in tqdm(range(len(data))): 83 | d = data[i] 84 | #if len(d["conversations"]) > 2: 85 | # continue 86 | prompt = d["conversations"][0]["value"] 87 | 88 | if len(prompt) > 1024: 89 | # exclude prompts that are too long 90 | continue 91 | 92 | conv = get_conversation_template(model_path) 93 | conv.append_message(conv.roles[0], prompt) 94 | conv.append_message(conv.roles[1], "") 95 | prompt_with_template = conv.get_prompt() 96 | 97 | #jacobian_prompt = prompt_with_template 98 | prompt_with_template_ids = tokenizer(prompt_with_template, return_tensors="pt")['input_ids'] 99 | inputs = torch.Tensor(prompt_with_template_ids).unsqueeze(0).to(dtype=torch.int) 100 | 101 | labels = tokenizer(prompt_with_template + d["conversations"][1]["value"], return_tensors="pt")['input_ids'][0] 102 | labels_ids = torch.concat((labels, torch.tensor([tokenizer.eos_token_id])), dim=-1).to(dtype=torch.int) 103 | 104 | train_dataset.append(dict(sources_input_ids=inputs, sources_len=[ 105 | input.ne(tokenizer.pad_token_id).sum().item() for input in inputs], labels_ids=labels_ids)) 106 | 107 | 108 | return train_dataset 109 | 110 | def train_tokenize_function_spider(examples, tokenizer): 111 | db_ids = [id for id in examples['db_id']] 112 | 113 | prompts = [] 114 | for db_name in db_ids: 115 | db_path = f"data/raw_data/spider/database/{db_name}/{db_name}.sqlite" 116 | con = sqlite3.connect(db_path) 117 | cursor = con.cursor() 118 | cursor.execute('SELECT name FROM sqlite_master WHERE type="table";') 119 | curr_table = cursor.fetchall() 120 | 121 | table_rows = {} 122 | for table in curr_table: 123 | table_name = str(table[0]) 124 | 125 | cursor_t = con.execute(f"SELECT * from {table_name}") 126 | names = list(map(lambda x: x[0], cursor_t.description)) 127 | table_rows[table_name] = names 128 | cursor_t.close() 129 | 130 | cursor.close() 131 | con.close() 132 | 133 | database_info = "The SQL database has " 134 | for k, v in table_rows.items(): 135 | database_info = database_info + f"table named {k} with columns {v}, " 136 | 137 | prefix= "Could you translate the following question into SQL. Please only generate SQL, don't include explanation in the answer. " 138 | prompt = prefix + database_info + "Question: " 139 | prompts.append(prompt) 140 | 141 | sources = [ 142 | build_instruction_prompt(prompt+instruction) 143 | for prompt, instruction in zip(prompts, examples['question']) 144 | ] 145 | targets = [f"{output}\n{EOT_TOKEN}" for output in examples['query']] 146 | 147 | data_dict = preprocess(sources, targets, tokenizer) 148 | return data_dict 149 | 150 | def preprocess_gsm8k( 151 | processed_prompts, 152 | answers, 153 | tokenizer: transformers.PreTrainedTokenizer, 154 | ) -> Dict: 155 | train_dataset = [] 156 | for processed_prompt, answer in zip(processed_prompts, answers): 157 | # Tokenize conversations 158 | inputs = tokenizer( 159 | processed_prompt, 160 | return_tensors="pt", 161 | ).input_ids 162 | labels_ids = tokenizer( 163 | processed_prompt+answer, 164 | return_tensors="pt", 165 | ).input_ids 166 | train_dataset.append(dict(sources_input_ids=inputs, sources_len=[ 167 | input.ne(tokenizer.pad_token_id).sum().item() for input in inputs], labels_ids=labels_ids)) 168 | 169 | return train_dataset 170 | 171 | def train_tokenize_function_code_search_net(examples, tokenizer): 172 | prompt = "Please generate code based on the following doc:\n" 173 | 174 | sources = [ 175 | build_instruction_prompt(prompt+instruction) for instruction in examples['func_documentation_string'] 176 | ] 177 | targets = [f"{output}\n{EOT_TOKEN}" for output in examples['func_code_string']] 178 | 179 | data_dict = preprocess(sources, targets, tokenizer) 180 | return data_dict 181 | 182 | ####### Get jacobian trajectory ####### 183 | @torch.inference_mode() 184 | def get_jacobian_trajectory( 185 | model, 186 | tokenizer, 187 | input_ids, 188 | attention_mask, 189 | max_new_tokens 190 | ): 191 | 192 | bsz = input_ids.shape[0] 193 | prompt_len = [torch.sum(t) for t in attention_mask] 194 | max_prompt_len = max(prompt_len) 195 | total_len = max_prompt_len + max_new_tokens 196 | 197 | # initialize the first point of jacobian trajectory 198 | tokens = torch.full((bsz, total_len), tokenizer.pad_token_id, dtype=torch.long, device="cuda") 199 | 200 | for i in range(bsz): 201 | tokens[i, :] = torch.tensor(random.choices(input_ids[i][attention_mask[i]==1], k=total_len)).to(dtype=torch.long, device="cuda") 202 | tokens[i, : prompt_len[i]] = torch.tensor(input_ids[i][: prompt_len[i]], dtype=torch.long, device="cuda") 203 | trajectory = [] 204 | logits_trajectory = [] 205 | next_generation = tokens 206 | generate_attention_mask = torch.full_like(next_generation, 1).to(model.device) 207 | trajectory.append(tokens) 208 | itr=0 209 | while True: 210 | 211 | current_generation = next_generation 212 | logits = model(current_generation, generate_attention_mask).logits 213 | logits_trajectory.append(logits) 214 | next_generation = torch.argmax(torch.nn.functional.softmax(logits, dim=-1) / 0.01, dim=-1) 215 | 216 | # hold prompt unchanged and update generated tokens 217 | for i in range(bsz): 218 | next_generation[i, :] = torch.cat((tokens[i, :prompt_len[i]], next_generation[i, prompt_len[i]-1:total_len-1]), dim=0) 219 | trajectory.append(next_generation) 220 | if torch.all(torch.eq(next_generation, current_generation)).item(): 221 | eos_reached = len(torch.where(trajectory[-1] == tokenizer.eos_token_id)[0])>0 222 | return trajectory[:-1], logits_trajectory[-1], eos_reached # converged generation is saved twice so we delete the last element of trajectory list 223 | itr+=1 224 | 225 | def main(filename, model, tokenizer, max_new_tokens, max_new_seq_len, use_aug, use_labels, data_size): 226 | 227 | if 'sharegpt' in filename.lower(): 228 | with open(filename) as f: 229 | data = json.load(f) 230 | 231 | train_dataset = preprocess_sharegpt(data, tokenizer) 232 | elif 'spider' in filename.lower(): #use another preprocess method when training with spider dataset 233 | raw_train_datasets = datasets.load_dataset('spider', split='train') 234 | 235 | train_dataset = raw_train_datasets.map( 236 | train_tokenize_function_spider, 237 | batched=True, 238 | batch_size=3000, 239 | num_proc=32, 240 | remove_columns=raw_train_datasets.column_names, 241 | load_from_cache_file=True, # not args.overwrite_cache 242 | desc="Running Encoding", 243 | fn_kwargs={"tokenizer": tokenizer} 244 | ) 245 | elif 'code_search_net' in filename.lower(): #use another preprocess method when training with spider dataset 246 | raw_train_datasets = datasets.load_dataset('code_search_net', 'python', split='train') 247 | 248 | train_dataset = raw_train_datasets.map( 249 | train_tokenize_function_code_search_net, 250 | batched=True, 251 | batch_size=3000, 252 | num_proc=32, 253 | remove_columns=raw_train_datasets.column_names, 254 | load_from_cache_file=True, # not args.overwrite_cache 255 | desc="Running Encoding", 256 | fn_kwargs={"tokenizer": tokenizer} 257 | ) 258 | elif 'gsm8k' in filename.lower(): 259 | data = [] 260 | with open(filename, 'r') as file: 261 | for line in file: 262 | data.append(json.loads(line)) 263 | 264 | prompt_mapping = "Question:\n{input}\nAnswer:\nLet's think step by step.\n" 265 | processed_prompts = [prompt_mapping.format(input=query['question']) for query in data] 266 | answers = [query['answer'] for query in data] 267 | 268 | train_dataset = preprocess_gsm8k(processed_prompts, answers, tokenizer) 269 | else: 270 | raise NotImplementedError('Jacobi trajectory collection for dataset: {filename.lower()} is not currently supported.') 271 | 272 | prompt_size = min(len(train_dataset), int(data_size)) 273 | 274 | counter = 0 275 | new_data = [] 276 | 277 | for i in tqdm(range(prompt_size)): 278 | d = train_dataset[i] 279 | inputs = torch.Tensor(d['sources_input_ids']).unsqueeze(0).to(device=model.device, dtype=torch.int) 280 | 281 | itr = 0 282 | eos_reached=False 283 | while itr * max_new_tokens < max_new_seq_len and eos_reached==False: 284 | dic = {} 285 | dic['data_id']=f'data_{i}' 286 | dic['jacobian_itr_id']=f'itr_{itr}' 287 | dic['prompt_ids_len'] = d['sources_len'] 288 | 289 | attention_mask = torch.full_like(inputs, 1, dtype=torch.int).to(model.device) 290 | dic['prompt_ids'] = inputs.tolist() 291 | 292 | print('retrieving one Jacobian trajectory...') 293 | jacobian_trajectory_ids, teacher_logits, eos_reached = get_jacobian_trajectory(model, tokenizer, inputs, attention_mask, max_new_tokens) 294 | dic["answer_trajectory_ids"] = [] 295 | for _, id in enumerate(jacobian_trajectory_ids): 296 | # only support batch size=1 now 297 | dic["answer_trajectory_ids"].append(id[0][-max_new_tokens:].tolist()) 298 | 299 | if use_aug: 300 | for j in range(len(dic["answer_trajectory_ids"])-3, -1, -1): 301 | incorrect_positions = torch.where(torch.tensor(dic["answer_trajectory_ids"][j])!=torch.tensor(dic["answer_trajectory_ids"][-1]))[0] 302 | for correct_id in random.choices(incorrect_positions[1:], k=incorrect_positions.shape[0]//2): 303 | dic["answer_trajectory_ids"][j][correct_id] = dic["answer_trajectory_ids"][-1][correct_id] 304 | 305 | if use_labels: 306 | dic['labels_ids'] = d['labels_ids'].tolist() 307 | 308 | inputs = jacobian_trajectory_ids[-1] 309 | 310 | dic['teacher_output_ids'] = jacobian_trajectory_ids[-1].tolist() 311 | new_data.append(dic) 312 | itr+=1 313 | 314 | print(f'writing counter = {counter}...') 315 | counter += 1 316 | 317 | print('Jacobi trajectory has been collected. Now delete low-quality generation as post processing.') 318 | save_path = 'data/collected_jacobi_trajectory/' 319 | cleaned_data = jacobian_generated_data_postprocessed(new_data, model_path) 320 | new_file_name = "cleaned_" + f"{filename.lower().split('/')[-1]}_jacobi_max_new_tokens{max_new_tokens}_aug{use_aug}_labels_{use_labels}_max_seq_len_{max_new_seq_len}.json" 321 | new_file_path = os.path.join(save_path, new_file_name) 322 | 323 | # create directory for a path if it doesn't exist 324 | if not os.path.exists(save_path): 325 | os.makedirs(save_path) 326 | with open(new_file_path, 'w') as f_merged: 327 | json.dump(cleaned_data, f_merged) 328 | 329 | 330 | if __name__ == "__main__": 331 | parser = argparse.ArgumentParser() 332 | parser.add_argument("--filename", type=str, 333 | default="data/raw_data/ShareGPT_V3_unfiltered_cleaned_split_no_imsorry.json") 334 | parser.add_argument("--max_new_tokens", type=int, default=16) 335 | parser.add_argument("--max_new_seq_len", type=int, default=512) 336 | parser.add_argument("--model", type=str, 337 | default="models/vicuna-7b-v1.5") 338 | parser.add_argument("--data_size", default=5000) 339 | parser.add_argument("--use_aug", action='store_true') 340 | parser.add_argument("--use_labels", action='store_true') 341 | args = parser.parse_args() 342 | filename = args.filename 343 | model_path = args.model 344 | max_new_tokens = args.max_new_tokens 345 | max_new_seq_len = args.max_new_seq_len 346 | model = LlamaForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, device_map='cuda', 347 | torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2") 348 | if 'gsm8k' in model_path.lower(): 349 | tokenizer = AutoTokenizer.from_pretrained(model_path, padding_side="right", use_fast=False) 350 | else: 351 | tokenizer = AutoTokenizer.from_pretrained(model_path, padding_side="right", use_fast=True) 352 | 353 | main(filename, model, tokenizer, max_new_tokens, max_new_seq_len, args.use_aug, args.use_labels, args.data_size) 354 | -------------------------------------------------------------------------------- /eval/gsm8k/speedup.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass, field 2 | import json 3 | import math 4 | import pathlib 5 | import functools 6 | from typing import Dict, Optional, Sequence, List, Tuple 7 | import random 8 | from tqdm import tqdm 9 | import torch.nn.functional as F 10 | import sqlite3 11 | import time 12 | import numpy as np 13 | import torch 14 | from torch.utils.data import Dataset 15 | import transformers 16 | from transformers.trainer_pt_utils import LabelSmoother, get_module_class_from_name 17 | from fastchat.model.model_adapter import get_conversation_template 18 | from transformers.cache_utils import Cache, DynamicCache 19 | from transformers.modeling_attn_mask_utils import ( 20 | _prepare_4d_causal_attention_mask, 21 | _prepare_4d_causal_attention_mask_for_sdpa, 22 | ) 23 | from transformers import LlamaModel, LlamaForCausalLM, GenerationConfig 24 | import argparse 25 | 26 | import os 27 | 28 | import sys 29 | from pathlib import Path 30 | 31 | path_root = Path(__file__).parents[2] 32 | sys.path.append(str(path_root)) 33 | 34 | from cllm.utils import detect_repetitive_patterns 35 | from cllm.cllm_llama_modeling import delete_false_key_value, jacobi_forward_profiling 36 | 37 | DynamicCache.delete_false_key_value = delete_false_key_value 38 | LlamaForCausalLM.jacobi_forward = jacobi_forward_profiling 39 | 40 | def jacobi_generate(inputs, model, tokenizer, max_new_tokens, max_new_seq_len): 41 | converge_step = [] 42 | forward_times = 0 43 | 44 | all_jacobian_trajectory = [] 45 | prompt_len = torch.sum(inputs['attention_mask'], dim=-1) 46 | generation = inputs['input_ids'] 47 | ### prefill the kv-cache 48 | past_key_values, first_correct_token = model.jacobi_forward(input_ids=inputs['input_ids'], max_new_tokens=max_new_tokens, past_key_values=None, use_cache = True, prefill_phase = True) 49 | ### generation phase 50 | itr = 0 51 | eos_reached = False 52 | while True: 53 | itr+=1 54 | bsz = 1 # only support batch_size = 1 now 55 | # randomly initialize the first point of jacobian trajectory 56 | random_point = torch.tensor(random.choices(generation[0], k=(max_new_tokens-1)), device="cuda").view(1,-1) 57 | input_ids = torch.cat((first_correct_token.view(1,-1), random_point),dim=-1) 58 | jacobian_trajectory, n_gram_generation, first_correct_token, iter_steps = model.jacobi_forward(input_ids=input_ids, max_new_tokens=max_new_tokens, past_key_values=past_key_values, use_cache = True, prefill_phase = False) 59 | forward_times += iter_steps 60 | all_jacobian_trajectory.append(jacobian_trajectory) 61 | eos_positions = torch.where(n_gram_generation[0]==tokenizer.eos_token_id)[0] 62 | 63 | if len(eos_positions)>0: 64 | eos_reached = True 65 | 66 | ### see if next max_new_tokens should be generated & if True, update weights and prepare new input_id 67 | generation = torch.cat((generation, n_gram_generation), dim=-1) 68 | if eos_reached or itr*max_new_tokens > max_new_seq_len: 69 | break 70 | 71 | # to support bsz > 1 72 | converge_step.append(forward_times / itr) 73 | 74 | return generation[0, prompt_len:], converge_step, all_jacobian_trajectory 75 | 76 | def jacobian_speed_evaluate(processed_prompt, model, tokenizer, max_new_tokens, max_new_seq_len): 77 | 78 | time_speed = [] 79 | eos_reached = False 80 | inputs = tokenizer([processed_prompt], return_tensors="pt").to(model.device) 81 | t1 = torch.cuda.Event(enable_timing=True) 82 | t2 = torch.cuda.Event(enable_timing=True) 83 | t1.record() 84 | jacobi_generation, converge_step, all_jacobian_trajectory = jacobi_generate(inputs, model, tokenizer, max_new_tokens, max_new_seq_len) 85 | t2.record() 86 | torch.cuda.synchronize() 87 | 88 | t = t1.elapsed_time(t2) / 1000 89 | prompt_token_len = torch.sum(inputs['attention_mask'], dim=-1) 90 | eos_positions = torch.where(jacobi_generation==tokenizer.eos_token_id)[0] 91 | if len(eos_positions)>0: 92 | eos_reached = True 93 | total_generation_len = jacobi_generation[:int(eos_positions[0])].shape[0] 94 | decoded_generation = tokenizer.decode(jacobi_generation[:int(eos_positions[0])]) 95 | else: 96 | total_generation_len = jacobi_generation.shape[0] 97 | decoded_generation = tokenizer.decode(jacobi_generation) 98 | time_speed.append(total_generation_len/t) 99 | 100 | return eos_reached, time_speed, converge_step, jacobi_generation, decoded_generation, all_jacobian_trajectory 101 | 102 | def speed_compare(args): 103 | # Load model and tokenizer 104 | model = transformers.LlamaForCausalLM.from_pretrained(args.test_model_path, low_cpu_mem_usage=True, device_map='auto', 105 | torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2") 106 | tokenizer = transformers.AutoTokenizer.from_pretrained( 107 | args.teacher_model_path, 108 | padding_side="right", 109 | use_fast=False, 110 | ) 111 | ##### compare speed of jacobian and ar ##### 112 | converge_step = [] 113 | ar_time_speed = [] 114 | jacobian_time_speed = [] 115 | filename = args.filename 116 | data = [] 117 | with open(filename, 'r') as file: 118 | for line in file: 119 | data.append(json.loads(line)) 120 | 121 | per_request_meta_trajectory_records = [] 122 | data_lst = range(args.data_size) 123 | # only support batch size ==1 now 124 | for i in tqdm(data_lst): 125 | d = data[i] 126 | prompt_mapping = "Question:\n{input}\nAnswer:\nLet's think step by step.\n" 127 | processed_prompt = prompt_mapping.format(input=d['question']) 128 | max_new_tokens = args.max_new_tokens 129 | inputs = tokenizer([processed_prompt], return_tensors="pt").to(model.device) 130 | ar_begin = time.time() 131 | ar_generated = model.generate(**inputs, use_cache=True, max_new_tokens=1024, do_sample=False)[0][inputs['input_ids'].shape[-1]:-1] 132 | ar_end = time.time() 133 | print(f'ar generated length: {len(ar_generated)}') 134 | eos_reached, jacobian_time_speed_lst, jacobian_itr_step_lst, decoded_ids, decoded_result, all_jacobian_trajectory = jacobian_speed_evaluate(processed_prompt, model, tokenizer, max_new_tokens, args.max_new_seq_len) 135 | 136 | if not detect_repetitive_patterns(tokenizer, decoded_ids, repeat_ngram_size=10): 137 | per_request_meta_trajectory_records.append(all_jacobian_trajectory) 138 | 139 | jacobian_time_speed.append(*jacobian_time_speed_lst) 140 | converge_step.append(*jacobian_itr_step_lst) 141 | 142 | inputs = tokenizer([processed_prompt], return_tensors="pt").to(model.device) 143 | 144 | gen_cfg = GenerationConfig.from_model_config(model.config) 145 | 146 | ar_begin = torch.cuda.Event(enable_timing=True) 147 | ar_end = torch.cuda.Event(enable_timing=True) 148 | ar_begin.record() 149 | ar_generated = model.generate(**inputs, use_cache=True, max_new_tokens=512)[0][inputs.input_ids.shape[-1]:-1] 150 | ar_end.record() 151 | torch.cuda.synchronize() 152 | 153 | #print(ar_generated) 154 | print(f'ar generated length: {len(ar_generated)}') 155 | ar_time = ar_begin.elapsed_time(ar_end) / 1000 156 | print(f'ar time: {len(ar_generated)/(ar_time)}') 157 | ar_time_speed.append(len(ar_generated)/ar_time) 158 | 159 | # all trajectory analsis for speedup interpretability 160 | fast_forward_and_fix_points_statistics = {} 161 | # initialize dict for all stats 162 | fast_forward_and_fix_points_statistics['fix_points'] = [] 163 | fast_forward_and_fix_points_statistics['fast_forward'] = [] 164 | fast_forward_and_fix_points_statistics['fix_points_per_gram'] = [] 165 | 166 | # iterate over all requests 167 | for all_generation_trajectory in per_request_meta_trajectory_records: 168 | fast_forward_metrics = [] 169 | 170 | fix_points_metrics = 0 171 | 172 | effective_trajectory_length = args.max_new_tokens 173 | # iterate over all n-grams, across the sequence length dimension 174 | # last trajectory contains eos, we need to keep track 175 | last_traj_flag = False 176 | for n_gram_id in range(len(all_generation_trajectory)): 177 | # initialize fix_points_tracker 178 | fix_points_tracker = {} 179 | for pos_ind in range(args.max_new_tokens): 180 | # to track how many times right token is predicted right 181 | fix_points_tracker[pos_ind] = 0 182 | 183 | # initialize single_fast_forward_metrics 184 | single_fast_forward_metrics = [] 185 | 186 | generation_trajectory = all_generation_trajectory[n_gram_id] 187 | 188 | if n_gram_id == len(all_generation_trajectory) - 1: 189 | last_traj_flag = True 190 | 191 | correct_token_cnt = 0 192 | fix_points_per_gram = 0 193 | # look at a single n-gram trajectory 194 | # iterate over all points in the trajectory (with the same dimension) 195 | eos_reached = False 196 | eos_pos = None 197 | steps_to_convergence = 0 198 | for id, generation_ids in enumerate(generation_trajectory): 199 | # skip initialiation 200 | if id == 0: 201 | continue 202 | if eos_reached == True: 203 | break 204 | assert len(generation_ids[0]) == args.max_new_tokens 205 | 206 | # iterate over all tokens 207 | fast_forward_cnt = 0 208 | 209 | contiguous_correct_flag = True 210 | 211 | for i in range(len(generation_ids[0])): 212 | token_generated = generation_ids[0][i] 213 | if generation_ids[0][i] == generation_trajectory[-1][0][i]: 214 | #print(BLUE + tokenizer.decode([token_generated]) + RESET, end=" ") # print blue token 215 | # update fix point tracker 216 | fix_points_tracker[i] += 1 217 | 218 | # update fast-forward tracker 219 | # first (i + 1) is to offset index 220 | if (i + 1) > correct_token_cnt and contiguous_correct_flag: 221 | fast_forward_cnt += 1 222 | 223 | # check whether eos has been reached as a contiguous sentence 224 | if last_traj_flag and token_generated == tokenizer.eos_token_id and contiguous_correct_flag: 225 | effective_trajectory_length = i + 1 226 | 227 | eos_reached = True 228 | eos_pos = i 229 | 230 | # before break out of the loop, uppdate values 231 | correct_token_cnt += fast_forward_cnt 232 | 233 | break 234 | else: 235 | #print(RED + tokenizer.decode([token_generated]) + RESET, end=" ") # print red token 236 | if fix_points_tracker[i] > 0: 237 | fix_points_tracker[i] = 0 238 | 239 | if contiguous_correct_flag: 240 | correct_token_cnt += fast_forward_cnt 241 | contiguous_correct_flag = False 242 | 243 | single_fast_forward_metrics.append(fast_forward_cnt) 244 | 245 | steps_to_convergence += 1 246 | 247 | ff_baseline_cnt = {} 248 | for pos_ind in range(effective_trajectory_length): 249 | # to track how many times right token should be predicted right, if there is only fast_forward 250 | ff_baseline_cnt[pos_ind] = 0 251 | 252 | fast_forward_ptr = 0 253 | next_ff_flag = True 254 | for pos_ind in range(effective_trajectory_length): 255 | if next_ff_flag: 256 | fast_forward_offset = single_fast_forward_metrics[fast_forward_ptr] 257 | next_ff_flag = False 258 | 259 | ff_baseline_cnt[pos_ind] = steps_to_convergence - fast_forward_ptr 260 | 261 | fast_forward_offset -= 1 262 | if fast_forward_offset == 0: 263 | next_ff_flag = True 264 | fast_forward_ptr += 1 265 | 266 | for pos_ind in fix_points_tracker.keys(): 267 | cnt = fix_points_tracker[pos_ind] 268 | ff_baseline = ff_baseline_cnt[pos_ind] 269 | if cnt > ff_baseline: 270 | fix_points_metrics += 1 271 | fix_points_per_gram += 1 272 | 273 | if last_traj_flag and pos_ind == eos_pos: 274 | break 275 | 276 | # record avg fast forward count over a single n-gram 277 | fast_forward_metrics.append(np.average(single_fast_forward_metrics)) 278 | fast_forward_and_fix_points_statistics['fix_points_per_gram'].append(fix_points_per_gram) 279 | 280 | 281 | all_fast_forward = fast_forward_and_fix_points_statistics['fast_forward'] 282 | all_fix_points = fast_forward_and_fix_points_statistics['fix_points'] 283 | 284 | avg_fast_forward = np.average(fast_forward_metrics) 285 | all_fast_forward.append(avg_fast_forward) 286 | all_fix_points.append(fix_points_metrics) 287 | 288 | 289 | print(f"global average fast forward cnt: {np.average(fast_forward_and_fix_points_statistics['fast_forward'])}") 290 | print(f"global average fix-point cnt: {np.average(fast_forward_and_fix_points_statistics['fix_points'])}") 291 | print(f"global average fix-point per gram cnt: {np.average(fast_forward_and_fix_points_statistics['fix_points_per_gram'])}") 292 | 293 | save_path = 'data/speedup_profiling_results/' 294 | if not os.path.exists(save_path): 295 | os.makedirs(save_path) 296 | 297 | new_file_path= f'gsm8k_speedup_profiling_results_{args.max_new_tokens}_{args.max_new_seq_len}_{args.data_size}_stats.json' 298 | fast_forward_and_fix_points_statistics_file = os.path.join(save_path, new_file_path) 299 | 300 | with open(fast_forward_and_fix_points_statistics_file, 'w') as f: 301 | json.dump(fast_forward_and_fix_points_statistics, f, indent=4) 302 | 303 | ar_time_speed = ar_time_speed[1:] 304 | jacobian_time_speed = jacobian_time_speed[1:] 305 | print(f'ar speed: {ar_time_speed}') 306 | print(f'jacobian speed: {jacobian_time_speed}') 307 | print(f'The max speed of model {args.test_model_path} using jacobian iteration (max_new_tokens: {max_new_tokens}) is {max(jacobian_time_speed)}') 308 | print(f'The min speed of model {args.test_model_path} using jacobian iteration (max_new_tokens: {max_new_tokens}) is {min(jacobian_time_speed)}') 309 | print(f'The avg speed of model {args.test_model_path} using jacobian iteration (max_new_tokens: {max_new_tokens}) is {sum(jacobian_time_speed)/len(jacobian_time_speed)}') 310 | print(f'The max speed of model {args.test_model_path} using ar is {max(ar_time_speed)}') 311 | print(f'The min speed of model {args.test_model_path} using ar is {min(ar_time_speed)}') 312 | print(f'The avg speed of model {args.test_model_path} using ar is {sum(ar_time_speed)/len(ar_time_speed)}') 313 | 314 | if __name__ == "__main__": 315 | parser = argparse.ArgumentParser() 316 | parser.add_argument("--filename", type=str, 317 | default="eval/gsm8k/test.jsonl") 318 | parser.add_argument("--max_new_tokens", type=int, default=16) 319 | parser.add_argument("--max_new_seq_len", type=int, default=1024) 320 | parser.add_argument("--test_model_path", type=str, 321 | default="models/vicuna-7b-sharegpt-gpt4-48k") 322 | parser.add_argument("--teacher_model_path", type=str, 323 | default="cllm/consistency-llm-7b-sharegpt48k") 324 | parser.add_argument("--data_size", type=str, 325 | default=500) 326 | args = parser.parse_args() 327 | speed_compare(args) -------------------------------------------------------------------------------- /eval/mt-bench/gen_model_answer_jacobi.py: -------------------------------------------------------------------------------- 1 | """Generate answers with local models. 2 | 3 | Usage: 4 | python3 gen_model_answer.py --model-path lmsys/fastchat-t5-3b-v1.0 --model-id fastchat-t5-3b-v1.0 5 | """ 6 | import argparse 7 | import json 8 | import os 9 | import random 10 | import time 11 | 12 | import shortuuid 13 | import torch 14 | from tqdm import tqdm 15 | 16 | from fastchat.llm_judge.common import load_questions, temperature_config 17 | from fastchat.model import load_model, get_conversation_template 18 | from fastchat.utils import str_to_torch_dtype 19 | 20 | def consistency_generate( 21 | model, 22 | tokenizer, 23 | inputs, 24 | max_new_tokens_for_consistency, 25 | max_new_seq_len 26 | ): 27 | max_new_tokens = max_new_tokens_for_consistency 28 | 29 | itr = 0 30 | while True: 31 | if itr == 0: 32 | input_ids = inputs['input_ids'] 33 | input_masks = inputs['attention_mask'] 34 | else: 35 | input_masks = torch.ones_like(input_ids).to(input_ids.device) 36 | for j in range(bsz): 37 | input_masks[j][torch.sum(inputs["attention_mask"], dim=-1)[j] + itr*max_new_tokens:] = 0 38 | 39 | bsz = input_ids.shape[0] 40 | eos_reached = torch.tensor([False] * bsz, device="cuda") 41 | generation = get_jacobian_trajectory(model, tokenizer, input_ids, input_masks, max_new_tokens) 42 | ### tokens generated after are set to 43 | for j in range(bsz): 44 | prompt_len = torch.sum(input_masks, dim=-1) 45 | eos_positions = torch.where(generation[j]==tokenizer.eos_token_id)[0] 46 | if len(eos_positions)==0: 47 | # no EOS, continue to the next item in the batch 48 | generation[j][prompt_len[j]+ max_new_tokens:] = tokenizer.pad_token_id 49 | continue 50 | # otherwise, set tokens coming after EOS as pad 51 | eos_reached[j] = True 52 | generation[j, int(eos_positions[0])+1:] = tokenizer.pad_token_id 53 | 54 | ### see if next max_new_tokens should be generated & if True, update weights and prepare new input_ids 55 | itr+=1 56 | if all(eos_reached) or itr*max_new_tokens >= max_new_seq_len: 57 | total_token_len = torch.sum(generation != tokenizer.pad_token_id, dim=-1) 58 | return generation[:total_token_len] 59 | input_ids = generation 60 | 61 | @torch.inference_mode() 62 | def get_jacobian_trajectory( 63 | model, 64 | tokenizer, 65 | input_ids, 66 | attention_mask, 67 | max_new_tokens 68 | ): 69 | 70 | bsz = input_ids.shape[0] 71 | prompt_len = [torch.sum(t) for t in attention_mask] 72 | max_prompt_len = max(prompt_len) 73 | total_len = max_prompt_len + max_new_tokens 74 | 75 | # initialize the first point of jacobian trajectory 76 | tokens = torch.full((bsz, total_len), tokenizer.pad_token_id, dtype=torch.long, device="cuda") 77 | for i in range(bsz): 78 | tokens[i, :] = torch.tensor(random.choices(input_ids[i][attention_mask[i]==1], k=total_len), dtype=torch.long, device="cuda") 79 | tokens[i, : prompt_len[i]] = torch.tensor(input_ids[i][: prompt_len[i]], dtype=torch.long, device="cuda") 80 | itr = 0 81 | next_generation = tokens 82 | generate_attention_mask = torch.full_like(next_generation, 1).to(tokens.device) 83 | while True: 84 | 85 | current_generation = next_generation 86 | with torch.no_grad(): 87 | logits = model(current_generation, generate_attention_mask).logits 88 | next_generation = torch.argmax(torch.nn.functional.softmax(logits, dim=-1), dim=-1) 89 | 90 | # hold prompt unchanged and update generated tokens 91 | for i in range(bsz): 92 | next_generation[i, :] = torch.cat((tokens[i, :prompt_len[i]], next_generation[i, prompt_len[i]-1:total_len-1]), dim=0) 93 | if torch.all(torch.eq(next_generation, current_generation)).item(): 94 | print(f"Iteration steps: {itr}") 95 | return next_generation # right generation is saved twice so we delete the last element of trajectory list 96 | itr+=1 97 | 98 | def run_eval( 99 | model_path, 100 | model_id, 101 | question_file, 102 | question_begin, 103 | question_end, 104 | answer_file, 105 | max_new_token, 106 | num_choices, 107 | num_gpus_per_model, 108 | num_gpus_total, 109 | max_gpu_memory, 110 | dtype, 111 | use_consistency_decoding, 112 | max_new_tokens_for_consistency, 113 | revision, 114 | ): 115 | questions = load_questions(question_file, question_begin, question_end) 116 | # random shuffle the questions to balance the loading 117 | random.shuffle(questions) 118 | 119 | # Split the question file into `num_gpus` files 120 | assert num_gpus_total % num_gpus_per_model == 0 121 | use_ray = num_gpus_total // num_gpus_per_model > 1 122 | 123 | if use_ray: 124 | get_answers_func = ray.remote(num_gpus=num_gpus_per_model)( 125 | get_model_answers 126 | ).remote 127 | else: 128 | get_answers_func = get_model_answers 129 | 130 | chunk_size = len(questions) // (num_gpus_total // num_gpus_per_model) 131 | ans_handles = [] 132 | for i in range(0, len(questions), chunk_size): 133 | ans_handles.append( 134 | get_answers_func( 135 | model_path, 136 | model_id, 137 | questions[i : i + chunk_size], 138 | answer_file, 139 | max_new_token, 140 | num_choices, 141 | num_gpus_per_model, 142 | max_gpu_memory, 143 | dtype=dtype, 144 | use_consistency_decoding=use_consistency_decoding, 145 | max_new_tokens_for_consistency=max_new_tokens_for_consistency, 146 | revision=revision, 147 | ) 148 | ) 149 | 150 | if use_ray: 151 | ray.get(ans_handles) 152 | 153 | 154 | @torch.inference_mode() 155 | def get_model_answers( 156 | model_path, 157 | model_id, 158 | questions, 159 | answer_file, 160 | max_new_token, 161 | num_choices, 162 | num_gpus_per_model, 163 | max_gpu_memory, 164 | dtype, 165 | revision, 166 | use_consistency_decoding, 167 | max_new_tokens_for_consistency, 168 | ): 169 | model, tokenizer = load_model( 170 | model_path, 171 | revision=revision, 172 | device="cuda", 173 | num_gpus=num_gpus_per_model, 174 | max_gpu_memory=max_gpu_memory, 175 | dtype=dtype, 176 | load_8bit=False, 177 | cpu_offloading=False, 178 | debug=False, 179 | ) 180 | 181 | for question in tqdm(questions): 182 | if question["category"] in temperature_config: 183 | temperature = temperature_config[question["category"]] 184 | else: 185 | temperature = 0.7 186 | 187 | choices = [] 188 | for i in range(num_choices): 189 | torch.manual_seed(i) 190 | conv = get_conversation_template('vicuna') 191 | turns = [] 192 | for j in range(len(question["turns"])): 193 | qs = question["turns"][j] 194 | conv.append_message(conv.roles[0], qs) 195 | conv.append_message(conv.roles[1], None) 196 | prompt = conv.get_prompt() 197 | input_ids = tokenizer([prompt]).input_ids 198 | 199 | if temperature < 1e-4: 200 | do_sample = False 201 | else: 202 | do_sample = True 203 | 204 | # some models may error out when generating long outputs 205 | try: 206 | if use_consistency_decoding: 207 | output_ids = consistency_generate( 208 | model, 209 | tokenizer, 210 | tokenizer([prompt], return_tensors="pt").to(model.device), 211 | max_new_tokens_for_consistency=max_new_tokens_for_consistency, 212 | max_new_seq_len=max_new_token, 213 | ) 214 | else: 215 | output_ids = model.generate( 216 | torch.as_tensor(input_ids).cuda(), 217 | do_sample=do_sample, 218 | temperature=temperature, 219 | max_new_tokens=max_new_token, 220 | ) 221 | if model.config.is_encoder_decoder: 222 | output_ids = output_ids[0] 223 | else: 224 | output_ids = output_ids[0][len(input_ids[0]) :] 225 | 226 | # be consistent with the template's stop_token_ids 227 | if conv.stop_token_ids: 228 | stop_token_ids_index = [ 229 | i 230 | for i, id in enumerate(output_ids) 231 | if id in conv.stop_token_ids 232 | ] 233 | if len(stop_token_ids_index) > 0: 234 | output_ids = output_ids[: stop_token_ids_index[0]] 235 | 236 | output = tokenizer.decode( 237 | output_ids, 238 | spaces_between_special_tokens=False, 239 | ) 240 | if conv.stop_str and isinstance(conv.stop_str, list): 241 | stop_str_indices = sorted( 242 | [ 243 | output.find(stop_str) 244 | for stop_str in conv.stop_str 245 | if output.find(stop_str) > 0 246 | ] 247 | ) 248 | if len(stop_str_indices) > 0: 249 | output = output[: stop_str_indices[0]] 250 | elif conv.stop_str and output.find(conv.stop_str) > 0: 251 | output = output[: output.find(conv.stop_str)] 252 | 253 | for special_token in tokenizer.special_tokens_map.values(): 254 | if isinstance(special_token, list): 255 | for special_tok in special_token: 256 | output = output.replace(special_tok, "") 257 | else: 258 | output = output.replace(special_token, "") 259 | output = output.strip() 260 | 261 | if conv.name == "xgen" and output.startswith("Assistant:"): 262 | output = output.replace("Assistant:", "", 1).strip() 263 | 264 | print('--------------- output ----------------') 265 | print(output) 266 | print('--------------- output ends ----------------') 267 | 268 | except RuntimeError as e: 269 | print("ERROR question ID: ", question["question_id"]) 270 | output = "ERROR" 271 | 272 | conv.update_last_message(output) 273 | turns.append(output) 274 | 275 | choices.append({"index": i, "turns": turns}) 276 | 277 | # Dump answers 278 | os.makedirs(os.path.dirname(answer_file), exist_ok=True) 279 | with open(os.path.expanduser(answer_file), "a") as fout: 280 | ans_json = { 281 | "question_id": question["question_id"], 282 | "answer_id": shortuuid.uuid(), 283 | "model_id": model_id, 284 | "choices": choices, 285 | "tstamp": time.time(), 286 | } 287 | fout.write(json.dumps(ans_json) + "\n") 288 | 289 | 290 | def reorg_answer_file(answer_file): 291 | """Sort by question id and de-duplication""" 292 | answers = {} 293 | with open(answer_file, "r") as fin: 294 | for l in fin: 295 | qid = json.loads(l)["question_id"] 296 | answers[qid] = l 297 | 298 | qids = sorted(list(answers.keys())) 299 | with open(answer_file, "w") as fout: 300 | for qid in qids: 301 | fout.write(answers[qid]) 302 | 303 | 304 | if __name__ == "__main__": 305 | parser = argparse.ArgumentParser() 306 | parser.add_argument( 307 | "--model-path", 308 | type=str, 309 | required=True, 310 | help="The path to the weights. This can be a local folder or a Hugging Face repo ID. Default: cllm/consistency-llm-7b-sharegpt48k", 311 | ) 312 | parser.add_argument( 313 | "--model-id", type=str, required=True, help="A custom name for the model." 314 | ) 315 | parser.add_argument( 316 | "--bench-name", 317 | type=str, 318 | default="mt_bench", 319 | help="The name of the benchmark question set.", 320 | ) 321 | parser.add_argument( 322 | "--question-begin", 323 | type=int, 324 | help="A debug option. The begin index of questions.", 325 | ) 326 | parser.add_argument( 327 | "--question-end", type=int, help="A debug option. The end index of questions." 328 | ) 329 | parser.add_argument("--answer-file", type=str, help="The output answer file.") 330 | parser.add_argument( 331 | "--max-new-token", 332 | type=int, 333 | default=1024, 334 | help="The maximum number of new generated tokens.", 335 | ) 336 | parser.add_argument( 337 | "--num-choices", 338 | type=int, 339 | default=1, 340 | help="How many completion choices to generate.", 341 | ) 342 | parser.add_argument( 343 | "--num-gpus-per-model", 344 | type=int, 345 | default=1, 346 | help="The number of GPUs per model.", 347 | ) 348 | parser.add_argument( 349 | "--num-gpus-total", type=int, default=1, help="The total number of GPUs." 350 | ) 351 | parser.add_argument( 352 | "--max-gpu-memory", 353 | type=str, 354 | help="Maxmum GPU memory used for model weights per GPU.", 355 | ) 356 | parser.add_argument( 357 | "--dtype", 358 | type=str, 359 | choices=["float32", "float16", "bfloat16"], 360 | help="Override the default dtype. If not set, it will use float16 on GPU and float32 on CPU.", 361 | default=None, 362 | ) 363 | parser.add_argument( 364 | "--revision", 365 | type=str, 366 | default="main", 367 | help="The model revision to load.", 368 | ) 369 | parser.add_argument( 370 | "--use_consistency_decoding", 371 | type=bool, 372 | default=True, 373 | help="Whether to use consistency decoding", 374 | ) 375 | parser.add_argument( 376 | "--max_new_tokens_for_consistency", 377 | type=int, 378 | default=32, 379 | help="The n-gram for consistency decoding.", 380 | ) 381 | 382 | args = parser.parse_args() 383 | 384 | if args.num_gpus_total // args.num_gpus_per_model > 1: 385 | import ray 386 | 387 | ray.init() 388 | 389 | question_file = f"data/{args.bench_name}/question.jsonl" 390 | if args.answer_file: 391 | answer_file = args.answer_file 392 | else: 393 | answer_file = f"data/{args.bench_name}/model_answer/{args.model_id}.jsonl" 394 | 395 | print(f"Output to {answer_file}") 396 | 397 | run_eval( 398 | model_path=args.model_path, 399 | model_id=args.model_id, 400 | question_file=question_file, 401 | question_begin=args.question_begin, 402 | question_end=args.question_end, 403 | answer_file=answer_file, 404 | max_new_token=args.max_new_token, 405 | num_choices=args.num_choices, 406 | num_gpus_per_model=args.num_gpus_per_model, 407 | num_gpus_total=args.num_gpus_total, 408 | max_gpu_memory=args.max_gpu_memory, 409 | dtype=str_to_torch_dtype(args.dtype), 410 | revision=args.revision, 411 | use_consistency_decoding=args.use_consistency_decoding, 412 | max_new_tokens_for_consistency = args.max_new_tokens_for_consistency, 413 | ) 414 | 415 | reorg_answer_file(answer_file) 416 | 417 | -------------------------------------------------------------------------------- /cllm/cllm_llama_modeling.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass, field 2 | import json 3 | import math 4 | import pathlib 5 | import functools 6 | from typing import Dict, Optional, Sequence, List, Tuple 7 | import random 8 | from tqdm import tqdm 9 | import torch.nn.functional as F 10 | import sqlite3 11 | import time 12 | import numpy as np 13 | import torch 14 | from torch.utils.data import Dataset 15 | import transformers 16 | from transformers.trainer_pt_utils import LabelSmoother, get_module_class_from_name 17 | from fastchat.model.model_adapter import get_conversation_template 18 | from transformers.cache_utils import Cache, DynamicCache 19 | from transformers.modeling_attn_mask_utils import ( 20 | _prepare_4d_causal_attention_mask, 21 | _prepare_4d_causal_attention_mask_for_sdpa, 22 | ) 23 | 24 | import torch.nn.functional as F 25 | from transformers import LlamaModel,LlamaForCausalLM 26 | import argparse 27 | 28 | def delete_false_key_value( 29 | self, 30 | num_of_false_tokens, 31 | ) -> Tuple[torch.Tensor, torch.Tensor]: 32 | 33 | for layer_idx in range(len(self.key_cache)): 34 | self.key_cache[layer_idx] = self.key_cache[layer_idx][..., :-num_of_false_tokens, :] 35 | self.value_cache[layer_idx] = self.value_cache[layer_idx][..., :-num_of_false_tokens, :] 36 | 37 | @torch.inference_mode() 38 | def jacobi_forward( 39 | self, 40 | input_ids: torch.LongTensor = None, 41 | tokenizer=None, 42 | attention_mask: Optional[torch.Tensor] = None, 43 | position_ids: Optional[torch.LongTensor] = None, 44 | past_key_values: Optional[List[torch.FloatTensor]] = None, 45 | use_cache: Optional[bool] = None, 46 | max_new_tokens: Optional[int] = None, 47 | prefill_phase: Optional[bool] = False, 48 | chat: Optional[bool] = False, 49 | ): 50 | assert use_cache == True 51 | 52 | if input_ids is not None: 53 | batch_size, seq_length = input_ids.shape[:2] 54 | else: 55 | raise ValueError("You have to specify either input_ids or inputs_embeds") 56 | 57 | if prefill_phase: # prefill phase, just compute the keys & values of prompt 58 | # self.model is the instance of class LlamaModel 59 | inputs_embeds = self.model.embed_tokens(input_ids) 60 | past_key_values_length = 0 61 | if use_cache: 62 | use_legacy_cache = not isinstance(past_key_values, Cache) 63 | if use_legacy_cache: 64 | past_key_values = DynamicCache.from_legacy_cache(past_key_values) 65 | past_key_values_length = past_key_values.get_usable_length(seq_length) 66 | 67 | if position_ids is None: 68 | device = input_ids.device if input_ids is not None else inputs_embeds.device 69 | position_ids = torch.arange( 70 | past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device 71 | ) 72 | position_ids = position_ids.unsqueeze(0) 73 | 74 | if self.model._use_flash_attention_2: 75 | # 2d mask is passed through the layers 76 | attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None 77 | elif self.model._use_sdpa : 78 | # output_attentions=True can not be supported when using SDPA, and we fall back on 79 | # the manual implementation that requires a 4D causal mask in all cases. 80 | attention_mask = _prepare_4d_causal_attention_mask_for_sdpa( 81 | attention_mask, 82 | (batch_size, seq_length), 83 | inputs_embeds, 84 | past_key_values_length, 85 | ) 86 | else: 87 | # 4d mask is passed through the layers 88 | attention_mask = _prepare_4d_causal_attention_mask( 89 | attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length 90 | ) 91 | # embed positions 92 | hidden_states = inputs_embeds 93 | 94 | # decoder layers 95 | for decoder_layer in self.model.layers: 96 | 97 | layer_outputs = decoder_layer( 98 | hidden_states, 99 | attention_mask=attention_mask, 100 | position_ids=position_ids, 101 | past_key_value=past_key_values, 102 | use_cache=use_cache, 103 | ) 104 | 105 | hidden_states = layer_outputs[0] 106 | 107 | if use_cache: 108 | next_decoder_cache = layer_outputs[1] 109 | 110 | hidden_states = self.model.norm(hidden_states) 111 | 112 | if self.config.pretraining_tp > 1: 113 | lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0) 114 | logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)] 115 | logits = torch.cat(logits, dim=-1) 116 | else: 117 | logits = self.lm_head(hidden_states) 118 | logits = logits.float() 119 | 120 | predict_next_tokens = torch.argmax(torch.nn.functional.softmax(logits, dim=-1) / 0.001, dim=-1) 121 | first_correct_token = predict_next_tokens[:, -1] 122 | return next_decoder_cache, first_correct_token 123 | else: # generation phase, input as random_initilized point and output as fixed point 124 | jacobian_trajectory = [] 125 | accurate_n_gram = torch.zeros_like(input_ids).to(input_ids.device) 126 | accurate_length = 0 127 | 128 | next_point = input_ids 129 | jacobian_trajectory.append(next_point) 130 | 131 | iter_counter = 0 132 | 133 | prev_len = 0 134 | while True: 135 | 136 | current_point = next_point 137 | inputs_embeds = self.model.embed_tokens(current_point) 138 | attention_mask = None 139 | position_ids = None 140 | seq_length = current_point.shape[1] 141 | if use_cache: 142 | use_legacy_cache = not isinstance(past_key_values, Cache) 143 | if use_legacy_cache: 144 | past_key_values = DynamicCache.from_legacy_cache(past_key_values) 145 | past_key_values_length = past_key_values.get_usable_length(seq_length) 146 | # print(past_key_values_length) # return previous_seq_length 147 | if position_ids is None: 148 | device = input_ids.device if input_ids is not None else inputs_embeds.device 149 | position_ids = torch.arange( 150 | past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device 151 | ) 152 | position_ids = position_ids.unsqueeze(0) 153 | 154 | if self.model._use_flash_attention_2: 155 | # 2d mask is passed through the layers 156 | attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None 157 | elif self.model._use_sdpa : 158 | # output_attentions=True can not be supported when using SDPA, and we fall back on 159 | # the manual implementation that requires a 4D causal mask in all cases. 160 | attention_mask = _prepare_4d_causal_attention_mask_for_sdpa( 161 | attention_mask, 162 | (batch_size, seq_length), 163 | inputs_embeds, 164 | past_key_values_length, 165 | ) 166 | else: 167 | # 4d mask is passed through the layers 168 | attention_mask = _prepare_4d_causal_attention_mask( 169 | attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length 170 | ) 171 | # embed positions 172 | hidden_states = inputs_embeds 173 | 174 | # decoder layers 175 | for decoder_layer in self.model.layers: 176 | layer_outputs = decoder_layer( 177 | hidden_states, 178 | attention_mask=attention_mask, 179 | position_ids=position_ids, 180 | past_key_value=past_key_values, 181 | use_cache=use_cache, 182 | ) 183 | 184 | hidden_states = layer_outputs[0] 185 | 186 | hidden_states = self.model.norm(hidden_states) 187 | 188 | if self.config.pretraining_tp > 1: 189 | lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0) 190 | logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)] 191 | logits = torch.cat(logits, dim=-1) 192 | else: 193 | logits = self.lm_head(hidden_states) 194 | 195 | logits = logits.float() 196 | all_shift_one_token = torch.argmax(torch.nn.functional.softmax(logits, dim=-1) / 0.001, dim=-1) 197 | 198 | next_point = torch.cat((current_point[0, 0].view(1,-1), all_shift_one_token[0, :seq_length-1].view(1,-1)), dim=-1) 199 | 200 | first_false_index = torch.where(torch.eq(current_point[0], next_point[0]) == False)[0] 201 | 202 | jacobian_trajectory.append(next_point) 203 | 204 | if len(first_false_index) > 0: 205 | fast_forward_cnt = first_false_index[0].item() 206 | 207 | past_key_values.delete_false_key_value(seq_length - fast_forward_cnt) # delete the false keys & values 208 | else: 209 | fast_forward_cnt = torch.sum(torch.eq(current_point, next_point)).item() 210 | 211 | accurate_n_gram[0, accurate_length : accurate_length + fast_forward_cnt] = next_point[0, :fast_forward_cnt] 212 | first_correct_token = all_shift_one_token[:,-1] 213 | if chat: 214 | if tokenizer.eos_token_id in accurate_n_gram[0, :accurate_length + fast_forward_cnt]: 215 | eos_positions = torch.where(accurate_n_gram[0]==tokenizer.eos_token_id)[0] 216 | eos_position = eos_positions[0] 217 | generated_str = tokenizer.decode(accurate_n_gram[0, :eos_position], skip_special_tokens=True) 218 | else: 219 | generated_str = tokenizer.decode(accurate_n_gram[0, :accurate_length + fast_forward_cnt], skip_special_tokens=True) 220 | 221 | print(generated_str[prev_len:], flush=True, end="") 222 | prev_len = len(generated_str) 223 | break 224 | 225 | accurate_n_gram[0, accurate_length : accurate_length + fast_forward_cnt] = next_point[0, :fast_forward_cnt] 226 | accurate_length += fast_forward_cnt 227 | next_point = next_point[0, fast_forward_cnt:].view(1,-1) # only false tokens should be re-generated 228 | 229 | if chat: 230 | if tokenizer.eos_token_id in accurate_n_gram[0, :accurate_length]: 231 | eos_positions = torch.where(accurate_n_gram[0]==tokenizer.eos_token_id)[0] 232 | eos_position = eos_positions[0] 233 | 234 | generated_str = tokenizer.decode(accurate_n_gram[0, :eos_position], skip_special_tokens=True) 235 | else: 236 | generated_str = tokenizer.decode(accurate_n_gram[0, :accurate_length], skip_special_tokens=True) 237 | 238 | print(generated_str[prev_len:], flush=True, end="") 239 | prev_len = len(generated_str) 240 | 241 | iter_counter += 1 242 | 243 | return accurate_n_gram, first_correct_token, iter_counter, accurate_length 244 | 245 | 246 | @torch.inference_mode() 247 | def jacobi_forward_profiling( 248 | self, 249 | input_ids: torch.LongTensor = None, 250 | attention_mask: Optional[torch.Tensor] = None, 251 | position_ids: Optional[torch.LongTensor] = None, 252 | past_key_values: Optional[List[torch.FloatTensor]] = None, 253 | use_cache: Optional[bool] = None, 254 | max_new_tokens: Optional[int] = None, 255 | prefill_phase: Optional[bool] = False, 256 | ): 257 | 258 | assert use_cache == True 259 | 260 | if input_ids is not None: 261 | batch_size, seq_length = input_ids.shape[:2] 262 | else: 263 | raise ValueError("You have to specify either input_ids or inputs_embeds") 264 | 265 | if prefill_phase: # prefill phase, just compute the keys & values of prompt 266 | # self.model is the instance of class LlamaModel 267 | inputs_embeds = self.model.embed_tokens(input_ids) 268 | past_key_values_length = 0 269 | if use_cache: 270 | use_legacy_cache = not isinstance(past_key_values, Cache) 271 | if use_legacy_cache: 272 | past_key_values = DynamicCache.from_legacy_cache(past_key_values) 273 | past_key_values_length = past_key_values.get_usable_length(seq_length) 274 | 275 | if position_ids is None: 276 | device = input_ids.device if input_ids is not None else inputs_embeds.device 277 | position_ids = torch.arange( 278 | past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device 279 | ) 280 | position_ids = position_ids.unsqueeze(0) 281 | 282 | if self.model._use_flash_attention_2: 283 | # 2d mask is passed through the layers 284 | attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None 285 | elif self.model._use_sdpa : 286 | # output_attentions=True can not be supported when using SDPA, and we fall back on 287 | # the manual implementation that requires a 4D causal mask in all cases. 288 | attention_mask = _prepare_4d_causal_attention_mask_for_sdpa( 289 | attention_mask, 290 | (batch_size, seq_length), 291 | inputs_embeds, 292 | past_key_values_length, 293 | ) 294 | else: 295 | # 4d mask is passed through the layers 296 | attention_mask = _prepare_4d_causal_attention_mask( 297 | attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length 298 | ) 299 | # embed positions 300 | hidden_states = inputs_embeds 301 | 302 | # decoder layers 303 | for decoder_layer in self.model.layers: 304 | 305 | layer_outputs = decoder_layer( 306 | hidden_states, 307 | attention_mask=attention_mask, 308 | position_ids=position_ids, 309 | past_key_value=past_key_values, 310 | use_cache=use_cache, 311 | ) 312 | 313 | hidden_states = layer_outputs[0] 314 | 315 | if use_cache: 316 | next_decoder_cache = layer_outputs[1] 317 | 318 | hidden_states = self.model.norm(hidden_states) 319 | 320 | if self.config.pretraining_tp > 1: 321 | lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0) 322 | logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)] 323 | logits = torch.cat(logits, dim=-1) 324 | else: 325 | logits = self.lm_head(hidden_states) 326 | logits = logits.float() 327 | 328 | predict_next_tokens = torch.argmax(torch.nn.functional.softmax(logits, dim=-1), dim=-1) 329 | first_correct_token = predict_next_tokens[:, -1] 330 | return next_decoder_cache, first_correct_token 331 | else: # generation phase, input as random_initilized point and output as fixed point 332 | jacobian_trajectory = [] 333 | accurate_n_gram = torch.zeros_like(input_ids).to(input_ids.device) 334 | accurate_length = 0 335 | next_point = input_ids 336 | jacobian_trajectory.append(next_point) 337 | 338 | iter_counter = 0 339 | while True: 340 | 341 | current_point = next_point 342 | inputs_embeds = self.model.embed_tokens(current_point) 343 | attention_mask = None 344 | position_ids = None 345 | seq_length = current_point.shape[1] 346 | if use_cache: 347 | use_legacy_cache = not isinstance(past_key_values, Cache) 348 | if use_legacy_cache: 349 | past_key_values = DynamicCache.from_legacy_cache(past_key_values) 350 | past_key_values_length = past_key_values.get_usable_length(seq_length) 351 | # print(past_key_values_length) # return previous_seq_length 352 | if position_ids is None: 353 | device = input_ids.device if input_ids is not None else inputs_embeds.device 354 | position_ids = torch.arange( 355 | past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device 356 | ) 357 | position_ids = position_ids.unsqueeze(0) 358 | 359 | if self.model._use_flash_attention_2: 360 | # 2d mask is passed through the layers 361 | attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None 362 | elif self.model._use_sdpa : 363 | # output_attentions=True can not be supported when using SDPA, and we fall back on 364 | # the manual implementation that requires a 4D causal mask in all cases. 365 | attention_mask = _prepare_4d_causal_attention_mask_for_sdpa( 366 | attention_mask, 367 | (batch_size, seq_length), 368 | inputs_embeds, 369 | past_key_values_length, 370 | ) 371 | else: 372 | # 4d mask is passed through the layers 373 | attention_mask = _prepare_4d_causal_attention_mask( 374 | attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length 375 | ) 376 | # embed positions 377 | hidden_states = inputs_embeds 378 | 379 | # decoder layers 380 | for decoder_layer in self.model.layers: 381 | layer_outputs = decoder_layer( 382 | hidden_states, 383 | attention_mask=attention_mask, 384 | position_ids=position_ids, 385 | past_key_value=past_key_values, 386 | use_cache=use_cache, 387 | ) 388 | 389 | hidden_states = layer_outputs[0] 390 | 391 | hidden_states = self.model.norm(hidden_states) 392 | 393 | if self.config.pretraining_tp > 1: 394 | lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0) 395 | logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)] 396 | logits = torch.cat(logits, dim=-1) 397 | else: 398 | logits = self.lm_head(hidden_states) 399 | 400 | logits = logits.float() 401 | all_shift_one_token = torch.argmax(torch.nn.functional.softmax(logits, dim=-1) / 0.01, dim=-1) 402 | next_point= torch.cat((current_point[0, 0].view(1,-1), all_shift_one_token[0, :seq_length-1].view(1,-1)), dim=-1) 403 | jacobian_trajectory.append(next_point) 404 | 405 | if torch.all(torch.eq(current_point, next_point)).item(): 406 | #print('Successfully break!') 407 | #print(next_point) 408 | first_correct_token = torch.argmax(torch.nn.functional.softmax(logits, dim=-1), dim=-1)[:,-1] 409 | break 410 | past_key_values.delete_false_key_value(seq_length) 411 | 412 | iter_counter += 1 413 | 414 | return jacobian_trajectory[:-1], next_point, first_correct_token, iter_counter --------------------------------------------------------------------------------