| 171 | |
| 172 | |
| 173 | class HfTorchDecoder(DecoderBase): |
| 174 | def __init__(self, name: str, dataset: str, **kwargs): |
| 175 | super().__init__(name=name, **kwargs) |
| 176 | self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| 177 | |
| 178 | kwargs = {} |
| 179 | kwargs["device_map"] = "auto" |
| 180 | kwargs["trust_remote_code"] = self.trust_remote_code |
| 181 | # string to torch dtype |
| 182 | kwargs["torch_dtype"] = getattr(torch, self.dtype) |
| 183 | self.skip_special_tokens = True |
| 184 | |
| 185 | print(f"{kwargs = }") |
| 186 | |
| 187 | self.tokenizer = AutoTokenizer.from_pretrained(name) |
| 188 | if self.tokenizer.chat_template is None: |
| 189 | self.eos += extra_eos_for_direct_completion(dataset) |
| 190 | |
| 191 | self.model = AutoModelForCausalLM.from_pretrained(name, **kwargs) |
| 192 | self.model = self.model.to(self.device) |
| 193 | |
| 194 | def is_direct_completion(self) -> bool: |
| 195 | return self.tokenizer.chat_template is not None |
| 196 | |
| 197 | @torch.inference_mode() |
| 198 | def codegen( |
| 199 | self, prompt: str, do_sample: bool = True, num_samples: int = 200 |
| 200 | ) -> List[str]: |
| 201 | if self.temperature == 0: |
| 202 | assert not do_sample |
| 203 | assert num_samples == 1 |
| 204 | |
| 205 | input_tokens = self.tokenizer.encode(prompt, return_tensors="pt").to( |
| 206 | self.device |
| 207 | ) |
| 208 | kwargs = {} |
| 209 | if do_sample: |
| 210 | kwargs["top_p"] = 0.95 |
| 211 | kwargs["temperature"] = self.temperature |
| 212 | |
| 213 | stop_sequencer = StopSequencer( |
| 214 | self.model, |
| 215 | model_type="causal", # or seq2seq |
| 216 | tokenizer=self.tokenizer, |
| 217 | ) |
| 218 | |
| 219 | model = stop_sequencer.register_stop_texts( |
| 220 | stop_texts=self.eos, |
| 221 | input_length=input_tokens.size(-1), |
| 222 | ) |
| 223 | |
| 224 | outputs = model.generate( |
| 225 | input_tokens, |
| 226 | max_new_tokens=self.max_new_tokens, |
| 227 | do_sample=do_sample, |
| 228 | num_return_sequences=min(self.batch_size, num_samples), |
| 229 | pad_token_id=self.tokenizer.eos_token_id, |
| 230 | **kwargs, |
nothing calls this directly
no outgoing calls
no test coverage detected