winglian commited on
Commit
c1a7b3d
1 Parent(s): 2b9687f

add gemma instruct chat template (#1341)

Browse files

* add gemma instruct chat template

* support for chat tempalte strategy too

src/axolotl/prompt_strategies/chat_template.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ HF Chat Templates prompt strategy
3
+ """
4
+ from typing import Any, Dict, Optional
5
+
6
+ from axolotl.prompt_tokenizers import PromptTokenizingStrategy
7
+ from axolotl.prompters import Prompter
8
+ from axolotl.utils.chat_templates import chat_templates
9
+
10
+
11
+ class ChatTemplatePrompter(Prompter):
12
+ """prompter for HF chat templates"""
13
+
14
+ def __init__(self, tokenizer, chat_template=None, max_length=2048):
15
+ self.tokenizer = tokenizer
16
+ self.chat_template = chat_template
17
+ self.max_length = max_length
18
+
19
+ def build_prompt(self, conversation, add_generation_prompt=False):
20
+ return self.tokenizer.apply_chat_template(
21
+ conversation,
22
+ truncation=True,
23
+ max_length=self.max_length,
24
+ add_generation_prompt=add_generation_prompt,
25
+ chat_template=self.chat_template,
26
+ )
27
+
28
+
29
+ class ChatTemplateStrategy(PromptTokenizingStrategy):
30
+ """
31
+ Tokenizing strategy for instruction-based prompts.
32
+ """
33
+
34
+ def tokenize_prompt(self, prompt):
35
+ turns = self.get_conversation_thread(prompt)
36
+ prompt_ids = self.prompter.build_prompt([turns[0]], add_generation_prompt=True)
37
+ input_ids = self.prompter.build_prompt(turns)
38
+
39
+ if not self.train_on_inputs:
40
+ user_prompt_len = len(prompt_ids)
41
+ labels = [-100] * user_prompt_len + input_ids[user_prompt_len:]
42
+ else:
43
+ labels = input_ids
44
+
45
+ tokenized_prompt = {
46
+ "input_ids": input_ids,
47
+ "labels": labels,
48
+ "attention_mask": [1] * len(input_ids),
49
+ }
50
+
51
+ return tokenized_prompt
52
+
53
+ def get_conversation_thread(self, prompt):
54
+ conversations = prompt["conversations"]
55
+ # remap roles - allow for assistant turn
56
+ role_map = {
57
+ "human": "user",
58
+ "user": "user",
59
+ "assistant": "assistant",
60
+ "gpt": "assistant",
61
+ }
62
+ turns = [
63
+ {"role": role_map[t["from"]], "content": t["value"]} for t in conversations
64
+ ]
65
+ return turns
66
+
67
+
68
+ def load(tokenizer, cfg, ds_cfg: Optional[Dict[str, Any]] = None):
69
+ chat_template = (
70
+ ds_cfg["chat_template"] if ds_cfg and "chat_template" in ds_cfg else "chatml"
71
+ )
72
+ strategy = ChatTemplateStrategy(
73
+ ChatTemplatePrompter(tokenizer, chat_templates(chat_template)),
74
+ tokenizer,
75
+ cfg.train_on_inputs,
76
+ cfg.sequence_len,
77
+ )
78
+ return strategy
src/axolotl/utils/chat_templates.py CHANGED
@@ -22,6 +22,7 @@ def chat_templates(user_choice: str):
22
  "alpaca": "{% for message in messages %}{% if message['role'] == 'user' %}{{ '### Instruction: ' + message['content'] + '\n\n' }}{% elif message['role'] == 'assistant' %}{{ '### Response: ' + message['content'] + eos_token}}{% endif %}{% endfor %}",
23
  "inst": "{{ bos_token }}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if message['role'] == 'user' %}{{ '[INST] ' + message['content'] + ' [/INST]' }}{% elif message['role'] == 'assistant' %}{{ message['content'] + eos_token}}{% else %}{{ raise_exception('Only user and assistant roles are supported!') }}{% endif %}{% endfor %}", # I don't know what this one is called. Used by Mistral/Mixtral.
24
  "chatml": "{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% else %}{% set loop_messages = messages %}{% set system_message = 'You are a helpful assistant.' %}{% endif %}{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% for message in loop_messages %}{% if loop.index0 == 0 %}{{'<|im_start|>system\n' + system_message + '<|im_end|>\n'}}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
 
25
  }
26
 
27
  if user_choice in templates:
 
22
  "alpaca": "{% for message in messages %}{% if message['role'] == 'user' %}{{ '### Instruction: ' + message['content'] + '\n\n' }}{% elif message['role'] == 'assistant' %}{{ '### Response: ' + message['content'] + eos_token}}{% endif %}{% endfor %}",
23
  "inst": "{{ bos_token }}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if message['role'] == 'user' %}{{ '[INST] ' + message['content'] + ' [/INST]' }}{% elif message['role'] == 'assistant' %}{{ message['content'] + eos_token}}{% else %}{{ raise_exception('Only user and assistant roles are supported!') }}{% endif %}{% endfor %}", # I don't know what this one is called. Used by Mistral/Mixtral.
24
  "chatml": "{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% else %}{% set loop_messages = messages %}{% set system_message = 'You are a helpful assistant.' %}{% endif %}{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% for message in loop_messages %}{% if loop.index0 == 0 %}{{'<|im_start|>system\n' + system_message + '<|im_end|>\n'}}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
25
+ "gemma": "{{ bos_token }}{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '<start_of_turn>' + role + '\n' + message['content'] | trim + '<end_of_turn>\n' }}{% endfor %}{% if add_generation_prompt %}{{'<start_of_turn>model\n'}}{% endif %}",
26
  }
27
 
28
  if user_choice in templates:
src/axolotl/utils/config/models/input/v0_4_1/__init__.py CHANGED
@@ -76,6 +76,7 @@ class SFTDataset(BaseModel):
76
  type: Optional[Union[str, UserDefinedPrompterType]] = None
77
  shards: Optional[int] = None
78
  conversation: Optional[str] = None
 
79
  data_files: Optional[Union[str, List[str]]] = None
80
  name: Optional[str] = None
81
  ds_type: Optional[str] = None
 
76
  type: Optional[Union[str, UserDefinedPrompterType]] = None
77
  shards: Optional[int] = None
78
  conversation: Optional[str] = None
79
+ chat_template: Optional[str] = None
80
  data_files: Optional[Union[str, List[str]]] = None
81
  name: Optional[str] = None
82
  ds_type: Optional[str] = None