|
| 1 | +""" |
| 2 | +llama_cpp/llama_jinja_format.py |
| 3 | +""" |
| 4 | +import dataclasses |
| 5 | +from typing import Any, Callable, Dict, List, Optional, Protocol, Union |
| 6 | + |
| 7 | +import jinja2 |
| 8 | +from jinja2 import Template |
| 9 | + |
| 10 | +# NOTE: We sacrifice readability for usability. |
| 11 | +# It will fail to work as expected if we attempt to format it in a readable way. |
| 12 | +llama2_template = """{% for message in messages %}{% if message['role'] == 'user' %}[INST] {{ message['content'] }} [/INST]\n{% elif message['role'] == 'assistant' %}{{ message['content'] }}\n{% elif message['role'] == 'system' %}<<SYS>> {{ message['content'] }} <</SYS>>\n{% endif %}{% endfor %}""" |
| 13 | + |
| 14 | + |
| 15 | +class MetaSingleton(type): |
| 16 | + """ |
| 17 | + Metaclass for implementing the Singleton pattern. |
| 18 | + """ |
| 19 | + |
| 20 | + _instances = {} |
| 21 | + |
| 22 | + def __call__(cls, *args, **kwargs): |
| 23 | + if cls not in cls._instances: |
| 24 | + cls._instances[cls] = super(MetaSingleton, cls).__call__(*args, **kwargs) |
| 25 | + return cls._instances[cls] |
| 26 | + |
| 27 | + |
| 28 | +class Singleton(object, metaclass=MetaSingleton): |
| 29 | + """ |
| 30 | + Base class for implementing the Singleton pattern. |
| 31 | + """ |
| 32 | + |
| 33 | + def __init__(self): |
| 34 | + super(Singleton, self).__init__() |
| 35 | + |
| 36 | + |
| 37 | +@dataclasses.dataclass |
| 38 | +class ChatFormatterResponse: |
| 39 | + prompt: str |
| 40 | + stop: Optional[Union[str, List[str]]] = None |
| 41 | + |
| 42 | + |
| 43 | +# Base Chat Formatter Protocol |
| 44 | +class ChatFormatterInterface(Protocol): |
| 45 | + def __init__(self, template: Optional[object] = None): |
| 46 | + ... |
| 47 | + |
| 48 | + def __call__( |
| 49 | + self, |
| 50 | + messages: List[Dict[str, str]], |
| 51 | + **kwargs, |
| 52 | + ) -> ChatFormatterResponse: |
| 53 | + ... |
| 54 | + |
| 55 | + @property |
| 56 | + def template(self) -> str: |
| 57 | + ... |
| 58 | + |
| 59 | + |
| 60 | +class AutoChatFormatter(ChatFormatterInterface): |
| 61 | + def __init__( |
| 62 | + self, |
| 63 | + template: Optional[str] = None, |
| 64 | + template_class: Optional[Template] = None, |
| 65 | + ): |
| 66 | + if template is not None: |
| 67 | + self._template = template |
| 68 | + else: |
| 69 | + self._template = llama2_template # default template |
| 70 | + |
| 71 | + self._environment = jinja2.Environment( |
| 72 | + loader=jinja2.BaseLoader(), |
| 73 | + trim_blocks=True, |
| 74 | + lstrip_blocks=True, |
| 75 | + ).from_string( |
| 76 | + self._template, |
| 77 | + template_class=template_class, |
| 78 | + ) |
| 79 | + |
| 80 | + def __call__( |
| 81 | + self, |
| 82 | + messages: List[Dict[str, str]], |
| 83 | + **kwargs: Any, |
| 84 | + ) -> ChatFormatterResponse: |
| 85 | + formatted_sequence = self._environment.render(messages=messages, **kwargs) |
| 86 | + return ChatFormatterResponse(prompt=formatted_sequence) |
| 87 | + |
| 88 | + @property |
| 89 | + def template(self) -> str: |
| 90 | + return self._template |
| 91 | + |
| 92 | + |
| 93 | +class FormatterNotFoundException(Exception): |
| 94 | + pass |
| 95 | + |
| 96 | + |
| 97 | +class ChatFormatterFactory(Singleton): |
| 98 | + _chat_formatters: Dict[str, Callable[[], ChatFormatterInterface]] = {} |
| 99 | + |
| 100 | + def register_formatter( |
| 101 | + self, |
| 102 | + name: str, |
| 103 | + formatter_callable: Callable[[], ChatFormatterInterface], |
| 104 | + overwrite=False, |
| 105 | + ): |
| 106 | + if not overwrite and name in self._chat_formatters: |
| 107 | + raise ValueError( |
| 108 | + f"Formatter with name '{name}' is already registered. Use `overwrite=True` to overwrite it." |
| 109 | + ) |
| 110 | + self._chat_formatters[name] = formatter_callable |
| 111 | + |
| 112 | + def unregister_formatter(self, name: str): |
| 113 | + if name in self._chat_formatters: |
| 114 | + del self._chat_formatters[name] |
| 115 | + else: |
| 116 | + raise ValueError(f"No formatter registered under the name '{name}'.") |
| 117 | + |
| 118 | + def get_formatter_by_name(self, name: str) -> ChatFormatterInterface: |
| 119 | + try: |
| 120 | + formatter_callable = self._chat_formatters[name] |
| 121 | + return formatter_callable() |
| 122 | + except KeyError: |
| 123 | + raise FormatterNotFoundException( |
| 124 | + f"Invalid chat format: {name} (valid formats: {list(self._chat_formatters.keys())})" |
| 125 | + ) |
| 126 | + |
| 127 | + |
| 128 | +# Define a chat format class |
| 129 | +class Llama2Formatter(AutoChatFormatter): |
| 130 | + def __init__(self): |
| 131 | + super().__init__(llama2_template) |
| 132 | + |
| 133 | + |
| 134 | +# With the Singleton pattern applied, regardless of where or how many times |
| 135 | +# ChatFormatterFactory() is called, it will always return the same instance |
| 136 | +# of the factory, ensuring that the factory's state is consistent throughout |
| 137 | +# the application. |
| 138 | +ChatFormatterFactory().register_formatter("llama-2", Llama2Formatter) |
0 commit comments