tokenization_cohere_fast.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. # coding=utf-8
  2. # Copyright 2024 Cohere team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # This file is based on the tokenization_llama_fast.py file in transformers
  16. import pickle
  17. from typing import Dict, List, Literal, Union
  18. from tokenizers import processors
  19. from ...tokenization_utils_base import BatchEncoding
  20. from ...tokenization_utils_fast import PreTrainedTokenizerFast
  21. from ...utils import logging
  22. from ...utils.versions import require_version
  23. require_version("tokenizers>=0.13.3")
  24. logger = logging.get_logger(__name__)
  25. VOCAB_FILES_NAMES = {"tokenizer_file": "tokenizer.json"}
  26. PRETRAINED_VOCAB_FILES_MAP = {
  27. "tokenizer_file": {
  28. "Cohere/Command-nightly": "https://huggingface.co/Cohere/Command-nightly/blob/main/tokenizer.json",
  29. },
  30. }
  31. # fmt: off
  32. DEFAULT_SYSTEM_PROMPT = "You are Command-R, a brilliant, sophisticated, AI-assistant trained to assist human users by providing thorough responses. You are trained by Cohere."
  33. DEFAULT_RAG_PREAMBLE = """## Task and Context
  34. You help people answer their questions and other requests interactively. You will be asked a very wide array of requests on all kinds of topics. You will be equipped with a wide range of search engines or similar tools to help you, which you use to research your answer. You should focus on serving the user's needs as best you can, which will be wide-ranging.
  35. ## Style Guide
  36. Unless the user asks for a different style of answer, you should answer in full sentences, using proper grammar and spelling."""
  37. # fmt: on
  38. class CohereTokenizerFast(PreTrainedTokenizerFast):
  39. """
  40. Construct a Cohere tokenizer. Based on byte-level Byte-Pair-Encoding.
  41. This uses notably ByteFallback and NFC normalization.
  42. ```python
  43. >>> from transformers import AutoTokenizer
  44. >>> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01")
  45. >>> tokenizer.encode("Hello this is a test")
  46. [5, 28339, 2075, 1801, 1671, 3282]
  47. ```
  48. If you want to change the `bos_token` or the `eos_token`, make sure to specify them when initializing the model, or
  49. call `tokenizer.update_post_processor()` to make sure that the post-processing is correctly done (otherwise the
  50. values of the first token and final token of an encoded sequence will not be correct). For more details, checkout
  51. [post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) documentation.
  52. You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since
  53. the model was not pretrained this way, it might yield a decrease in performance.
  54. <Tip>
  55. When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
  56. </Tip>
  57. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
  58. refer to this superclass for more information regarding those methods.
  59. Args:
  60. vocab_file (`str`, *optional*):
  61. Path to the vocabulary file.
  62. merges_file (`str`, *optional*):
  63. Path to the merges file.
  64. tokenizer_file (`str`, *optional*):
  65. [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
  66. contains everything needed to load the tokenizer.
  67. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
  68. Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
  69. extra spaces.
  70. unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<UNK>"`):
  71. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  72. token instead.
  73. bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<BOS_TOKEN>"`):
  74. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  75. eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<|END_OF_TURN_TOKEN|>"`):
  76. The end of sequence token.
  77. add_bos_token (`bool`, *optional*, defaults to `True`):
  78. Whether or not to add an `bos_token` at the start of sequences.
  79. add_eos_token (`bool`, *optional*, defaults to `False`):
  80. Whether or not to add an `eos_token` at the end of sequences.
  81. use_default_system_prompt (`bool`, *optional*, defaults to `False`):
  82. Whether or not the default system prompt for Cohere tokenizer should be used.
  83. add_prefix_space (`bool`, *optional*, defaults to `False`):
  84. Whether or not the tokenizer should automatically add a prefix space
  85. """
  86. vocab_files_names = VOCAB_FILES_NAMES
  87. pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
  88. padding_side = "left"
  89. model_input_names = ["input_ids", "attention_mask"]
  90. slow_tokenizer_class = None
  91. # No `max_model_input_sizes`
  92. def __init__(
  93. self,
  94. vocab_file=None,
  95. merges_file=None,
  96. tokenizer_file=None,
  97. clean_up_tokenization_spaces=False,
  98. unk_token="<UNK>",
  99. bos_token="<BOS_TOKEN>",
  100. eos_token="<|END_OF_TURN_TOKEN|>",
  101. add_bos_token=True,
  102. add_eos_token=False,
  103. use_default_system_prompt=False,
  104. add_prefix_space=False,
  105. **kwargs,
  106. ):
  107. super().__init__(
  108. vocab_file=vocab_file,
  109. merges_file=merges_file,
  110. tokenizer_file=tokenizer_file,
  111. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  112. unk_token=unk_token,
  113. bos_token=bos_token,
  114. eos_token=eos_token,
  115. add_bos_token=add_bos_token,
  116. add_eos_token=add_eos_token,
  117. use_default_system_prompt=use_default_system_prompt,
  118. add_prefix_space=add_prefix_space,
  119. **kwargs,
  120. )
  121. self._add_bos_token = add_bos_token
  122. self._add_eos_token = add_eos_token
  123. self.update_post_processor()
  124. self.use_default_system_prompt = use_default_system_prompt
  125. self.vocab_file = vocab_file
  126. self.grounded_generation_template = kwargs.pop("grounded_generation_template", None)
  127. self.tool_use_template = kwargs.pop("tool_use_template", None)
  128. # TODO @ArthurZucker this can only work one way for now, to update later-on. Tests should also properly
  129. # check this as they were green before.
  130. pre_tok_state = pickle.dumps(self.backend_tokenizer.pre_tokenizer)
  131. decoder_state = pickle.dumps(self.backend_tokenizer.decoder)
  132. if add_prefix_space:
  133. pre_tok_state = pre_tok_state.replace(b'"add_prefix_space":false', b'"add_prefix_space": true')
  134. decoder_state = decoder_state.replace(b'"add_prefix_space":false', b'"add_prefix_space": true')
  135. self.backend_tokenizer.pre_tokenizer = pickle.loads(pre_tok_state)
  136. self.backend_tokenizer.decoder = pickle.loads(decoder_state)
  137. self.add_prefix_space = add_prefix_space
  138. def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
  139. is_split_into_words = kwargs.get("is_split_into_words", False)
  140. if not (self.add_prefix_space or not is_split_into_words):
  141. raise Exception(
  142. f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with"
  143. " pretokenized inputs."
  144. )
  145. return super()._batch_encode_plus(*args, **kwargs)
  146. def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
  147. is_split_into_words = kwargs.get("is_split_into_words", False)
  148. if not (self.add_prefix_space or not is_split_into_words):
  149. raise Exception(
  150. f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with"
  151. " pretokenized inputs."
  152. )
  153. return super()._encode_plus(*args, **kwargs)
  154. def update_post_processor(self):
  155. """
  156. Updates the underlying post processor with the current `bos_token` and `eos_token`.
  157. """
  158. bos = self.bos_token
  159. bos_token_id = self.bos_token_id
  160. if bos is None and self.add_bos_token:
  161. raise ValueError("add_bos_token = True but bos_token = None")
  162. eos = self.eos_token
  163. eos_token_id = self.eos_token_id
  164. if eos is None and self.add_eos_token:
  165. raise ValueError("add_eos_token = True but eos_token = None")
  166. single = f"{(bos+':0 ') if self.add_bos_token else ''}$A:0{(' '+eos+':0') if self.add_eos_token else ''}"
  167. pair = f"{single}{(' '+bos+':1') if self.add_bos_token else ''} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"
  168. special_tokens = []
  169. if self.add_bos_token:
  170. special_tokens.append((bos, bos_token_id))
  171. if self.add_eos_token:
  172. special_tokens.append((eos, eos_token_id))
  173. self._tokenizer.post_processor = processors.TemplateProcessing(
  174. single=single, pair=pair, special_tokens=special_tokens
  175. )
  176. @property
  177. def add_eos_token(self):
  178. return self._add_eos_token
  179. @property
  180. def add_bos_token(self):
  181. return self._add_bos_token
  182. @add_eos_token.setter
  183. def add_eos_token(self, value):
  184. self._add_eos_token = value
  185. self.update_post_processor()
  186. @add_bos_token.setter
  187. def add_bos_token(self, value):
  188. self._add_bos_token = value
  189. self.update_post_processor()
  190. def apply_tool_use_template(
  191. self,
  192. conversation: Union[List[Dict[str, str]]],
  193. tools: List[Dict],
  194. **kwargs,
  195. ) -> Union[str, List[int]]:
  196. """Create a Command-R tool-use prompt.
  197. Once rendered, the prompt instructs the model to generate a list of actions to perform on a set of user supplied tools
  198. to help carry out the user's requests.
  199. Conceptually, this works in the same way as `apply_chat_format`, but takes an additional `tools` parameter.
  200. Converts a chat in the form of a list of dictionaries with `"role"` and `"content"` keys and a list of available
  201. tools for the model to use into a prompt string, or a list of token ids.
  202. This method will use the tokenizer's `default_tool_use_template` template specified at the class level.
  203. You can override the default template using the `tool_use_template` kwarg but the quality of your results may decrease.
  204. Args:
  205. conversation (Union[List[Dict[str, str]]]): A list of dicts
  206. with "role" and "content" keys, representing the chat history so far.
  207. tools (List[Dict]): a list of tools to render into the prompt for the model to choose from.
  208. See an example at the bottom of the docstring.
  209. The format should be:
  210. * name (str): The name of the tool to be called. Valid names contain only the characters a-z,
  211. A-Z, 0-9, _ and must not begin with a digit.
  212. * description (str): The description of what the tool does, the model uses the description to
  213. choose when and how to call the function.
  214. * parameter_definitions (List[Dict]): The input parameters of the tool. Accepts a dictionary
  215. where the key is the name of the parameter and the value is the parameter spec.
  216. Valid parameter names contain only the characters a-z, A-Z, 0-9, _ and must not begin with a digit.
  217. Parameter specs are as follows:
  218. * description (str): The description of the parameter.
  219. * type (str): the type of the parameter - most effective for python builtin data types, such as 'str', 'bool'
  220. * required: boolean: Denotes whether the parameter is always present (required) or not. Defaults to not required.
  221. add_generation_prompt (bool, *optional*): Whether to end the prompt with the token(s) that indicate
  222. the start of an assistant message. This is useful when you want to generate a response from the model.
  223. Note that this argument will be passed to the chat template, and so it must be supported in the
  224. template for this argument to have any effect.
  225. tokenize (`bool`, defaults to `True`):
  226. Whether to tokenize the output. If `False`, the output will be a string.
  227. padding (`bool`, defaults to `False`):
  228. Whether to pad sequences to the maximum length. Has no effect if tokenize is `False`.
  229. truncation (`bool`, defaults to `False`):
  230. Whether to truncate sequences at the maximum length. Has no effect if tokenize is `False`.
  231. max_length (`int`, *optional*):
  232. Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is `False`. If
  233. not specified, the tokenizer's `max_length` attribute will be used as a default.
  234. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  235. If set, will return tensors of a particular framework. Has no effect if tokenize is `False`. Acceptable
  236. values are:
  237. - `'tf'`: Return TensorFlow `tf.Tensor` objects.
  238. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  239. - `'np'`: Return NumPy `np.ndarray` objects.
  240. - `'jax'`: Return JAX `jnp.ndarray` objects.
  241. return_dict (`bool`, *optional*, defaults to `False`):
  242. Whether to return a dictionary with named outputs. Has no effect if tokenize is `False`.
  243. **tokenizer_kwargs: Additional kwargs to pass to the tokenizer.
  244. Returns:
  245. `str`: A rendered prompt string.
  246. or if tokenize=True:
  247. `List[int]`: A list of token ids representing the tokenized chat so far, including control tokens. This
  248. output is ready to pass to the model, either directly or via methods like `generate()`.
  249. Examples:
  250. ```python
  251. >> tokenizer = CohereTokenizerFast.from_pretrained("CohereForAI/c4ai-command-r-v01")
  252. >> tools = [
  253. {
  254. "name": "internet_search",
  255. "description": "Returns a list of relevant document snippets for a textual query retrieved from the internet",
  256. "parameter_definitions": {
  257. "query": {
  258. "description": "Query to search the internet with",
  259. "type": "str",
  260. "required": True
  261. }
  262. }
  263. },
  264. {
  265. "name': "directly_answer",
  266. "description": "Calls a standard (un-augmented) AI chatbot to generate a response given the conversation history",
  267. "parameter_definitions": {}
  268. }
  269. ]
  270. >> conversation = [
  271. {"role": "user", "content": "Whats the biggest penguin in the world?"}
  272. ]
  273. >> # render the prompt, ready for user to inspect, or for input into the model:
  274. >> prompt = tokenizer.apply_tool_use_template(conversation, tools=tools, tokenize=False, add_generation_prompt=True)
  275. >> print(prompt)
  276. <BOS_TOKEN><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># Safety Preamble
  277. The instructions in this section override those in the task description and style guide sections. Don't answer questions that are harmful or immoral.
  278. # System Preamble
  279. ## Basic Rules
  280. You are a powerful conversational AI trained by Cohere to help people. You are augmented by a number of tools, and your job is to use and consume the output of these tools to best help the user. You will see a conversation history between yourself and a user, ending with an utterance from the user. You will then see a specific instruction instructing you what kind of response to generate. When you answer the user's requests, you cite your sources in your answers, according to those instructions.
  281. # User Preamble
  282. ## Task and Context
  283. You help people answer their questions and other requests interactively. You will be asked a very wide array of requests on all kinds of topics. You will be equipped with a wide range of search engines or similar tools to help you, which you use to research your answer. You should focus on serving the user's needs as best you can, which will be wide-ranging.
  284. ## Style Guide
  285. Unless the user asks for a different style of answer, you should answer in full sentences, using proper grammar and spelling.
  286. ## Available Tools
  287. Here is a list of tools that you have available to you:
  288. \\`\\`\\`python
  289. def internet_search(query: str) -> List[Dict]:
  290. \"\"\"Returns a list of relevant document snippets for a textual query retrieved from the internet
  291. Args:
  292. query (str): Query to search the internet with
  293. \"\"\"
  294. pass
  295. \\`\\`\\`
  296. \\`\\`\\`python
  297. def directly_answer() -> List[Dict]:
  298. \"\"\"Calls a standard (un-augmented) AI chatbot to generate a response given the conversation history
  299. \"\"\"
  300. pass
  301. \\`\\`\\`<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|USER_TOKEN|>Whats the biggest penguin in the world?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>Write 'Action:' followed by a json-formatted list of actions that you want to perform in order to produce a good response to the user's last input. You can use any of the supplied tools any number of times, but you should aim to execute the minimum number of necessary actions for the input. You should use the `directly-answer` tool if calling the other tools is unnecessary. The list of actions you want to call should be formatted as a list of json objects, for example:
  302. \\`\\`\\`json
  303. [
  304. {
  305. "tool_name": title of the tool in the specification,
  306. "parameters": a dict of parameters to input into the tool as they are defined in the specs, or {} if it takes no parameters
  307. }
  308. ]\\`\\`\\`<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>
  309. ```
  310. >> inputs = tokenizer.encode(prompt, add_special_tokens=False, return_tensors='pt')
  311. >> outputs = model.generate(inputs, max_new_tokens=128)
  312. >> print(tokenizer.decode(outputs[0]))
  313. Action: ```json
  314. [
  315. {
  316. "tool_name": "internet_search",
  317. "parameters": {
  318. "query": "biggest penguin in the world"
  319. }
  320. }
  321. ]
  322. ```
  323. """
  324. return self.apply_chat_template(
  325. conversation,
  326. chat_template="tool_use",
  327. tools=tools,
  328. **kwargs,
  329. )
  330. def apply_grounded_generation_template(
  331. self,
  332. conversation: Union[List[Dict[str, str]]],
  333. documents: List[Dict],
  334. citation_mode: Literal["fast", "accurate"] = "accurate",
  335. **kwargs,
  336. ) -> Union[str, List[int]]:
  337. """Create a Command-R grounded generation (aka RAG) prompt.
  338. Once rendered, the prompt instructs the model to generate a response with citations in, based on supplied documents.
  339. Conceptually, this works in the same way as `apply_chat_format`, but takes additional `documents`
  340. and parameter `citation_mode` parameters.
  341. Converts a list of dictionaries with `"role"` and `"content"` keys and a list of
  342. documents for the model to ground its response on into a prompt string, or a list of token ids.
  343. This method will use the tokenizer's `grounded_generation_template` template specified at the class level.
  344. You can override the default template using the `grounded_generation_template` kwarg but the quality of your results may decrease.
  345. Args:
  346. conversation (Union[List[Dict[str, str]]]): A list of dicts
  347. with "role" and "content" keys, representing the chat history so far.
  348. documents (List[Dict[str, str]): A list of dicts, representing documents or tool outputs to ground your
  349. generation on. A document is a semistructured dict, wiht a string to string mapping. Common fields are
  350. `url`, `title`, `snippet` etc but should be descriptive of the key. They will get rendered into the prompt.
  351. citation_mode: either "accurate" (prompt the model to generate an answer first, then rewrite it with citation
  352. spans in) or "fast", where the prompt instructs the model to generate an answer with citations in directly.
  353. The former has higher quality citations, the latter requires fewer tokens to be generated.
  354. add_generation_prompt (bool, *optional*): Whether to end the prompt with the token(s) that indicate
  355. the start of an assistant message. This is useful when you want to generate a response from the model.
  356. Note that this argument will be passed to the chat template, and so it must be supported in the
  357. template for this argument to have any effect.
  358. tokenize (`bool`, defaults to `True`):
  359. Whether to tokenize the output. If `False`, the output will be a string.
  360. padding (`bool`, defaults to `False`):
  361. Whether to pad sequences to the maximum length. Has no effect if tokenize is `False`.
  362. truncation (`bool`, defaults to `False`):
  363. Whether to truncate sequences at the maximum length. Has no effect if tokenize is `False`.
  364. max_length (`int`, *optional*):
  365. Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is `False`. If
  366. not specified, the tokenizer's `max_length` attribute will be used as a default.
  367. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  368. If set, will return tensors of a particular framework. Has no effect if tokenize is `False`. Acceptable
  369. values are:
  370. - `'tf'`: Return TensorFlow `tf.Tensor` objects.
  371. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  372. - `'np'`: Return NumPy `np.ndarray` objects.
  373. - `'jax'`: Return JAX `jnp.ndarray` objects.
  374. return_dict (`bool`, *optional*, defaults to `False`):
  375. Whether to return a dictionary with named outputs. Has no effect if tokenize is `False`.
  376. **tokenizer_kwargs: Additional kwargs to pass to the tokenizer.
  377. Returns:
  378. `str`: A rendered prompt string.
  379. or if tokenize=True:
  380. `List[int]`: A list of token ids representing the tokenized chat so far, including control tokens. This
  381. output is ready to pass to the model, either directly or via methods like `generate()`.
  382. Examples:
  383. ```python
  384. >> tokenizer = CohereTokenizerFast.from_pretrained('CohereForAI/c4ai-command-r-v01')
  385. >> # define documents:
  386. >> documents = [
  387. { "title": "Tall penguins", "text": "Emperor penguins are the tallest." },
  388. { "title": "Penguin habitats", "text": "Emperor penguins only live in Antarctica."}
  389. ]
  390. >> # define a conversation:
  391. >> conversation = [
  392. {"role": "user", "content": "Whats the biggest penguin in the world?"}
  393. ]
  394. >> # render the prompt, ready for user to inspect, or for input into the model:
  395. >> grounded_generation_prompt = tokenizer.apply_grounded_generation_template(conversation, documents=documents, tokenize=False, add_generation_prompt=True)
  396. >> print(grounded_generation_prompt)
  397. <BOS_TOKEN><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># Safety Preamble
  398. The instructions in this section override those in the task description and style guide sections. Don't answer questions that are harmful or immoral.
  399. ## Basic Rules
  400. You are a powerful conversational AI trained by Cohere to help people. You are augmented by a number of tools, and your job is to use and consume the output of these tools to best help the user. You will see a conversation history between yourself and a user, ending with an utterance from the user. You will then see a specific instruction instructing you what kind of response to generate. When you answer the user's requests, you cite your sources in your answers, according to those instructions.
  401. # User Preamble
  402. ## Task and Context
  403. You help people answer their questions and other requests interactively. You will be asked a very wide array of requests on all kinds of topics. You will be equipped with a wide range of search engines or similar tools to help you, which you use to research your answer. You should focus on serving the user's needs as best you can, which will be wide-ranging.
  404. ## Style Guide
  405. Unless the user asks for a different style of answer, you should answer in full sentences, using proper grammar and spelling.<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|USER_TOKEN|>Whats the biggest penguin in the world?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|><results>
  406. Document: 0
  407. title: Tall penguins
  408. text: Emperor penguins are the tallest.
  409. Document: 1
  410. title: Penguin habitats
  411. text: Emperor penguins only live in Antarctica.
  412. </results><|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>Carefully perform the following instructions, in order, starting each with a new line.
  413. Firstly, Decide which of the retrieved documents are relevant to the user's last input by writing 'Relevant Documents:' followed by comma-separated list of document numbers. If none are relevant, you should instead write 'None'.
  414. Secondly, Decide which of the retrieved documents contain facts that should be cited in a good answer to the user's last input by writing 'Cited Documents:' followed a comma-separated list of document numbers. If you dont want to cite any of them, you should instead write 'None'.
  415. Thirdly, Write 'Answer:' followed by a response to the user's last input in high quality natural english. Use the retrieved documents to help you. Do not insert any citations or grounding markup.
  416. Finally, Write 'Grounded answer:' followed by a response to the user's last input in high quality natural english. Use the symbols <co: doc> and </co: doc> to indicate when a fact comes from a document in the search result, e.g <co: 0>my fact</co: 0> for a fact from document 0.<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>'''
  417. ```
  418. >> inputs = tokenizer.encode(prompt, add_special_tokens=False, return_tensors='pt')
  419. >> outputs = model.generate(inputs, max_new_tokens=128)
  420. >> print(tokenizer.decode(outputs[0]))
  421. Relevant Documents: 0,1
  422. Cited Documents: 0,1
  423. Answer: The Emperor Penguin is the tallest or biggest penguin in the world. It is a bird that lives only in Antarctica and grows to a height of around 122 centimetres.
  424. Grounded answer: The <co: 0>Emperor Penguin</co: 0> is the <co: 0>tallest</co: 0> or biggest penguin in the world. It is a bird that <co: 1>lives only in Antarctica</co: 1> and <co: 0>grows to a height of around 122 centimetres.</co: 0>
  425. """
  426. return self.apply_chat_template(
  427. conversation,
  428. chat_template="rag",
  429. documents=documents,
  430. citation_mode=citation_mode,
  431. **kwargs,
  432. )
  433. # TODO ArthurZ let's rely on the template processor instead, refactor all fast tokenizers
  434. def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
  435. bos_token_id = [self.bos_token_id] if self.add_bos_token else []
  436. eos_token_id = [self.eos_token_id] if self.add_eos_token else []
  437. output = bos_token_id + token_ids_0 + eos_token_id
  438. if token_ids_1 is not None:
  439. output = output + bos_token_id + token_ids_1 + eos_token_id
  440. return output