(
sources,
tokenizer: transformers.PreTrainedTokenizer,
template: str="tool-llama"
)
| 88 | |
| 89 | |
| 90 | def preprocess( |
| 91 | sources, |
| 92 | tokenizer: transformers.PreTrainedTokenizer, |
| 93 | template: str="tool-llama" |
| 94 | ) -> Dict: |
| 95 | conv = get_conversation_template(template) |
| 96 | if template == "tool-llama": |
| 97 | roles = {"human": conv.roles[0], "gpt": conv.roles[1]} |
| 98 | elif template == "tool-llama-single-round" or template == "tool-llama-multi-rounds": |
| 99 | roles = {"system": conv.roles[0], "user": conv.roles[1], "function": conv.roles[2], "assistant": conv.roles[3]} |
| 100 | |
| 101 | # Apply prompt templates |
| 102 | conversations = [] |
| 103 | for i, source in enumerate(sources): |
| 104 | conv.messages = [] |
| 105 | for j, sentence in enumerate(source): |
| 106 | role = roles[sentence["from"]] |
| 107 | conv.append_message(role, sentence["value"]) |
| 108 | conversations.append(conv.get_prompt()) |
| 109 | |
| 110 | # Tokenize conversations |
| 111 | input_ids = tokenizer( |
| 112 | conversations, |
| 113 | return_tensors="pt", |
| 114 | padding="max_length", |
| 115 | max_length=tokenizer.model_max_length, |
| 116 | truncation=True, |
| 117 | ).input_ids |
| 118 | targets = input_ids.clone() |
| 119 | |
| 120 | # Mask targets. Only compute loss on the assistant outputs. |
| 121 | sep = conv.sep + conv.roles[-1] + ": " |
| 122 | for conversation, target in zip(conversations, targets): |
| 123 | total_len = int(target.ne(tokenizer.pad_token_id).sum()) |
| 124 | turns = conversation.split(conv.sep2) |
| 125 | cur_len = 1 |
| 126 | target[:cur_len] = IGNORE_TOKEN_ID |
| 127 | for i, turn in enumerate(turns): |
| 128 | if turn == "": |
| 129 | continue |
| 130 | turn_len = len(tokenizer(turn).input_ids) |
| 131 | |
| 132 | parts = turn.split(sep) |
| 133 | |
| 134 | # only train on the last assistant reply, treat the history chat as instruction |
| 135 | prefix = parts[:-1] |
| 136 | instruction = "" |
| 137 | for part in prefix: |
| 138 | instruction += part |
| 139 | instruction += sep |
| 140 | |
| 141 | # "-2" is hardcoded for the LLaMA tokenizer to make the offset correct. |
| 142 | instruction_len = len(tokenizer(instruction).input_ids) - 2 |
| 143 | |
| 144 | # Ignore the user instructions |
| 145 | target[cur_len : cur_len + instruction_len] = IGNORE_TOKEN_ID |
| 146 | cur_len += turn_len |
| 147 |
no test coverage detected