|
| 1 | +from typing import Union |
| 2 | +import json |
| 3 | + |
| 4 | +import jinja2 |
| 5 | +from vllm import LLM, SamplingParams |
| 6 | +from vllm.sampling_params import StructuredOutputsParams |
| 7 | + |
| 8 | +from align_system.algorithms.abstracts import StructuredInferenceEngine |
| 9 | + |
| 10 | +# Sometimes the internal default for VLLM is 50, |
| 11 | +# leading to very short (and often invalid JSON) outputs. Setting a |
| 12 | +# somewhat generous default. |
| 13 | +DEFAULT_MAX_TOKENS = 8192 |
| 14 | + |
| 15 | +class VLLMInferenceEngine(StructuredInferenceEngine): |
| 16 | + def __init__(self, |
| 17 | + model_name, |
| 18 | + sampling_params=None): |
| 19 | + self.llm = LLM(model=model_name) |
| 20 | + |
| 21 | + self.sampling_params = sampling_params |
| 22 | + if self.sampling_params is None: |
| 23 | + self.sampling_params = {} |
| 24 | + |
| 25 | + if 'max_tokens' not in self.sampling_params: |
| 26 | + self.sampling_params['max_tokens'] = DEFAULT_MAX_TOKENS |
| 27 | + |
| 28 | + def dialog_to_prompt(self, dialog: list[dict]) -> str: |
| 29 | + tokenizer = self.llm.get_tokenizer() |
| 30 | + |
| 31 | + try: |
| 32 | + encoded_dialog = tokenizer.apply_chat_template(dialog) |
| 33 | + except jinja2.exceptions.TemplateError: |
| 34 | + # Assume that the tokenizer chat template doesn't accept |
| 35 | + # system messages; combine system message first user |
| 36 | + # message |
| 37 | + # Ensure each dialog element is a dict |
| 38 | + system_msg, user_msg, *rest = [dict(d) for d in dialog] |
| 39 | + |
| 40 | + assert user_msg['role'] == 'user' |
| 41 | + |
| 42 | + updated_content = system_msg['content'] + '\n' + user_msg['content'] |
| 43 | + |
| 44 | + dialog = [{'role': 'user', 'content': updated_content}, *rest] |
| 45 | + |
| 46 | + encoded_dialog = tokenizer.apply_chat_template(dialog) |
| 47 | + |
| 48 | + return tokenizer.decode(encoded_dialog) |
| 49 | + |
| 50 | + def run_inference(self, |
| 51 | + prompts: Union[str, list[str]], |
| 52 | + schema: str) -> Union[dict, list[dict]]: |
| 53 | + json_schema = json.loads(schema) |
| 54 | + schema_params = StructuredOutputsParams(json=json_schema) |
| 55 | + |
| 56 | + structured_sampling_params = SamplingParams( |
| 57 | + **self.sampling_params, |
| 58 | + structured_outputs=schema_params) |
| 59 | + |
| 60 | + outputs = self.llm.generate( |
| 61 | + prompts, |
| 62 | + sampling_params=structured_sampling_params) |
| 63 | + |
| 64 | + parsed_outputs = [json.loads(o.outputs[0].text) for o in outputs] |
| 65 | + |
| 66 | + if isinstance(prompts, str): |
| 67 | + # Return single instance if single prompt provided as a string |
| 68 | + return parsed_outputs[0] |
| 69 | + else: |
| 70 | + return parsed_outputs |
0 commit comments