| 98 | image=vllm_image, |
| 99 | ) |
| 100 | class Model: |
| 101 | def __init__(self, huggingface_model_id: str): |
| 102 | model_dir = merged_model_cache_dir(huggingface_model_id) |
| 103 | cache_model_weights(huggingface_model_id, model_dir) |
| 104 | |
| 105 | logging.info("Preloading model") |
| 106 | read_all_files(model_dir) |
| 107 | |
| 108 | logging.info(f"Loading model from volume {model_dir}") |
| 109 | self.engine = AsyncLLMEngine.from_engine_args(AsyncEngineArgs(model=model_dir)) |
| 110 | |
| 111 | @modal.method() |
| 112 | async def generate(self, request: Input) -> Output: |
| 113 | sample_params = SamplingParams( |
| 114 | n=request.n, |
| 115 | temperature=request.temperature, |
| 116 | max_tokens=request.max_tokens, |
| 117 | ) |
| 118 | |
| 119 | request_id = random_uuid() |
| 120 | |
| 121 | logging.info(f"Generating for request {request_id}") |
| 122 | output_generator = self.engine.generate( |
| 123 | request.prompt, sample_params, request_id=request_id |
| 124 | ) |
| 125 | |
| 126 | final_output: Union[RequestOutput, None] = None |
| 127 | async for request_output in output_generator: |
| 128 | # TODO: support streaming |
| 129 | final_output = request_output |
| 130 | |
| 131 | if final_output is None: |
| 132 | raise Exception("No output generated") |
| 133 | |
| 134 | prompt_tokens = len(final_output.prompt_token_ids) |
| 135 | completion_tokens = sum(len(x.token_ids) for x in final_output.outputs) |
| 136 | |
| 137 | output = Output( |
| 138 | id=request_id, |
| 139 | choices=[ |
| 140 | Choice(text=choice.text, finish_reason=choice.finish_reason) |
| 141 | for choice in final_output.outputs |
| 142 | ], |
| 143 | usage=Usage( |
| 144 | prompt_tokens=prompt_tokens, |
| 145 | completion_tokens=completion_tokens, |
| 146 | ), |
| 147 | ) |
| 148 | |
| 149 | return output |
| 150 | |
| 151 | |
| 152 | # TODO: convert this to a FastAPI endpoint like the trainer so we can codegen a |