|
| 1 | +# Copyright 2024 Bytedance Ltd. and/or its affiliates |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +import asyncio |
| 15 | +from typing import Any, Dict, List |
| 16 | + |
| 17 | +import torch |
| 18 | +from omegaconf import DictConfig |
| 19 | +from openai.types.chat.chat_completion import ChatCompletion |
| 20 | +from tensordict import TensorDict |
| 21 | + |
| 22 | +from verl.protocol import DataProto |
| 23 | +from verl.workers.rollout.async_server import ChatCompletionScheduler |
| 24 | + |
| 25 | + |
| 26 | +class NaiveChatCompletionScheduler(ChatCompletionScheduler): |
| 27 | + """ |
| 28 | + A very naive implementation of ChatCompletionScheduler for demo purpose, |
| 29 | + only do single-turn chat completion. |
| 30 | + """ |
| 31 | + |
| 32 | + def __init__( |
| 33 | + self, |
| 34 | + config: DictConfig, |
| 35 | + model_path: str, |
| 36 | + server_addresses: List[str], |
| 37 | + max_cache_size: int = 10000, |
| 38 | + ): |
| 39 | + super().__init__(config, model_path, server_addresses, max_cache_size) |
| 40 | + |
| 41 | + async def generate_sequences(self, batch: DataProto, **sampling_params) -> DataProto: |
| 42 | + kwargs = dict( |
| 43 | + n=self.config.n, |
| 44 | + max_completion_tokens=self.config.response_length, |
| 45 | + temperature=self.config.temperature, |
| 46 | + top_p=self.config.top_p, |
| 47 | + ) |
| 48 | + |
| 49 | + do_sample = batch.meta_info.get("do_sample", True) |
| 50 | + is_validate = batch.meta_info.get("validate", False) |
| 51 | + if not do_sample or is_validate: |
| 52 | + kwargs["n"] = 1 |
| 53 | + kwargs["temperature"] = 0 |
| 54 | + |
| 55 | + kwargs.update(sampling_params) |
| 56 | + print(f"[NaiveChatCompletionScheduler] generate_sequences sampling params: {kwargs}") |
| 57 | + |
| 58 | + async def callback(completions: ChatCompletion, info: Dict[str, Any], exception: Exception): |
| 59 | + conversation, batch_conversations, batch_index = ( |
| 60 | + info["conversation"], |
| 61 | + info["batch_conversations"], |
| 62 | + info["batch_index"], |
| 63 | + ) |
| 64 | + |
| 65 | + conversations = [] |
| 66 | + for choice in completions.choices: |
| 67 | + chat = conversation.copy() |
| 68 | + chat.append({"role": choice.message.role, "content": choice.message.content}) |
| 69 | + conversations.append(chat) |
| 70 | + batch_conversations[batch_index] = conversations |
| 71 | + |
| 72 | + # NOTE: we can call tools and resubmit chat completions here. |
| 73 | + # call_tools(completions, info) |
| 74 | + # await self.submit_chat_completions(callback2, ...) |
| 75 | + |
| 76 | + tasks, batch_conversations = [], [None] * len(batch) |
| 77 | + for batch_index, conversation in enumerate(batch.non_tensor_batch["raw_prompt"]): |
| 78 | + # raw_prompt: [{"role": "user", "content": ""}, ["role": "assistant", "content"], ...] |
| 79 | + tasks.append( |
| 80 | + asyncio.create_task( |
| 81 | + self.submit_chat_completions( |
| 82 | + callback=callback, |
| 83 | + callback_additional_info={ |
| 84 | + "batch_conversations": batch_conversations, |
| 85 | + "batch_index": batch_index, |
| 86 | + "conversation": list(conversation), |
| 87 | + }, |
| 88 | + model=self.model_name, |
| 89 | + messages=conversation, |
| 90 | + **kwargs, |
| 91 | + ) |
| 92 | + ) |
| 93 | + ) |
| 94 | + await asyncio.gather(*tasks) |
| 95 | + print("[NaiveChatCompletionScheduler] generate_sequences done") |
| 96 | + |
| 97 | + return self._postprocess(batch, batch_conversations, kwargs["n"]) |
| 98 | + |
| 99 | + def _postprocess( |
| 100 | + self, batch: DataProto, batch_conversations: List[List[List[Dict[str, str]]]], n: int |
| 101 | + ) -> DataProto: |
| 102 | + # NOTE: consistent with batch version of generate_sequences in vllm_rollout_spmd.py |
| 103 | + # prompts: left pad |
| 104 | + # responses: right pad |
| 105 | + # input_ids: prompt + response |
| 106 | + # attention_mask: [0,0,0,0,1,1,1,1, | 1,1,1,0,0,0,0,0] |
| 107 | + # position_ids: [0,0,0,0,0,1,2,3, | 4,5,6,7,8,9,10,11] |
| 108 | + |
| 109 | + # prompts: [prompt] from input dataset |
| 110 | + prompts = [ |
| 111 | + self.tokenizer.apply_chat_template(prompt, add_generation_prompt=True, tokenize=False) |
| 112 | + for prompt in batch.non_tensor_batch["raw_prompt"] |
| 113 | + ] |
| 114 | + |
| 115 | + # flatten batch_conversations if n > 1 |
| 116 | + assert len(batch_conversations) == len(prompts) |
| 117 | + batch_conversations = [conversation for conversations in batch_conversations for conversation in conversations] |
| 118 | + assert len(batch_conversations) == len(prompts) * n |
| 119 | + |
| 120 | + # sequences: [prompt + response] |
| 121 | + sequences = [ |
| 122 | + self.tokenizer.apply_chat_template(conversation, add_generation_prompt=False, tokenize=False) |
| 123 | + for conversation in batch_conversations |
| 124 | + ] |
| 125 | + |
| 126 | + # responses: [response] |
| 127 | + # TODO: mask out tools calling tokens? |
| 128 | + responses = [sequence[len(prompts[i // n]) :] for i, sequence in enumerate(sequences)] |
| 129 | + |
| 130 | + prompts = self.tokenizer(prompts, return_tensors="pt", padding="longest", padding_side="left") |
| 131 | + responses = self.tokenizer(responses, return_tensors="pt", padding="longest", padding_side="right") |
| 132 | + if n > 1: |
| 133 | + prompts["input_ids"] = prompts["input_ids"].repeat_interleave(n, dim=0) |
| 134 | + prompts["attention_mask"] = prompts["attention_mask"].repeat_interleave(n, dim=0) |
| 135 | + |
| 136 | + input_ids = torch.cat([prompts["input_ids"], responses["input_ids"]], dim=1) |
| 137 | + attention_mask = torch.cat([prompts["attention_mask"], responses["attention_mask"]], dim=1) |
| 138 | + position_ids = (attention_mask.cumsum(dim=1) - 1) * attention_mask |
| 139 | + |
| 140 | + batch = TensorDict( |
| 141 | + { |
| 142 | + "prompts": prompts["input_ids"], |
| 143 | + "responses": responses["input_ids"], |
| 144 | + "input_ids": input_ids, |
| 145 | + "attention_mask": attention_mask, |
| 146 | + "position_ids": position_ids, |
| 147 | + }, |
| 148 | + batch_size=len(input_ids), |
| 149 | + ) |
| 150 | + |
| 151 | + return DataProto(batch=batch) |
0 commit comments