From 71214d6775b9de5c0287f6fab5767688c256f73c Mon Sep 17 00:00:00 2001 From: Stephen Date: Mon, 17 Jun 2024 17:27:33 +0800 Subject: [PATCH] function calling support of openai style api for qwen1.5 and qwen2 model --- .DS_Store | Bin 0 -> 8196 bytes .idea/.gitignore | 8 + .idea/Qwen2.iml | 12 + .idea/deployment.xml | 15 + .idea/inspectionProfiles/Project_Default.xml | 14 + .../inspectionProfiles/profiles_settings.xml | 6 + .idea/misc.xml | 7 + .idea/modules.xml | 8 + .idea/vcs.xml | 6 + examples/.DS_Store | Bin 0 -> 6148 bytes openai_api/openai_api.py | 646 ++++++++++++++++++ openai_api/openai_service.sh | 8 + openai_api/qwen2chat.py | 144 ++++ openai_api/qwen_generation_utils.py | 428 ++++++++++++ 14 files changed, 1302 insertions(+) create mode 100644 .DS_Store create mode 100644 .idea/.gitignore create mode 100644 .idea/Qwen2.iml create mode 100644 .idea/deployment.xml create mode 100644 .idea/inspectionProfiles/Project_Default.xml create mode 100644 .idea/inspectionProfiles/profiles_settings.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 examples/.DS_Store create mode 100644 openai_api/openai_api.py create mode 100644 openai_api/openai_service.sh create mode 100644 openai_api/qwen2chat.py create mode 100644 openai_api/qwen_generation_utils.py diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..a54c2cb17da07ba7bb1fc66a915ea51538af10b1 GIT binary patch literal 8196 zcmeHM%Wl&^6upy%)}}&a0U{faCALvXP*o}FCZy?t1)Cbd0#JzKsI}^NtUO4iD3Z6p z$FSrNSnvUS4HBGrBubq`>Z(QMUTN+b&zzgFk3BQK4iSmwIIIzsiO4}wSlWeKW2#@3 z6)V`5`#^zsq8<%i#)`mLr03G95Y*@?;>QMZq$sU9a6*k2XCLH~qq5~TiGlM3a zgb62MM;10i5qfmQd74h5VURs5zzVD?pmO(Z3Q1Cz&U5*@no2KF_Wo$o!9~j*F6H@( z_iYm|m<&_Ywg#?f$8t^N{)t>T^S9cRbcbw2oKa^jCVqw%oW8N5?RuceHGdA$?7 ziF%WE>A{gqMx7|>4Rk;h_CR_6HcCP{Y07aD4t1<=Ivm$=+oea-X{}bTc=dx>#hccj zS1aEB!TxOKIuD;dJ3MKh$NfZp))z*?t}JxV954JA)E1Zh$sZ)KOit0J_zonypbqsZ zr5N>`EaEXZ%kr)8Z-+c9mz9(0E}pLx@+6QdqBeX=(d8$o;6kd((v!9}=61-n_R`|h zn%|ZE6f(?hEw3+IEjyu{pTD0J%B3G_l5XIJSLUW?R~tWfYh5~_V=NObdIj9WOb9RE zSn(BSx0nM$Pa8FPc>kZ@W=2-vCKT8*gO*kPf4uqo|4p14kI4$K0@tK~D7O4o6NAm) zfb-+3t=dERh@wpKGJ`qn+a literal 0 HcmV?d00001 diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 00000000..13566b81 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/Qwen2.iml b/.idea/Qwen2.iml new file mode 100644 index 00000000..be6d7ebb --- /dev/null +++ b/.idea/Qwen2.iml @@ -0,0 +1,12 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/deployment.xml b/.idea/deployment.xml new file mode 100644 index 00000000..33e90575 --- /dev/null +++ b/.idea/deployment.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 00000000..f4f1b89d --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,14 @@ + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 00000000..105ce2da --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 00000000..15e73d82 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 00000000..5bd76de3 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 00000000..35eb1ddf --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/examples/.DS_Store b/examples/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..13778cbb8d01328348dd025cb3da450603931071 GIT binary patch literal 6148 zcmeHK%}T>S5T3PBQ;X1pqQ`*OqOFud@e->Zyc*GiN^MNlV49UCwTDv3RbR%VZ{q9d z%bss)%u%-%lR-oWJ>xQJAFV^1E2bS&K`{ z_Oe~Due^KN_tI9{OB${21+7k{jQr8O<)4M^ezUlCAmg+Z#_g_32!l3;T%LzMiF&I=T^^#Ms4NK0TzFRIi)mn8p%-ic*J9{V1ho}?FXU)36Ye~r} z;|N}GGA`%I>&B6c@6bl^IY{6Z(kU`t(esrIj+zfDxR@y-uwo-~%m5z_yD-N!n$ipd zhJoKPK=*@#O6W3X8r9W-gK7Z~Ei@~^x%%}-bjX0{GG-dlf+BP(qD~duVhHXWgic4l z%kh~;oen~M8Ta8Y3+_+^Hy*-K;UHX%W;6^K1|}KE>1C1L|D&J#|H&k?G7K07=86Gf z9eRfiEQ#ONnd0cJbx^NSNhmJUs8Vp?=U7eXDc(d?f= 0: + response = response[t + len('Thought: '):] + response = response.strip() + choice_data = ChatCompletionResponseChoice( + index=0, + message=ChatMessage( + role='assistant', + content=response, + function_call={ + 'name': func_name, + 'arguments': func_args + }, + ), + finish_reason='function_call', + ) + return choice_data + + z = response.rfind('\nFinal Answer: ') + if z >= 0: + response = response[z + len('\nFinal Answer: '):] + choice_data = ChatCompletionResponseChoice( + index=0, + message=ChatMessage(role='assistant', content=response), + finish_reason='stop', + ) + return choice_data + + +# completion mode, not chat mode +def text_complete_last_message(history, stop_words_ids, gen_kwargs, system): + im_start = '<|im_start|>' + im_end = '<|im_end|>' + prompt = f'{im_start}system\n{system}{im_end}' + for i, (query, response) in enumerate(history): + query = query.lstrip('\n').rstrip() + response = response.lstrip('\n').rstrip() + prompt += f'\n{im_start}user\n{query}{im_end}' + prompt += f'\n{im_start}assistant\n{response}{im_end}' + prompt = prompt[:-len(im_end)] + + _stop_words_ids = [tokenizer.encode(im_end)] + if stop_words_ids: + for s in stop_words_ids: + _stop_words_ids.append(s) + stop_words_ids = _stop_words_ids + + input_ids = torch.tensor([tokenizer.encode(prompt)]).to(model.device) + output = model.generate(input_ids, + stop_words_ids=stop_words_ids, + **gen_kwargs).tolist()[0] + output = tokenizer.decode(output, errors='ignore') + assert output.startswith(prompt) + output = output[len(prompt):] + output = trim_stop_words(output, ['<|endoftext|>', im_end]) + print(f'\n{prompt}\n\n{output}\n') + return output + + +@app.post('/v1/chat/completions', response_model=ChatCompletionResponse) +async def create_chat_completion(request: ChatCompletionRequest): + global model, tokenizer + + gen_kwargs = {} + if request.top_k is not None: + gen_kwargs['top_k'] = request.top_k + if request.temperature is not None: + if request.temperature < 0.01: + gen_kwargs['top_k'] = 1 # greedy decoding + else: + # Not recommended. Please tune top_p instead. + gen_kwargs['temperature'] = request.temperature + if request.top_p is not None: + gen_kwargs['top_p'] = request.top_p + if request.max_length is not None: + gen_kwargs['max_new_tokens'] = request.max_length + else: + gen_kwargs['max_new_tokens'] = 512 + + stop_words = add_extra_stop_words(request.stop) + if request.functions: + stop_words = stop_words or [] + if 'Observation:' not in stop_words: + stop_words.append('Observation:') + + query, history, system = parse_messages(request.messages, + request.functions) + + if request.stream: + if request.functions: + raise HTTPException( + status_code=400, + detail= + 'Invalid request: Function calling is not yet implemented for stream mode.', + ) + generate = predict(query, + history, + request.model, + stop_words, + gen_kwargs, + system=system) + return EventSourceResponse(generate, media_type='text/event-stream') + + stop_words_ids = [tokenizer.encode(s) + for s in stop_words] if stop_words else None + if query is _TEXT_COMPLETION_CMD: + response = text_complete_last_message(history, + stop_words_ids=stop_words_ids, + gen_kwargs=gen_kwargs, + system=system) + else: + response, _ = model.chat( + tokenizer, + query, + history=history, + system=system, + stop_words_ids=stop_words_ids, + **gen_kwargs, + ) + print('') + pprint(history, indent=2) + print(f'{query}\n\n{response}\n') + _gc() + + response = trim_stop_words(response, stop_words) + if request.functions: + choice_data = parse_response(response) + else: + choice_data = ChatCompletionResponseChoice( + index=0, + message=ChatMessage(role='assistant', content=response), + finish_reason='stop', + ) + return ChatCompletionResponse(model=request.model, + choices=[choice_data], + object='chat.completion') + + +def _dump_json(data: BaseModel, *args, **kwargs) -> str: + try: + return data.model_dump_json(*args, **kwargs) + except AttributeError: # pydantic<2.0.0 + return data.json(*args, **kwargs) # noqa + + +async def predict( + query: str, + history: List[List[str]], + model_id: str, + stop_words: List[str], + gen_kwargs: Dict, + system: str, +): + global model, tokenizer + choice_data = ChatCompletionResponseStreamChoice( + index=0, delta=DeltaMessage(role='assistant'), finish_reason=None) + chunk = ChatCompletionResponse(model=model_id, + choices=[choice_data], + object='chat.completion.chunk') + yield '{}'.format(_dump_json(chunk, exclude_unset=True)) + + current_length = 0 + stop_words_ids = [tokenizer.encode(s) + for s in stop_words] if stop_words else None + + delay_token_num = max([len(x) for x in stop_words]) if stop_words_ids else 0 + response_generator = model.chat_stream(tokenizer, + query, + history=history, + stop_words_ids=stop_words_ids, + system=system, + **gen_kwargs) + for _new_response in response_generator: + if len(_new_response) <= delay_token_num: + continue + new_response = _new_response[:-delay_token_num] if delay_token_num else _new_response + + if len(new_response) == current_length: + continue + + new_text = new_response[current_length:] + current_length = len(new_response) + + choice_data = ChatCompletionResponseStreamChoice( + index=0, delta=DeltaMessage(content=new_text), finish_reason=None) + chunk = ChatCompletionResponse(model=model_id, + choices=[choice_data], + object='chat.completion.chunk') + yield '{}'.format(_dump_json(chunk, exclude_unset=True)) + + if current_length != len(_new_response): + # Determine whether to print the delay tokens + delayed_text = _new_response[current_length:] + new_text = trim_stop_words(delayed_text, stop_words) + if len(new_text) > 0: + choice_data = ChatCompletionResponseStreamChoice( + index=0, delta=DeltaMessage(content=new_text), finish_reason=None) + chunk = ChatCompletionResponse(model=model_id, + choices=[choice_data], + object='chat.completion.chunk') + yield '{}'.format(_dump_json(chunk, exclude_unset=True)) + + choice_data = ChatCompletionResponseStreamChoice(index=0, + delta=DeltaMessage(), + finish_reason='stop') + chunk = ChatCompletionResponse(model=model_id, + choices=[choice_data], + object='chat.completion.chunk') + yield '{}'.format(_dump_json(chunk, exclude_unset=True)) + yield '[DONE]' + + _gc() + + +def _get_args(): + parser = ArgumentParser() + parser.add_argument( + '-c', + '--checkpoint-path', + type=str, + default='Qwen/Qwen2-7B-Instruct', + help='Checkpoint name or path, default to %(default)r' + ) + parser.add_argument('--device', + help='number of device of cuda, e.g cuda:0', + type=str, + default='cuda:2' + ) + parser.add_argument('--api-auth', help='API authentication credentials') + parser.add_argument('--cpu-only', + action='store_true', + help='Run demo with CPU only') + parser.add_argument('--server-port', + type=int, + default=6071, + help='Demo server port.') + parser.add_argument( + '--server-name', + type=str, + default='0.0.0.0', + help= + 'Demo server name. Default: 127.0.0.1, which is only visible from the local computer.' + ' If you want other computers to access your server, use 0.0.0.0 instead.', + ) + parser.add_argument( + '--disable-gc', + action='store_true', + help='Disable GC after each response generated.', + ) + + args = parser.parse_args() + return args + + +if __name__ == '__main__': + args = _get_args() + + tokenizer = Qwen2Tokenizer.from_pretrained( + args.checkpoint_path, + resume_download=True + ) + + if args.api_auth: + app.add_middleware(BasicAuthMiddleware, + username=args.api_auth.split(':')[0], + password=args.api_auth.split(':')[1]) + + if args.cpu_only: + device_map = 'cpu' + else: + device_map = args.device + + model = Qwen2ForCausalLM.from_pretrained( + args.checkpoint_path, + device_map=device_map, + resume_download=True, + torch_dtype="auto", + ) + model.eval() + + model.generation_config = GenerationConfig.from_pretrained( + args.checkpoint_path, + resume_download=True, + ) + model.__class__ = Qwen2ForChatLM + + uvicorn.run(app, host=args.server_name, port=args.server_port, workers=1) diff --git a/openai_api/openai_service.sh b/openai_api/openai_service.sh new file mode 100644 index 00000000..3931f3f5 --- /dev/null +++ b/openai_api/openai_service.sh @@ -0,0 +1,8 @@ +#!/bin/bash + +PORT=6069 +lsof -i :$PORT | grep LISTEN | awk '{print $2}' | xargs kill -9 + +nohup python openai_api.py --checkpoint-path Qwen/Qwen1.5-7B-Chat --device 1 --server-port $PORT \ +--server-name '0.0.0.0' > nohup.out 2>&1 & + diff --git a/openai_api/qwen2chat.py b/openai_api/qwen2chat.py new file mode 100644 index 00000000..b54bbc55 --- /dev/null +++ b/openai_api/qwen2chat.py @@ -0,0 +1,144 @@ +from transformers import Qwen2ForCausalLM, Qwen2Tokenizer +from transformers import PreTrainedTokenizer, GenerationConfig, StoppingCriteriaList +from typing import TYPE_CHECKING, Optional, Tuple, Union, Callable, List, Any, Generator +from qwen_generation_utils import ( + HistoryType, + make_context, + decode_tokens, + get_stop_words_ids, + StopWordsLogitsProcessor, +) +import copy +import torch +from transformers.generation.logits_process import LogitsProcessorList +from transformers.generation.utils import GenerateOutput +from transformers.modeling_utils import PreTrainedModel +from transformers.generation.streamers import BaseStreamer + +_ERROR_BAD_CHAT_FORMAT = """\ +We detect you are probably using the pretrained model (rather than chat model) for chatting, since the chat_format in generation_config is not "chatml". +If you are directly using the model downloaded from Huggingface, please make sure you are using our "Qwen/Qwen-7B-Chat" Huggingface model (rather than "Qwen/Qwen-7B") when you call model.chat(). +我们检测到您可能在使用预训练模型(而非chat模型)进行多轮chat,因为您当前在generation_config指定的chat_format,并未设置为我们在对话中所支持的"chatml"格式。 +如果您在直接使用我们从Huggingface提供的模型,请确保您在调用model.chat()时,使用的是"Qwen/Qwen-7B-Chat"模型(而非"Qwen/Qwen-7B"预训练模型)。 +""" + +_SENTINEL = object() +_ERROR_STREAM_IN_CHAT = """\ +Pass argument `stream` to model.chat() is buggy, deprecated, and marked for removal. Please use model.chat_stream(...) instead of model.chat(..., stream=True). +向model.chat()传入参数stream的用法可能存在Bug,该用法已被废弃,将在未来被移除。请使用model.chat_stream(...)代替model.chat(..., stream=True)。 +""" + +_ERROR_INPUT_CPU_QUERY_WITH_FLASH_ATTN_ACTIVATED = """\ +We detect you have activated flash attention support, but running model computation on CPU. Please make sure that your input data has been placed on GPU. If you actually want to run CPU computation, please following the readme and set device_map="cpu" to disable flash attention when loading the model (calling AutoModelForCausalLM.from_pretrained). +检测到您的模型已激活了flash attention支持,但正在执行CPU运算任务。如使用flash attention,请您确认模型输入已经传到GPU上。如果您确认要执行CPU运算,请您在载入模型(调用AutoModelForCausalLM.from_pretrained)时,按照readme说法,指定device_map="cpu"以禁用flash attention。 +""" + +class Qwen2ForChatLM(Qwen2ForCausalLM): + def chat( + self, + tokenizer: PreTrainedTokenizer, + query: str, + history: Optional[HistoryType], + system: str = "You are a helpful assistant.", + stream: Optional[bool] = _SENTINEL, + stop_words_ids: Optional[List[List[int]]] = None, + generation_config: Optional[GenerationConfig] = None, + max_window_size=32000, + **kwargs, + ) -> Tuple[str, HistoryType]: + generation_config = generation_config if generation_config is not None else self.generation_config + + assert stream is _SENTINEL, _ERROR_STREAM_IN_CHAT + # assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT + if history is None: + history = [] + else: + # make a copy of the user's input such that is is left untouched + history = copy.deepcopy(history) + + if stop_words_ids is None: + stop_words_ids = [] + chat_format = 'chatml' + + raw_text, context_tokens = make_context( + tokenizer, + query, + history=history, + system=system, + max_window_size=max_window_size, + chat_format=chat_format + ) + + stop_words_ids.extend((get_stop_words_ids(chat_format, tokenizer))) + input_ids = torch.tensor([context_tokens]).to(self.device) + + outputs = self.generate( + input_ids, + stop_words_ids=stop_words_ids, + return_dict_in_generate=False, + generation_config=generation_config, + **kwargs, + ) + + response = decode_tokens( + outputs[0], + tokenizer, + raw_text_len=len(raw_text), + context_length=len(context_tokens), + chat_format=chat_format, + verbose=False, + errors='replace' + ) + + # as history is a copy of the user inputs, + # we can always return the new turn to the user. + # separating input history and output history also enables the user + # to implement more complex history management + history.append((query, response)) + + return response, history + + def generate( + self, + inputs: Optional[torch.Tensor] = None, + generation_config: Optional[GenerationConfig] = None, + logits_processor: Optional[LogitsProcessorList] = None, + stopping_criteria: Optional[StoppingCriteriaList] = None, + prefix_allowed_tokens_fn: Optional[ + Callable[[int, torch.Tensor], List[int]] + ] = None, + synced_gpus: Optional[bool] = None, + assistant_model: Optional["PreTrainedModel"] = None, + streamer: Optional["BaseStreamer"] = None, + **kwargs, + ) -> Union[GenerateOutput, torch.LongTensor]: + generation_config = generation_config if generation_config is not None else self.generation_config + + # Process stop_words_ids. + stop_words_ids = kwargs.pop("stop_words_ids", None) + if stop_words_ids is None and generation_config is not None: + stop_words_ids = getattr(generation_config, "stop_words_ids", None) + if stop_words_ids is None: + stop_words_ids = getattr(generation_config, "stop_words_ids", None) + + if stop_words_ids is not None: + stop_words_logits_processor = StopWordsLogitsProcessor( + stop_words_ids=stop_words_ids, + eos_token_id=generation_config.eos_token_id, + ) + if logits_processor is None: + logits_processor = LogitsProcessorList([stop_words_logits_processor]) + else: + logits_processor.append(stop_words_logits_processor) + + return super().generate( + inputs, + generation_config=generation_config, + logits_processor=logits_processor, + stopping_criteria=stopping_criteria, + prefix_allowed_tokens_fn=prefix_allowed_tokens_fn, + synced_gpus=synced_gpus, + assistant_model=assistant_model, + streamer=streamer, + **kwargs, + ) \ No newline at end of file diff --git a/openai_api/qwen_generation_utils.py b/openai_api/qwen_generation_utils.py new file mode 100644 index 00000000..6b412c1c --- /dev/null +++ b/openai_api/qwen_generation_utils.py @@ -0,0 +1,428 @@ +# Copyright (c) Alibaba Cloud. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +"""Generation support.""" + +from typing import Tuple, List, Union, Iterable + +import numpy as np +import torch +import torch.nn.functional as F +from transformers import PreTrainedTokenizer +from transformers import logging +from transformers.generation import LogitsProcessor + +logger = logging.get_logger(__name__) + +# Types. +HistoryType = List[Tuple[str, str]] +TokensType = List[int] +BatchTokensType = List[List[int]] + + +def pad_batch(batch: BatchTokensType, pad_id: int, seq_length: int) -> BatchTokensType: + for tokens in batch: + context_length = len(tokens) + if context_length < seq_length: + tokens.extend([pad_id] * (seq_length - context_length)) + return batch + + +def get_ltor_masks_and_position_ids( + data, + eod_token, + reset_position_ids, + reset_attention_mask, + eod_mask_loss, +): + """Build masks and position id for left to right model.""" + + # Extract batch size and sequence length. + micro_batch_size, seq_length = data.size() + + # Attention mask (lower triangular). + if reset_attention_mask: + att_mask_batch = micro_batch_size + else: + att_mask_batch = 1 + attention_mask = torch.tril( + torch.ones((att_mask_batch, seq_length, seq_length), device=data.device) + ).view(att_mask_batch, 1, seq_length, seq_length) + + # Loss mask. + loss_mask = torch.ones(data.size(), dtype=torch.float, device=data.device) + if eod_mask_loss: + loss_mask[data == eod_token] = 0.0 + + # Position ids. + position_ids = torch.arange(seq_length, dtype=torch.long, device=data.device) + position_ids = position_ids.unsqueeze(0).expand_as(data) + # We need to clone as the ids will be modifed based on batch index. + if reset_position_ids: + position_ids = position_ids.clone() + + if reset_position_ids or reset_attention_mask: + # Loop through the batches: + for b in range(micro_batch_size): + + # Find indecies where EOD token is. + eod_index = position_ids[b, data[b] == eod_token] + # Detach indecies from positions if going to modify positions. + if reset_position_ids: + eod_index = eod_index.clone() + + # Loop through EOD indecies: + prev_index = 0 + for j in range(eod_index.size()[0]): + i = eod_index[j] + # Mask attention loss. + if reset_attention_mask: + attention_mask[b, 0, (i + 1) :, : (i + 1)] = 0 + # Reset positions. + if reset_position_ids: + position_ids[b, (i + 1) :] -= i + 1 - prev_index + prev_index = i + 1 + + # Convert attention mask to binary: + attention_mask = attention_mask < 0.5 + + return attention_mask, loss_mask, position_ids + + +def get_batch(context_tokens: torch.LongTensor, eod_id: int): + """Generate batch from context tokens.""" + # Move to GPU. + tokens = context_tokens.contiguous().to(context_tokens.device) + # Get the attention mask and postition ids. + attention_mask, _, position_ids = get_ltor_masks_and_position_ids( + tokens, + eod_id, + reset_position_ids=False, + reset_attention_mask=False, + eod_mask_loss=False, + ) + return tokens, attention_mask, position_ids + + +def get_stop_words_ids(chat_format, tokenizer): + if chat_format == "raw": + stop_words_ids = [tokenizer.encode("Human:"), [tokenizer.eod_id]] + elif chat_format == "chatml": + #stop_words_ids = [[tokenizer.im_end_id], [tokenizer.im_start_id]] + #stop_words_ids = [tokenizer.encode("<|im_start|>"), tokenizer.encode("<|im_end|>")] + stop_words_ids = [[tokenizer.convert_tokens_to_ids("<|im_start|>")], [tokenizer.convert_tokens_to_ids("<|im_end|>")]] + else: + raise NotImplementedError(f"Unknown chat format {chat_format!r}") + return stop_words_ids + + +def make_context( + tokenizer: PreTrainedTokenizer, + query: str, + history: List[Tuple[str, str]] = None, + system: str = "", + max_window_size: int = 6144, + chat_format: str = "chatml", +): + if history is None: + history = [] + + if chat_format == "chatml": + im_start, im_end = "<|im_start|>", "<|im_end|>" + im_start_tokens = [tokenizer.convert_tokens_to_ids("<|im_start|>")] + im_end_tokens = [tokenizer.convert_tokens_to_ids("<|im_end|>")] + + # im_start_tokens = [tokenizer.im_start_id] + # im_end_tokens = [tokenizer.im_end_id] + nl_tokens = tokenizer.convert_tokens_to_ids(tokenizer.tokenize("\n")) + + # def _tokenize_str(role, content): + # return f"{role}\n{content}", tokenizer.encode( + # role, allowed_special=set() + # ) + nl_tokens + tokenizer.encode(content, allowed_special=set()) + def _tokenize_str(role, content): + return (f"{role}\n{content}", tokenizer.convert_tokens_to_ids(tokenizer.tokenize(role)) + + nl_tokens + tokenizer.convert_tokens_to_ids(tokenizer.tokenize(content))) + + + return f"{role}\n{content}" + system_text, system_tokens_part = _tokenize_str("system", system) + system_tokens = im_start_tokens + system_tokens_part + im_end_tokens + + raw_text = "" + context_tokens = [] + + for turn_query, turn_response in reversed(history): + query_text, query_tokens_part = _tokenize_str("user", turn_query) + query_tokens = im_start_tokens + query_tokens_part + im_end_tokens + response_text, response_tokens_part = _tokenize_str( + "assistant", turn_response + ) + response_tokens = im_start_tokens + response_tokens_part + im_end_tokens + + next_context_tokens = nl_tokens + query_tokens + nl_tokens + response_tokens + prev_chat = ( + f"\n{im_start}{query_text}{im_end}\n{im_start}{response_text}{im_end}" + ) + + current_context_size = ( + len(system_tokens) + len(next_context_tokens) + len(context_tokens) + ) + if current_context_size < max_window_size: + context_tokens = next_context_tokens + context_tokens + raw_text = prev_chat + raw_text + else: + break + + context_tokens = system_tokens + context_tokens + raw_text = f"{im_start}{system_text}{im_end}" + raw_text + context_tokens += ( + nl_tokens + + im_start_tokens + + _tokenize_str("user", query)[1] + + im_end_tokens + + nl_tokens + + im_start_tokens + #+ tokenizer.encode("assistant") + + tokenizer.convert_tokens_to_ids(tokenizer.tokenize("assistant")) + + nl_tokens + ) + raw_text += f"\n{im_start}user\n{query}{im_end}\n{im_start}assistant\n" + + elif chat_format == "raw": + raw_text = query + context_tokens = tokenizer.encode(raw_text) + else: + raise NotImplementedError(f"Unknown chat format {chat_format!r}") + + return raw_text, context_tokens + + +def _decode_default( + tokens: List[int], + *, + stop_words: List[str], + eod_words: List[str], + tokenizer: PreTrainedTokenizer, + raw_text_len: int, + verbose: bool = False, + return_end_reason: bool = False, + errors: str='replace', +): + trim_decode_tokens = tokenizer.decode(tokens, errors=errors)[raw_text_len:] + if verbose: + print("\nRaw Generate: ", trim_decode_tokens) + + end_reason = f"Gen length {len(tokens)}" + for stop_word in stop_words: + trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip() + for eod_word in eod_words: + if eod_word in trim_decode_tokens: + end_reason = f"Gen {eod_word!r}" + trim_decode_tokens = trim_decode_tokens.split(eod_word)[0] + trim_decode_tokens = trim_decode_tokens.strip() + if verbose: + print("\nEnd Reason:", end_reason) + print("\nGenerate: ", trim_decode_tokens) + + if return_end_reason: + return trim_decode_tokens, end_reason + else: + return trim_decode_tokens + + +def _decode_chatml( + tokens: List[int], + *, + stop_words: List[str], + eod_token_ids: List[int], + tokenizer: PreTrainedTokenizer, + raw_text_len: int, + context_length: int, + verbose: bool = False, + return_end_reason: bool = False, + errors: str='replace' +): + end_reason = f"Gen length {len(tokens)}" + eod_token_idx = context_length + for eod_token_idx in range(context_length, len(tokens)): + if tokens[eod_token_idx] in eod_token_ids: + end_reason = f"Gen {tokenizer.decode([tokens[eod_token_idx]])!r}" + break + + trim_decode_tokens = tokenizer.decode(tokens[:eod_token_idx], errors=errors)[raw_text_len:] + if verbose: + print("\nRaw Generate w/o EOD:", tokenizer.decode(tokens, errors=errors)[raw_text_len:]) + print("\nRaw Generate:", trim_decode_tokens) + print("\nEnd Reason:", end_reason) + for stop_word in stop_words: + trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip() + trim_decode_tokens = trim_decode_tokens.strip() + if verbose: + print("\nGenerate:", trim_decode_tokens) + + if return_end_reason: + return trim_decode_tokens, end_reason + else: + return trim_decode_tokens + + +def decode_tokens( + tokens: Union[torch.LongTensor, TokensType], + tokenizer: PreTrainedTokenizer, + raw_text_len: int, + context_length: int, + chat_format: str="chatml", + verbose: bool = False, + return_end_reason: bool = False, + errors: str="replace", +) -> str: + if torch.is_tensor(tokens): + tokens = tokens.cpu().numpy().tolist() + + if chat_format == "chatml": + return _decode_chatml( + tokens, + stop_words=[], + #eod_token_ids=[tokenizer.im_start_id, tokenizer.im_end_id], + eod_token_ids=[tokenizer.convert_tokens_to_ids("<|im_start|>"), tokenizer.convert_tokens_to_ids("<|im_start|>")], + tokenizer=tokenizer, + raw_text_len=raw_text_len, + context_length=context_length, + verbose=verbose, + return_end_reason=return_end_reason, + errors=errors, + ) + elif chat_format == "raw": + return _decode_default( + tokens, + stop_words=["<|endoftext|>"], + eod_words=["<|endoftext|>"], + tokenizer=tokenizer, + raw_text_len=raw_text_len, + verbose=verbose, + return_end_reason=return_end_reason, + errors=errors, + ) + else: + raise NotImplementedError(f"Unknown chat format {chat_format!r}") + + +class StopWordsLogitsProcessor(LogitsProcessor): + """ + :class:`transformers.LogitsProcessor` that enforces that when specified sequences appear, stop geration. + + Args: + stop_words_ids (:obj:`List[List[int]]`): + List of list of token ids of stop ids. In order to get the tokens of the words + that should not appear in the generated text, use :obj:`tokenizer(bad_word, + add_prefix_space=True).input_ids`. + eos_token_id (:obj:`int`): + The id of the `end-of-sequence` token. + """ + + def __init__(self, stop_words_ids: Iterable[Iterable[int]], eos_token_id: int): + + if not isinstance(stop_words_ids, List) or len(stop_words_ids) == 0: + raise ValueError( + f"`stop_words_ids` has to be a non-emtpy list, but is {stop_words_ids}." + ) + if any(not isinstance(bad_word_ids, list) for bad_word_ids in stop_words_ids): + raise ValueError( + f"`stop_words_ids` has to be a list of lists, but is {stop_words_ids}." + ) + if any( + any( + (not isinstance(token_id, (int, np.integer)) or token_id < 0) + for token_id in stop_word_ids + ) + for stop_word_ids in stop_words_ids + ): + raise ValueError( + f"Each list in `stop_words_ids` has to be a list of positive integers, but is {stop_words_ids}." + ) + + self.stop_words_ids = list( # stop_words_ids 中所有不等于 eos_token_id 的元素, eos_token是结束符 + filter( + lambda bad_token_seq: bad_token_seq != [eos_token_id], stop_words_ids + ) + ) + self.eos_token_id = eos_token_id + for stop_token_seq in self.stop_words_ids: + assert ( + len(stop_token_seq) > 0 + ), "Stop words token sequences {} cannot have an empty list".format( + stop_words_ids + ) + + def __call__( + self, input_ids: torch.LongTensor, scores: torch.FloatTensor + ) -> torch.FloatTensor: + stopped_samples = self._calc_stopped_samples(input_ids) + for i, should_stop in enumerate(stopped_samples): + if should_stop: + scores[i, self.eos_token_id] = float(2**15) + return scores + + def _tokens_match(self, prev_tokens: torch.LongTensor, tokens: List[int]) -> bool: + if len(tokens) == 0: + # if bad word tokens is just one token always ban it + return True + elif len(tokens) > len(prev_tokens): + # if bad word tokens are longer then prev input_ids they can't be equal + return False + elif prev_tokens[-len(tokens) :].tolist() == tokens: + # if tokens match + return True + else: + return False + + def _calc_stopped_samples(self, prev_input_ids: Iterable[int]) -> Iterable[int]: + stopped_samples = [] + for prev_input_ids_slice in prev_input_ids: + match = False + for stop_token_seq in self.stop_words_ids: + if self._tokens_match(prev_input_ids_slice, stop_token_seq): + # if tokens do not match continue + match = True + break + stopped_samples.append(match) + + return stopped_samples + + +def top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-float("Inf")): + """This function has been mostly taken from huggingface conversational + ai code at + https://medium.com/huggingface/how-to-build-a-state-of-the-art- + conversational-ai-with-transfer-learning-2d818ac26313""" + + if top_k > 0: + # Remove all tokens with a probability less than the + # last token of the top-k + indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None] + logits[indices_to_remove] = filter_value + + if top_p > 0.0: + # Cconvert to 1D + sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1) + cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1) + + # Remove tokens with cumulative probability above the threshold + sorted_indices_to_remove = cumulative_probs > top_p + # Shift the indices to the right to keep also the first token + # above the threshold + sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone() + sorted_indices_to_remove[..., 0] = 0 + for i in range(sorted_indices.size(0)): + indices_to_remove = sorted_indices[i][sorted_indices_to_remove[i]] + logits[i][indices_to_remove] = filter_value + + return logits + + +def switch(val1, val2, boolean): + boolean = boolean.type_as(val1) + return (1 - boolean) * val1 + boolean * val2