(
encodings,
num_beams=10,
max_new_tokens=64,
length_penalty=1.0,
**kwargs,
)
| 150 | model.config.bos_token_id = tokenizer.bos_token_id |
| 151 | |
| 152 | def evaluate( |
| 153 | encodings, |
| 154 | num_beams=10, |
| 155 | max_new_tokens=64, |
| 156 | length_penalty=1.0, |
| 157 | **kwargs, |
| 158 | ): |
| 159 | maxLen = max([len(_["input_ids"]) for _ in encodings]) |
| 160 | |
| 161 | padding_encodings = {"input_ids": []} |
| 162 | attention_mask = [] |
| 163 | |
| 164 | for _ in encodings: |
| 165 | L = len(_["input_ids"]) |
| 166 | padding_encodings["input_ids"].append([tokenizer.pad_token_id] * (maxLen - L) + _["input_ids"]) |
| 167 | attention_mask.append([0] * (maxLen - L) + [1] * L) |
| 168 | |
| 169 | # print(f"num_beams: {num_beams}") |
| 170 | generation_config = GenerationConfig( |
| 171 | num_beams=num_beams, |
| 172 | length_penalty=length_penalty, |
| 173 | num_return_sequences=num_beams, |
| 174 | pad_token_id = model.config.pad_token_id, |
| 175 | eos_token_id = model.config.eos_token_id, |
| 176 | max_new_tokens = max_new_tokens, |
| 177 | top_k=None, |
| 178 | top_p=None, |
| 179 | **kwargs |
| 180 | ) |
| 181 | |
| 182 | with torch.no_grad(): |
| 183 | clp = ConstrainedLogitsProcessor( |
| 184 | prefix_allowed_tokens_fn=prefix_allowed_tokens_fn, |
| 185 | num_beams=num_beams, |
| 186 | base_model=base_model, |
| 187 | eos_token_id=model.config.eos_token_id |
| 188 | ) |
| 189 | logits_processor = LogitsProcessorList([clp]) |
| 190 | |
| 191 | generation_output = model.generate( |
| 192 | torch.tensor(padding_encodings["input_ids"]).to(device), |
| 193 | attention_mask=torch.tensor(attention_mask).to(device), |
| 194 | generation_config=generation_config, |
| 195 | return_dict_in_generate=True, |
| 196 | output_scores=True, |
| 197 | logits_processor=logits_processor, |
| 198 | ) |
| 199 | |
| 200 | batched_completions = generation_output.sequences[:, maxLen:] |
| 201 | |
| 202 | |
| 203 | if base_model.lower().find("llama") > -1: |
| 204 | output = tokenizer.batch_decode(batched_completions, skip_special_tokens=True, clean_up_tokenization_spaces=False) |
| 205 | else: |
| 206 | output = tokenizer.batch_decode(batched_completions, skip_special_tokens=True) |
| 207 | |
| 208 | output = [_.split("Response:\n")[-1].strip() for _ in output] |
| 209 | real_outputs = [output[i * num_beams: (i + 1) * num_beams] for i in range(len(output) // num_beams)] |
no test coverage detected