|
| 1 | +"""PPL Inferencer.""" |
| 2 | + |
| 3 | +import os |
| 4 | +from typing import List, Optional |
| 5 | + |
| 6 | +import mmengine |
| 7 | +import torch |
| 8 | +from tqdm import tqdm |
| 9 | + |
| 10 | +from opencompass.models.base import BaseModel |
| 11 | +from opencompass.registry import ICL_INFERENCERS |
| 12 | + |
| 13 | +from ..icl_prompt_template import PromptTemplate |
| 14 | +from ..icl_retriever import BaseRetriever |
| 15 | +from ..utils import get_logger |
| 16 | +from .icl_base_inferencer import BaseInferencer, dump_results_dict |
| 17 | + |
| 18 | +logger = get_logger(__name__) |
| 19 | + |
| 20 | + |
| 21 | +@ICL_INFERENCERS.register_module() |
| 22 | +class InferencePPLOnlyInferencer(BaseInferencer): |
| 23 | + """InferencePPLOnlyInferencer class to calculate Inference-PPL only, no |
| 24 | + choice is made. This Inferencer is usually used along with |
| 25 | + AverageInferencePPLEvaluator. |
| 26 | +
|
| 27 | + Attributes: |
| 28 | + model (:obj:`BaseModel`, optional): The module to inference. |
| 29 | + max_seq_len (:obj:`int`): Maximum number of tokenized words allowed by |
| 30 | + the LM. |
| 31 | + batch_size (:obj:`int`, optional): Batch size for the :obj:`DataLoader` |
| 32 | + output_json_filepath (:obj:`str`, optional): File path for output |
| 33 | + `JSON` file. |
| 34 | + output_json_filename (:obj:`str`, optional): File name for output |
| 35 | + `JSON` file. |
| 36 | + save_every (:obj:`int`, optional): Save intermediate results every |
| 37 | + """ |
| 38 | + |
| 39 | + def __init__( |
| 40 | + self, |
| 41 | + model: BaseModel, |
| 42 | + max_seq_len: Optional[int] = None, |
| 43 | + batch_size: Optional[int] = 1, |
| 44 | + output_json_filepath: Optional[str] = './icl_inference_output', |
| 45 | + output_json_filename: Optional[str] = 'predictions', |
| 46 | + save_every: Optional[int] = 1, |
| 47 | + **kwargs) -> None: |
| 48 | + super().__init__( |
| 49 | + model=model, |
| 50 | + max_seq_len=max_seq_len, |
| 51 | + batch_size=batch_size, |
| 52 | + output_json_filename=output_json_filename, |
| 53 | + output_json_filepath=output_json_filepath, |
| 54 | + **kwargs, |
| 55 | + ) |
| 56 | + |
| 57 | + self.save_every = save_every |
| 58 | + |
| 59 | + def inference(self, |
| 60 | + retriever: BaseRetriever, |
| 61 | + ice_template: Optional[PromptTemplate] = None, |
| 62 | + prompt_template: Optional[PromptTemplate] = None, |
| 63 | + output_json_filepath: Optional[str] = None, |
| 64 | + output_json_filename: Optional[str] = None) -> List: |
| 65 | + # 1. Preparation for output logs |
| 66 | + output_handler = InferencePPLOnlyInferencerOutputHandler() |
| 67 | + |
| 68 | + if output_json_filepath is None: |
| 69 | + output_json_filepath = self.output_json_filepath |
| 70 | + if output_json_filename is None: |
| 71 | + output_json_filename = self.output_json_filename |
| 72 | + |
| 73 | + # 2. Get results of retrieval process |
| 74 | + ice_idx_list = retriever.retrieve() |
| 75 | + |
| 76 | + # 3. Generate prompts for testing input |
| 77 | + prompt_list, label_list = self.get_generation_prompt_list_and_label( |
| 78 | + ice_idx_list, |
| 79 | + retriever, |
| 80 | + max_seq_len=self.max_seq_len, |
| 81 | + ice_template=ice_template, |
| 82 | + prompt_template=prompt_template) |
| 83 | + |
| 84 | + prompt_list = [{ |
| 85 | + 'prompt': prompt, |
| 86 | + 'label': label |
| 87 | + } for prompt, label in zip(prompt_list, label_list)] |
| 88 | + |
| 89 | + # 3.1 Fetch and zip prompt & gold answer if output column exists |
| 90 | + ds_reader = retriever.dataset_reader |
| 91 | + |
| 92 | + assert ds_reader.output_column is None, ( |
| 93 | + 'InferencePPLOnlyInferencer supports `output_column=None` only.') |
| 94 | + |
| 95 | + # Create tmp json file for saving intermediate results and future |
| 96 | + # resuming |
| 97 | + index = 0 |
| 98 | + tmp_json_filepath = os.path.join(output_json_filepath, |
| 99 | + 'tmp_' + output_json_filename) |
| 100 | + if os.path.exists(tmp_json_filepath): |
| 101 | + # TODO: move resume to output handler |
| 102 | + try: |
| 103 | + tmp_result_dict = mmengine.load(tmp_json_filepath) |
| 104 | + except Exception: |
| 105 | + pass |
| 106 | + else: |
| 107 | + output_handler.results_dict = tmp_result_dict |
| 108 | + index = len(tmp_result_dict) |
| 109 | + |
| 110 | + # 4. Wrap prompts with Dataloader |
| 111 | + dataloader = self.get_dataloader(prompt_list[index:], self.batch_size) |
| 112 | + |
| 113 | + # 5. Inference for prompts in each batch |
| 114 | + logger.info('Starting inference process...') |
| 115 | + for datum in tqdm(dataloader, disable=not self.is_main_process): |
| 116 | + entry = [datum_single['prompt'] for datum_single in datum] |
| 117 | + label = [datum_single['label'] for datum_single in datum] |
| 118 | + |
| 119 | + # 5-1. Inference with local model |
| 120 | + with torch.no_grad(): |
| 121 | + (inference_loss_list, |
| 122 | + token_len_list) = self.model.get_ppl_tokenwise_from_template( |
| 123 | + entry, label) |
| 124 | + |
| 125 | + parsed_entries = self.model.parse_template(entry, mode='gen') |
| 126 | + # 5-3. Save current output |
| 127 | + for prompt, inference_loss, token_len, in zip( |
| 128 | + parsed_entries, inference_loss_list, token_len_list): |
| 129 | + output_handler.save_results(prompt, inference_loss, token_len, |
| 130 | + index) |
| 131 | + index = index + 1 |
| 132 | + |
| 133 | + # 5-4. Save intermediate results |
| 134 | + if (self.save_every is not None and index % self.save_every == 0 |
| 135 | + and self.is_main_process): |
| 136 | + output_handler.write_to_json(output_json_filepath, |
| 137 | + 'tmp_' + output_json_filename) |
| 138 | + |
| 139 | + # 6. Output |
| 140 | + if self.is_main_process: |
| 141 | + os.makedirs(output_json_filepath, exist_ok=True) |
| 142 | + output_handler.write_to_json(output_json_filepath, |
| 143 | + output_json_filename) |
| 144 | + if os.path.exists(tmp_json_filepath): |
| 145 | + os.remove(tmp_json_filepath) |
| 146 | + |
| 147 | + return [ |
| 148 | + sample['ppl'] for sample in output_handler.results_dict.values() |
| 149 | + ] |
| 150 | + |
| 151 | + def get_generation_prompt_list_from_retriever_indices( |
| 152 | + self, |
| 153 | + ice_idx_list: List[List[int]], |
| 154 | + retriever: BaseRetriever, |
| 155 | + max_seq_len: Optional[int] = None, |
| 156 | + ice_template: Optional[PromptTemplate] = None, |
| 157 | + prompt_template: Optional[PromptTemplate] = None): |
| 158 | + prompt_list = [] |
| 159 | + for idx, ice_idx in enumerate(ice_idx_list): |
| 160 | + ice = retriever.generate_ice(ice_idx, ice_template=ice_template) |
| 161 | + |
| 162 | + prompt = retriever.generate_prompt_for_generate_task( |
| 163 | + idx, |
| 164 | + ice, |
| 165 | + ice_template=ice_template, |
| 166 | + prompt_template=prompt_template) |
| 167 | + |
| 168 | + if max_seq_len is not None: |
| 169 | + prompt_token_num = self.model.get_token_len_from_template( |
| 170 | + prompt, mode='gen') |
| 171 | + while len(ice_idx) > 0 and prompt_token_num > max_seq_len: |
| 172 | + ice_idx = ice_idx[:-1] |
| 173 | + ice = retriever.generate_ice(ice_idx, |
| 174 | + ice_template=ice_template) |
| 175 | + prompt = retriever.generate_prompt_for_generate_task( |
| 176 | + idx, |
| 177 | + ice, |
| 178 | + ice_template=ice_template, |
| 179 | + prompt_template=prompt_template) |
| 180 | + prompt_token_num = self.model.get_token_len_from_template( |
| 181 | + prompt, mode='gen') |
| 182 | + prompt_list.append(prompt) |
| 183 | + return prompt_list |
| 184 | + |
| 185 | + def get_generation_prompt_list_and_label( |
| 186 | + self, |
| 187 | + ice_idx_list: List[List[int]], |
| 188 | + retriever: BaseRetriever, |
| 189 | + max_seq_len: Optional[int] = None, |
| 190 | + ice_template: Optional[PromptTemplate] = None, |
| 191 | + prompt_template: Optional[PromptTemplate] = None): |
| 192 | + prompt_list = [] |
| 193 | + label_list = [] |
| 194 | + for idx, ice_idx in enumerate(ice_idx_list): |
| 195 | + ice = retriever.generate_ice(ice_idx, ice_template=ice_template) |
| 196 | + |
| 197 | + prompt, label = retriever.generate_prompt_and_label_for_generate_task( # noqa |
| 198 | + idx, |
| 199 | + ice, |
| 200 | + ice_template=ice_template, |
| 201 | + prompt_template=prompt_template) |
| 202 | + |
| 203 | + if max_seq_len is not None: |
| 204 | + prompt_token_num = self.model.get_token_len_from_template( |
| 205 | + prompt, mode='gen') |
| 206 | + while len(ice_idx) > 0 and prompt_token_num > max_seq_len: |
| 207 | + ice_idx = ice_idx[:-1] |
| 208 | + ice = retriever.generate_ice(ice_idx, |
| 209 | + ice_template=ice_template) |
| 210 | + prompt, label = retriever.generate_prompt_for_generate_task( # noqa |
| 211 | + idx, |
| 212 | + ice, |
| 213 | + ice_template=ice_template, |
| 214 | + prompt_template=prompt_template) |
| 215 | + prompt_token_num = self.model.get_token_len_from_template( |
| 216 | + prompt, mode='gen') |
| 217 | + prompt_list.append(prompt) |
| 218 | + label_list.append(label) |
| 219 | + return prompt_list, label_list |
| 220 | + |
| 221 | + |
| 222 | +class InferencePPLOnlyInferencerOutputHandler: |
| 223 | + origin_prompt_dict = {} |
| 224 | + output_dict = {} |
| 225 | + results_dict = {} |
| 226 | + |
| 227 | + def __init__(self) -> None: |
| 228 | + self.results_dict = {} |
| 229 | + |
| 230 | + def write_to_json(self, save_dir: str, filename: str): |
| 231 | + """Dump the result to a json file.""" |
| 232 | + dump_results_dict(self.results_dict, os.path.join(save_dir, filename)) |
| 233 | + |
| 234 | + def save_results(self, origin_prompt, ppl, token_len, idx): |
| 235 | + self.results_dict[str(idx)] = { |
| 236 | + 'origin_prompt': origin_prompt, |
| 237 | + 'ppl': ppl, |
| 238 | + 'token_len': token_len, |
| 239 | + } |
0 commit comments