|
| 1 | +import torch |
| 2 | +from torch import nn |
| 3 | + |
| 4 | +from transformers import AutoTokenizer, AutoModelForCausalLM, PreTrainedTokenizerBase, LlamaConfig |
| 5 | +from typing import Optional, Tuple, List, Type, Dict |
| 6 | + |
| 7 | +from vllm.transformers_utils.tokenizer import (detokenize_incrementally, |
| 8 | + get_tokenizer) |
| 9 | +from vllm.model_executor.quantization_utils import QuantizationConfig |
| 10 | +from vllm.sequence import SamplerOutput, SequenceOutputs |
| 11 | +import math |
| 12 | + |
| 13 | +import pdb |
| 14 | + |
| 15 | +from transformers.generation.logits_process import ( |
| 16 | + LogitsProcessorList, |
| 17 | + RepetitionPenaltyLogitsProcessor, |
| 18 | + TemperatureLogitsWarper, |
| 19 | + TopKLogitsWarper, |
| 20 | + TopPLogitsWarper, |
| 21 | +) |
| 22 | + |
| 23 | +def prepare_logits_processor( |
| 24 | + temperature: float, repetition_penalty: float, top_p: float, top_k: int |
| 25 | +) -> LogitsProcessorList: |
| 26 | + processor_list = LogitsProcessorList() |
| 27 | + # TemperatureLogitsWarper doesn't accept 0.0, 1.0 makes it a no-op so we skip two cases. |
| 28 | + if temperature >= 1e-5 and temperature != 1.0: |
| 29 | + processor_list.append(TemperatureLogitsWarper(temperature)) |
| 30 | + # if repetition_penalty > 1.0: |
| 31 | + # processor_list.append(RepetitionPenaltyLogitsProcessor(repetition_penalty)) |
| 32 | + if 1e-8 <= top_p < 1.0: |
| 33 | + processor_list.append(TopPLogitsWarper(top_p)) |
| 34 | + if top_k > 0: |
| 35 | + processor_list.append(TopKLogitsWarper(top_k)) |
| 36 | + return processor_list |
| 37 | + |
| 38 | +class BigDLLlamaForCausalLM(nn.Module): |
| 39 | + def __init__( |
| 40 | + self, |
| 41 | + config: LlamaConfig, |
| 42 | + quant_config: Optional[QuantizationConfig] = None, |
| 43 | + ): |
| 44 | + super().__init__() |
| 45 | + # pdb.set_trace() |
| 46 | + self.config = config |
| 47 | + self.model = AutoModelForCausalLM.from_pretrained(config._name_or_path) |
| 48 | + self.tokenizer = AutoTokenizer.from_pretrained(config._name_or_path) |
| 49 | + |
| 50 | + def decode(self, generated_ids: List[int]) -> str: |
| 51 | + return self.tokenizer.decode( |
| 52 | + generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False |
| 53 | + ) |
| 54 | + |
| 55 | + def forward( |
| 56 | + self, seq_group_meta_data_lists, kv_cache: Optional = None |
| 57 | + ) -> Tuple[torch.Tensor, List[Tuple[torch.Tensor, torch.Tensor]]]: |
| 58 | + kv_cache_0 = self.model.config.num_hidden_layers |
| 59 | + kv_cache_1 = 2 |
| 60 | + bigdl_kv_cache = [[torch.Tensor() for _ in range(kv_cache_1)] for _ in range(kv_cache_0)] |
| 61 | + seq_len = len(seq_group_meta_data_lists) |
| 62 | + for i in range(seq_len): |
| 63 | + if kv_cache.get(i) is None: |
| 64 | + kv_cache[i] = bigdl_kv_cache[:] |
| 65 | + |
| 66 | + bigdl_input_ids = [] |
| 67 | + bigdl_position_ids = [] |
| 68 | + cur_seq_ids = [] |
| 69 | + bigdl_sampling_params = {} |
| 70 | + |
| 71 | + all_decoding = True |
| 72 | + for seq_group_meta_data in seq_group_meta_data_lists: |
| 73 | + req_id = seq_group_meta_data.request_id |
| 74 | + all_decoding = all_decoding and (not seq_group_meta_data.is_prompt) |
| 75 | + seq_ids = list(seq_group_meta_data.seq_data.keys()) |
| 76 | + seq_id = seq_ids[0] |
| 77 | + print(seq_id) |
| 78 | + cur_seq_ids.append(seq_id) |
| 79 | + seq_data = seq_group_meta_data.seq_data[seq_id] |
| 80 | + |
| 81 | + cur_seq_input_ids = seq_data.get_token_ids() |
| 82 | + bigdl_input_ids.append(cur_seq_input_ids) |
| 83 | + |
| 84 | + bigdl_sampling_params[seq_id] = seq_group_meta_data.sampling_params |
| 85 | + |
| 86 | + context_len = seq_data.get_len() |
| 87 | + bigdl_position_ids.append(range(context_len)) |
| 88 | + if all_decoding: |
| 89 | + for seq_group_meta_data in seq_group_meta_data_lists: |
| 90 | + for i in range(kv_cache_0): |
| 91 | + for j in range(kv_cache_1): |
| 92 | + bigdl_kv_cache[i][j] = torch.cat((bigdl_kv_cache[i][j], kv_cache[seq_id][i][j]), dim=0) |
| 93 | + |
| 94 | + bigdl_input_ids = torch.tensor(bigdl_input_ids, device="cuda") |
| 95 | + bigdl_position_ids = torch.tensor(bigdl_position_ids, device="cuda") |
| 96 | + if all_decoding: |
| 97 | + kwargs = { |
| 98 | + "input_ids": bigdl_input_ids, |
| 99 | + "position_ids": bigdl_position_ids, |
| 100 | + "past_key_values": bigdl_kv_cache, |
| 101 | + "use_cache": True, |
| 102 | + "return_dict": True, |
| 103 | + } |
| 104 | + else: |
| 105 | + kwargs = { |
| 106 | + "input_ids": bigdl_input_ids, |
| 107 | + "position_ids": bigdl_position_ids, |
| 108 | + "past_key_values": None, |
| 109 | + "use_cache": True, |
| 110 | + "return_dict": True, |
| 111 | + } |
| 112 | + # kwargs["position_ids"] = position_ids |
| 113 | + outputs = self.model.forward(**kwargs) |
| 114 | + index = 0 |
| 115 | + bigdl_output = [] |
| 116 | + for seq_id in cur_seq_ids: |
| 117 | + cur_sampling_params = bigdl_sampling_params[seq_id] |
| 118 | + logits_processor = prepare_logits_processor( |
| 119 | + cur_sampling_params.temperature, 1, |
| 120 | + cur_sampling_params.top_p, cur_sampling_params.top_k |
| 121 | + ) |
| 122 | + |
| 123 | + last_token_logits = logits_processor(None, outputs.logits[index:index+1, -1, :])[0] |
| 124 | + probs = torch.softmax(last_token_logits, dim=-1) |
| 125 | + indices = torch.multinomial(probs, num_samples=2) |
| 126 | + tokens = [int(token) for token in indices.tolist()] |
| 127 | + |
| 128 | + logprobs = math.log(probs[tokens[0]]) |
| 129 | + seq_output = SequenceOutputs( |
| 130 | + parent_seq_id = seq_id, |
| 131 | + output_token = tokens[0], |
| 132 | + logprobs = {tokens[0]: logprobs} |
| 133 | + ) |
| 134 | + bigdl_output.append([seq_output]) |
| 135 | + |
| 136 | + for i in range(kv_cache_0): |
| 137 | + for j in range(kv_cache_1): |
| 138 | + kv_cache[seq_id][i][j] = outputs.past_key_values[i][j][index].unsqueeze(0) |
| 139 | + index = index + 1 |
| 140 | + return bigdl_output |
0 commit comments