|
| 1 | +from typing import Optional, Callable, Iterable, List, Dict |
| 2 | + |
| 3 | +from pydantic import BaseModel |
| 4 | + |
| 5 | + |
| 6 | +class Message(BaseModel): |
| 7 | + role: str |
| 8 | + content: str |
| 9 | + |
| 10 | + weight: Optional[float] = None |
| 11 | + |
| 12 | + |
| 13 | +class Conversation(BaseModel): |
| 14 | + items: List[Message] |
| 15 | + |
| 16 | + condition: str = "" |
| 17 | + system: str = "" |
| 18 | + |
| 19 | + |
| 20 | +class ConversationTemplate(BaseModel): |
| 21 | + tokenizer: Callable |
| 22 | + |
| 23 | + # Prompt |
| 24 | + role_prefix: Callable |
| 25 | + eot: str |
| 26 | + |
| 27 | + inference_condition: Optional[str] = None |
| 28 | + |
| 29 | + # Private |
| 30 | + bos_tokens_: List[int] |
| 31 | + eot_tokens_: List[int] |
| 32 | + |
| 33 | + def __init__(self, **data): |
| 34 | + tokenizer = data["tokenizer"] |
| 35 | + eot = data["eot"] |
| 36 | + bos_tokens_ = tokenizer("").input_ids |
| 37 | + eot_tokens_ = tokenizer(eot, add_special_tokens=False).input_ids |
| 38 | + |
| 39 | + super().__init__(**data, bos_tokens_=bos_tokens_, eot_tokens_=eot_tokens_) |
| 40 | + |
| 41 | + def _safe_tokenize(self, strings: Iterable[str]) -> List[List[int]]: |
| 42 | + return self.tokenizer(strings, split_special_tokens=True, return_attention_mask=False, add_special_tokens=False).input_ids |
| 43 | + |
| 44 | + def tokenize_conversations(self, conversations: Iterable[Conversation], inference: bool = False, seq_level_weight: bool = False): |
| 45 | + # Pre-tokenize all conversations |
| 46 | + default_condition = self.inference_condition if inference else "" |
| 47 | + |
| 48 | + sys_mappings = set() |
| 49 | + role_mappings = set() |
| 50 | + all_text = [] |
| 51 | + for conv in conversations: |
| 52 | + sys_mappings.add(conv.system) |
| 53 | + for msg in conv.items: |
| 54 | + role_mappings.add((msg.role, conv.condition or default_condition)) |
| 55 | + all_text.append(msg.content) |
| 56 | + |
| 57 | + sys_mappings = list(sys_mappings) |
| 58 | + role_mappings = list(role_mappings) |
| 59 | + |
| 60 | + # Tokenize |
| 61 | + sys_mappings = dict(zip(sys_mappings, self._safe_tokenize(sys_mappings))) |
| 62 | + role_mappings = dict(zip(role_mappings, self._safe_tokenize([self.role_prefix(*args) for args in role_mappings]))) |
| 63 | + all_text = self._safe_tokenize(all_text) |
| 64 | + |
| 65 | + # Convert |
| 66 | + result_tokens = [] |
| 67 | + result_weights = [] |
| 68 | + all_text_idx = 0 |
| 69 | + for conv in conversations: |
| 70 | + tokens = [] |
| 71 | + weights = [] |
| 72 | + |
| 73 | + # bos tokens |
| 74 | + tokens.extend(self.bos_tokens_) |
| 75 | + weights.extend([0.] * len(self.bos_tokens_)) |
| 76 | + |
| 77 | + # System |
| 78 | + if conv.system: |
| 79 | + system = sys_mappings[conv.system] |
| 80 | + tokens.extend(system) |
| 81 | + weights.extend([0.] * len(system)) |
| 82 | + |
| 83 | + tokens.extend(self.eot_tokens_) |
| 84 | + weights.extend([0.] * len(self.eot_tokens_)) |
| 85 | + |
| 86 | + # Messages |
| 87 | + last_idx = len(conv.items) - 1 |
| 88 | + for idx, msg in enumerate(conv.items): |
| 89 | + # Prefix |
| 90 | + role = role_mappings[(msg.role, conv.condition or default_condition)] |
| 91 | + tokens.extend(role) |
| 92 | + weights.extend([0.] * len(role)) |
| 93 | + |
| 94 | + # Message |
| 95 | + text = all_text[all_text_idx] |
| 96 | + all_text_idx += 1 |
| 97 | + |
| 98 | + # weight |
| 99 | + w = None |
| 100 | + if not inference: |
| 101 | + assert msg.weight is not None |
| 102 | + |
| 103 | + w = msg.weight |
| 104 | + if seq_level_weight: |
| 105 | + w /= len(text) + len(self.eot_tokens_) |
| 106 | + |
| 107 | + # Message tokens |
| 108 | + tokens.extend(text) |
| 109 | + weights.extend([w] * len(text)) |
| 110 | + |
| 111 | + if not (inference and idx == last_idx): # Do not add EOT on last turn during inference |
| 112 | + tokens.extend(self.eot_tokens_) |
| 113 | + weights.extend([w] * len(self.eot_tokens_)) |
| 114 | + |
| 115 | + # Append result |
| 116 | + result_tokens.append(tokens) |
| 117 | + result_weights.append(weights) |
| 118 | + |
| 119 | + # Sanity check |
| 120 | + assert all_text_idx == len(all_text) |
| 121 | + |
| 122 | + return result_tokens, result_weights |
0 commit comments