Spaces:
Paused
Paused
:recycle: [Refactor] Use official chat_template to replace mannual parses for several models, and remove unused message split functions
Browse filesFiles changed (2)
2 unmodified lines34567893 unmodified lines13141516171827 unmodified lines4647484950515253545556571 unmodified line59606162636418 unmodified lines838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512617 unmodified lines14414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426521 unmodified lines2872882892902912922932942952 unmodified linesfrom transformers import AutoTokenizerfrom constants.models import AVAILABLE_MODELSfrom utils.logger import logger3 unmodified linesself.model = modelelse:self.model = "mixtral-8x7b"self.system_roles = ["system"]self.inst_roles = ["user", "system", "inst"]self.answer_roles = ["assistant", "bot", "answer", "model"]27 unmodified linesreturn concat_messagesdef merge(self, messages) -> str:# Mistral and Mixtral:# <s> [INST] Instruction [/INST] Model answer </s> [INST] Follow-up instruction [/INST]# OpenChat:# GPT4 Correct User: Hello<|end_of_turn|>GPT4 Correct Assistant: Hi<|end_of_turn|>GPT4 Correct User: How are you today?<|end_of_turn|>GPT4 Correct Assistant:# Nous Mixtral:# <|im_start|>system# You are "Hermes 2".<|im_end|>1 unmodified line# Hello, who are you?<|im_end|># <|im_start|>assistant# Google Gemma-it# <start_of_turn>user# How does the brain work?<end_of_turn>18 unmodified linesself.cached_str = f"[INST] {content} [/INST]"if self.cached_str:self.merged_str += f"{self.cached_str}"# https://huggingface.co/NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO#prompt-formatelif self.model in ["nous-mixtral-8x7b"]:self.merged_str_list = []for message in self.messages:role = message["role"]content = message["content"]if role not in ["system", "user", "assistant"]:role = self.default_rolemessage_line = f"<|im_start|>{role}\n{content}<|im_end|>"self.merged_str_list.append(message_line)self.merged_str_list.append("<|im_start|>assistant")self.merged_str = "\n".join(self.merged_str_list)# https://huggingface.co/openchat/openchat-3.5-0106elif self.model in ["openchat-3.5"]:tokenizer = AutoTokenizer.from_pretrained("openchat/openchat-3.5-0106")self.merged_str = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)# self.messages = self.concat_messages_by_role(messages)# self.merged_str_list = []# self.end_of_turn = "<|end_of_turn|>"# for message in self.messages:# role = message["role"]# content = message["content"]# if role in self.inst_roles:# self.merged_str_list.append(# f"GPT4 Correct User:\n{content}{self.end_of_turn}"# )# elif role in self.answer_roles:# self.merged_str_list.append(# f"GPT4 Correct Assistant:\n{content}{self.end_of_turn}"# )# else:# self.merged_str_list.append(# f"GPT4 Correct User: {content}{self.end_of_turn}"# )# self.merged_str_list.append(f"GPT4 Correct Assistant:\n")# self.merged_str = "\n".join(self.merged_str_list)# https://huggingface.co/google/gemma-7b-it#chat-templateelif self.model in ["gemma-7b"]:self.messages = self.concat_messages_by_role(messages)17 unmodified lines)self.merged_str_list.append(f"{self.start_of_turn}model\n")self.merged_str = "\n".join(self.merged_str_list)else:self.merged_str = "\n".join([f'`{message["role"]}`:\n{message["content"]}\n'for message in self.messages])return self.merged_strdef convert_pair_matches_to_messages(self, pair_matches_list):messages = []if len(pair_matches_list) <= 0:messages = [{"role": "user","content": self.merged_str,}]else:for match in pair_matches_list:inst = match.group("inst")answer = match.group("answer")messages.extend([{"role": "user", "content": inst.strip()},{"role": "assistant", "content": answer.strip()},])return messagesdef append_last_instruction_to_messages(self, inst_matches_list, pair_matches_list):if len(inst_matches_list) > len(pair_matches_list):self.messages.extend([{"role": "user","content": inst_matches_list[-1].group("inst").strip(),}])def split(self, merged_str) -> list:self.merged_str = merged_strself.messages = []if self.model in ["mixtral-8x7b", "mistral-7b"]:pair_pattern = (r"<s>\s*\[INST\](?P<inst>[\s\S]*?)\[/INST\](?P<answer>[\s\S]*?)</s>")pair_matches = re.finditer(pair_pattern, self.merged_str, re.MULTILINE)pair_matches_list = list(pair_matches)self.messages = self.convert_pair_matches_to_messages(pair_matches_list)inst_pattern = r"\[INST\](?P<inst>[\s\S]*?)\[/INST\]"inst_matches = re.finditer(inst_pattern, self.merged_str, re.MULTILINE)inst_matches_list = list(inst_matches)self.append_last_instruction_to_messages(inst_matches_list, pair_matches_list)elif self.model in ["nous-mixtral-8x7b"]:# https://huggingface.co/NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO#prompt-format# message_pattern = r"<\|im_start\|>(?P<role>system|user|assistant)[\s\n]*(?P<content>[\s\S]*?)<\|im_end\|>"message_pattern = r"<\|im_start\|>(?P<role>system|user|assistant)[\s\n]*(?P<content>[\s\S]*?)<\|im_end\|>"message_matches = re.finditer(message_pattern, self.merged_str, flags=re.MULTILINE | re.IGNORECASE)message_matches_list = list(message_matches)logger.note(f"message_matches_list: {message_matches_list}")for match in message_matches_list:role = match.group("role")content = match.group("content")self.messages.append({"role": role, "content": content.strip()})elif self.model in ["openchat-3.5"]:pair_pattern = r"GPT4 Correct User:(?P<inst>[\s\S]*?)<\|end_of_turn\|>\s*GPT4 Correct Assistant:(?P<answer>[\s\S]*?)<\|end_of_turn\|>"pair_matches = re.finditer(pair_pattern, self.merged_str, flags=re.MULTILINE | re.IGNORECASE)pair_matches_list = list(pair_matches)self.messages = self.convert_pair_matches_to_messages(pair_matches_list)inst_pattern = r"GPT4 Correct User:(?P<inst>[\s\S]*?)<\|end_of_turn\|>"inst_matches = re.finditer(inst_pattern, self.merged_str, flags=re.MULTILINE | re.IGNORECASE)inst_matches_list = list(inst_matches)self.append_last_instruction_to_messages(inst_matches_list, pair_matches_list)# https://huggingface.co/google/gemma-7b-it#chat-templateelif self.model in ["gemma-7b"]:pair_pattern = r"<start_of_turn>user[\s\n]*(?P<inst>[\s\S]*?)<end_of_turn>[\s\n]*<start_of_turn>model(?P<answer>[\s\S]*?)<end_of_turn>"pair_matches = re.finditer(pair_pattern, self.merged_str, flags=re.MULTILINE | re.IGNORECASE)pair_matches_list = list(pair_matches)self.messages = self.convert_pair_matches_to_messages(pair_matches_list)inst_pattern = r"<start_of_turn>user\n(?P<inst>[\s\S]*?)<end_of_turn>"inst_matches = re.finditer(inst_pattern, self.merged_str, flags=re.MULTILINE | re.IGNORECASE)inst_matches_list = list(inst_matches)self.append_last_instruction_to_messages(inst_matches_list, pair_matches_list)else:self.messages = [{"role": "user","content": self.merged_str,}]return self.messagesif __name__ == "__main__":# model = "mixtral-8x7b"21 unmodified linesmerged_str = composer.merge(messages)logger.note("merged_str:")logger.mesg(merged_str)logger.note("splitted messages:")pprint(composer.split(merged_str))# logger.note("merged merged_str:")# logger.mesg(composer.merge(composer.split(merged_str)))# python -m messagers.message_composer2 unmodified lines34567893 unmodified lines1314151617181927 unmodified lines474849505152535455565758596061621 unmodified line64656667686970717218 unmodified lines91929394959617 unmodified lines11411511611711811912012112212312412512612712812913021 unmodified lines1521531541551562 unmodified linesfrom transformers import AutoTokenizerfrom constants.models import AVAILABLE_MODELS, MODEL_MAPfrom utils.logger import logger3 unmodified linesself.model = modelelse:self.model = "mixtral-8x7b"self.model_fullname = MODEL_MAP[self.model]self.system_roles = ["system"]self.inst_roles = ["user", "system", "inst"]self.answer_roles = ["assistant", "bot", "answer", "model"]27 unmodified linesreturn concat_messagesdef merge(self, messages) -> str:# Templates for Chat Models# - https://huggingface.co/docs/transformers/main/en/chat_templating# - https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1#instruction-format# - https://huggingface.co/NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO#prompt-format# - https://huggingface.co/openchat/openchat-3.5-0106# - https://huggingface.co/google/gemma-7b-it#chat-template# Mistral and Mixtral:# <s> [INST] Instruction [/INST] Model answer </s> [INST] Follow-up instruction [/INST]# Nous Mixtral:# <|im_start|>system# You are "Hermes 2".<|im_end|>1 unmodified line# Hello, who are you?<|im_end|># <|im_start|>assistant# OpenChat:# GPT4 Correct User: Hello<|end_of_turn|>GPT4 Correct Assistant: Hi<|end_of_turn|>GPT4 Correct User: How are you today?<|end_of_turn|>GPT4 Correct Assistant:# Google Gemma-it# <start_of_turn>user# How does the brain work?<end_of_turn>18 unmodified linesself.cached_str = f"[INST] {content} [/INST]"if self.cached_str:self.merged_str += f"{self.cached_str}"# https://huggingface.co/google/gemma-7b-it#chat-templateelif self.model in ["gemma-7b"]:self.messages = self.concat_messages_by_role(messages)17 unmodified lines)self.merged_str_list.append(f"{self.start_of_turn}model\n")self.merged_str = "\n".join(self.merged_str_list)# https://huggingface.co/NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO#prompt-format# https://huggingface.co/openchat/openchat-3.5-0106# elif self.model in ["openchat-3.5", "nous-mixtral-8x7b"]:else:tokenizer = AutoTokenizer.from_pretrained("openchat/openchat-3.5-0106")self.merged_str = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)return self.merged_strif __name__ == "__main__":# model = "mixtral-8x7b"21 unmodified linesmerged_str = composer.merge(messages)logger.note("merged_str:")logger.mesg(merged_str)# python -m messagers.message_composer
123456aiohttpfastapihttpxmarkdown2[all]openaipydantic1234567aiohttpfastapihttpxjinja2markdown2[all]openaipydantic
messagers/message_composer.py+18-157
requirements.txt+1