text_generation.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. import enum
  2. import itertools
  3. import types
  4. from typing import Any, overload
  5. from ..generation import GenerationConfig
  6. from ..utils import ModelOutput, add_end_docstrings, is_tf_available, is_torch_available
  7. from .base import Pipeline, build_pipeline_init_args
  8. if is_torch_available():
  9. import torch
  10. from ..models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
  11. from .pt_utils import KeyDataset
  12. if is_tf_available():
  13. import tensorflow as tf
  14. from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
  15. ChatType = list[dict[str, str]]
  16. class ReturnType(enum.Enum):
  17. TENSORS = 0
  18. NEW_TEXT = 1
  19. FULL_TEXT = 2
  20. class Chat:
  21. """This class is intended to just be used internally in this pipeline and not exposed to users. We convert chats
  22. to this format because the rest of the pipeline code tends to assume that lists of messages are
  23. actually a batch of samples rather than messages in the same conversation."""
  24. def __init__(self, messages: dict):
  25. for message in messages:
  26. if not ("role" in message and "content" in message):
  27. raise ValueError("When passing chat dicts as input, each dict must have a 'role' and 'content' key.")
  28. self.messages = messages
  29. @add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
  30. class TextGenerationPipeline(Pipeline):
  31. """
  32. Language generation pipeline using any `ModelWithLMHead` or `ModelForCausalLM`. This pipeline predicts the words
  33. that will follow a specified text prompt. When the underlying model is a conversational model, it can also accept
  34. one or more chats, in which case the pipeline will operate in chat mode and will continue the chat(s) by adding
  35. its response(s). Each chat takes the form of a list of dicts, where each dict contains "role" and "content" keys.
  36. Unless the model you're using explicitly sets these generation parameters in its configuration files
  37. (`generation_config.json`), the following default values will be used:
  38. - max_new_tokens: 256
  39. - do_sample: True
  40. - temperature: 0.7
  41. Examples:
  42. ```python
  43. >>> from transformers import pipeline
  44. >>> generator = pipeline(model="openai-community/gpt2")
  45. >>> generator("I can't believe you did such a ", do_sample=False)
  46. [{'generated_text': "I can't believe you did such a icky thing to me. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I"}]
  47. >>> # These parameters will return suggestions, and only the newly created text making it easier for prompting suggestions.
  48. >>> outputs = generator("My tart needs some", num_return_sequences=4, return_full_text=False)
  49. ```
  50. ```python
  51. >>> from transformers import pipeline
  52. >>> generator = pipeline(model="HuggingFaceH4/zephyr-7b-beta")
  53. >>> # Zephyr-beta is a conversational model, so let's pass it a chat instead of a single string
  54. >>> generator([{"role": "user", "content": "What is the capital of France? Answer in one word."}], do_sample=False, max_new_tokens=2)
  55. [{'generated_text': [{'role': 'user', 'content': 'What is the capital of France? Answer in one word.'}, {'role': 'assistant', 'content': 'Paris'}]}]
  56. ```
  57. Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial). You can pass text
  58. generation parameters to this pipeline to control stopping criteria, decoding strategy, and more. Learn more about
  59. text generation parameters in [Text generation strategies](../generation_strategies) and [Text
  60. generation](text_generation).
  61. This language generation pipeline can currently be loaded from [`pipeline`] using the following task identifier:
  62. `"text-generation"`.
  63. The models that this pipeline can use are models that have been trained with an autoregressive language modeling
  64. objective. See the list of available [text completion models](https://huggingface.co/models?filter=text-generation)
  65. and the list of [conversational models](https://huggingface.co/models?other=conversational)
  66. on [huggingface.co/models].
  67. """
  68. # Prefix text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
  69. # in https://github.com/rusiaaman/XLNet-gen#methodology
  70. # and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
  71. XL_PREFIX = """
  72. In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The
  73. voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western
  74. Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision
  75. and denounces one of the men as a horse thief. Although his father initially slaps him for making such an
  76. accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
  77. the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,
  78. begging for his blessing. <eod> </s> <eos>
  79. """
  80. _pipeline_calls_generate = True
  81. _load_processor = False
  82. _load_image_processor = False
  83. _load_feature_extractor = False
  84. _load_tokenizer = True
  85. # Make sure the docstring is updated when the default generation config is changed
  86. _default_generation_config = GenerationConfig(
  87. max_new_tokens=256,
  88. do_sample=True, # free-form text generation often uses sampling
  89. temperature=0.7,
  90. )
  91. def __init__(self, *args, **kwargs):
  92. super().__init__(*args, **kwargs)
  93. self.check_model_type(
  94. TF_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES if self.framework == "tf" else MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
  95. )
  96. if "prefix" not in self._preprocess_params:
  97. # This is very specific. The logic is quite complex and needs to be done
  98. # as a "default".
  99. # It also defines both some preprocess_kwargs and generate_kwargs
  100. # which is why we cannot put them in their respective methods.
  101. prefix = None
  102. if self.prefix is not None:
  103. prefix = self.prefix
  104. if prefix is None and self.model.__class__.__name__ in [
  105. "XLNetLMHeadModel",
  106. "TransfoXLLMHeadModel",
  107. "TFXLNetLMHeadModel",
  108. "TFTransfoXLLMHeadModel",
  109. ]:
  110. # For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
  111. prefix = self.XL_PREFIX
  112. if prefix is not None:
  113. # Recalculate some generate_kwargs linked to prefix.
  114. preprocess_params, forward_params, _ = self._sanitize_parameters(prefix=prefix, **self._forward_params)
  115. self._preprocess_params = {**self._preprocess_params, **preprocess_params}
  116. self._forward_params = {**self._forward_params, **forward_params}
  117. def _sanitize_parameters(
  118. self,
  119. return_full_text=None,
  120. return_tensors=None,
  121. return_text=None,
  122. return_type=None,
  123. clean_up_tokenization_spaces=None,
  124. prefix=None,
  125. handle_long_generation=None,
  126. stop_sequence=None,
  127. truncation=None,
  128. max_length=None,
  129. continue_final_message=None,
  130. skip_special_tokens=None,
  131. tokenizer_encode_kwargs=None,
  132. **generate_kwargs,
  133. ):
  134. # preprocess kwargs
  135. preprocess_params = {}
  136. add_special_tokens = False
  137. if "add_special_tokens" in generate_kwargs:
  138. add_special_tokens = preprocess_params["add_special_tokens"] = generate_kwargs.pop("add_special_tokens")
  139. if "padding" in generate_kwargs:
  140. preprocess_params["padding"] = generate_kwargs.pop("padding")
  141. if truncation is not None:
  142. preprocess_params["truncation"] = truncation
  143. if max_length is not None:
  144. preprocess_params["max_length"] = max_length
  145. generate_kwargs["max_length"] = max_length
  146. if prefix is not None:
  147. preprocess_params["prefix"] = prefix
  148. if prefix:
  149. prefix_inputs = self.tokenizer(
  150. prefix, padding=False, add_special_tokens=add_special_tokens, return_tensors=self.framework
  151. )
  152. generate_kwargs["prefix_length"] = prefix_inputs["input_ids"].shape[-1]
  153. if handle_long_generation is not None:
  154. if handle_long_generation != "hole":
  155. raise ValueError(
  156. f"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected"
  157. " [None, 'hole']"
  158. )
  159. preprocess_params["handle_long_generation"] = handle_long_generation
  160. if continue_final_message is not None:
  161. preprocess_params["continue_final_message"] = continue_final_message
  162. if tokenizer_encode_kwargs is not None:
  163. preprocess_params["tokenizer_encode_kwargs"] = tokenizer_encode_kwargs
  164. preprocess_params.update(generate_kwargs)
  165. # forward kwargs
  166. if stop_sequence is not None:
  167. stop_sequence_ids = self.tokenizer.encode(stop_sequence, add_special_tokens=False)
  168. generate_kwargs["eos_token_id"] = stop_sequence_ids
  169. forward_params = generate_kwargs
  170. if self.assistant_model is not None:
  171. forward_params["assistant_model"] = self.assistant_model
  172. if self.assistant_tokenizer is not None:
  173. forward_params["tokenizer"] = self.tokenizer
  174. forward_params["assistant_tokenizer"] = self.assistant_tokenizer
  175. # postprocess kwargs
  176. postprocess_params = {}
  177. if return_full_text is not None and return_type is None:
  178. if return_text is not None:
  179. raise ValueError("`return_text` is mutually exclusive with `return_full_text`")
  180. if return_tensors is not None:
  181. raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`")
  182. return_type = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
  183. if return_tensors is not None and return_type is None:
  184. if return_text is not None:
  185. raise ValueError("`return_text` is mutually exclusive with `return_tensors`")
  186. return_type = ReturnType.TENSORS
  187. if return_type is not None:
  188. postprocess_params["return_type"] = return_type
  189. if clean_up_tokenization_spaces is not None:
  190. postprocess_params["clean_up_tokenization_spaces"] = clean_up_tokenization_spaces
  191. if continue_final_message is not None:
  192. postprocess_params["continue_final_message"] = continue_final_message
  193. if skip_special_tokens is not None:
  194. postprocess_params["skip_special_tokens"] = skip_special_tokens
  195. return preprocess_params, forward_params, postprocess_params
  196. # overriding _parse_and_tokenize to allow for unusual language-modeling tokenizer arguments
  197. def _parse_and_tokenize(self, *args, **kwargs):
  198. """
  199. Parse arguments and tokenize
  200. """
  201. # Parse arguments
  202. if self.model.__class__.__name__ == "TransfoXLLMHeadModel":
  203. kwargs.update({"add_space_before_punct_symbol": True})
  204. return super()._parse_and_tokenize(*args, **kwargs)
  205. @overload
  206. def __call__(self, text_inputs: str, **kwargs: Any) -> list[dict[str, str]]: ...
  207. @overload
  208. def __call__(self, text_inputs: list[str], **kwargs: Any) -> list[list[dict[str, str]]]: ...
  209. @overload
  210. def __call__(self, text_inputs: ChatType, **kwargs: Any) -> list[dict[str, ChatType]]: ...
  211. @overload
  212. def __call__(self, text_inputs: list[ChatType], **kwargs: Any) -> list[list[dict[str, ChatType]]]: ...
  213. def __call__(self, text_inputs, **kwargs):
  214. """
  215. Complete the prompt(s) given as inputs.
  216. Args:
  217. text_inputs (`str`, `list[str]`, list[dict[str, str]], or `list[list[dict[str, str]]]`):
  218. One or several prompts (or one list of prompts) to complete. If strings or a list of string are
  219. passed, this pipeline will continue each prompt. Alternatively, a "chat", in the form of a list
  220. of dicts with "role" and "content" keys, can be passed, or a list of such chats. When chats are passed,
  221. the model's chat template will be used to format them before passing them to the model.
  222. return_tensors (`bool`, *optional*, defaults to `False`):
  223. Returns the tensors of predictions (as token indices) in the outputs. If set to
  224. `True`, the decoded text is not returned.
  225. return_text (`bool`, *optional*):
  226. Returns the decoded texts in the outputs.
  227. return_full_text (`bool`, *optional*, defaults to `True`):
  228. If set to `False` only added text is returned, otherwise the full text is returned. Cannot be
  229. specified at the same time as `return_text`.
  230. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
  231. Whether or not to clean up the potential extra spaces in the text output.
  232. continue_final_message( `bool`, *optional*): This indicates that you want the model to continue the
  233. last message in the input chat rather than starting a new one, allowing you to "prefill" its response.
  234. By default this is `True` when the final message in the input chat has the `assistant` role and
  235. `False` otherwise, but you can manually override that behaviour by setting this flag.
  236. prefix (`str`, *optional*):
  237. Prefix added to prompt.
  238. handle_long_generation (`str`, *optional*):
  239. By default, this pipelines does not handle long generation (ones that exceed in one form or the other
  240. the model maximum length). There is no perfect way to address this (more info
  241. :https://github.com/huggingface/transformers/issues/14033#issuecomment-948385227). This provides common
  242. strategies to work around that problem depending on your use case.
  243. - `None` : default strategy where nothing in particular happens
  244. - `"hole"`: Truncates left of input, and leaves a gap wide enough to let generation happen (might
  245. truncate a lot of the prompt and not suitable when generation exceed the model capacity)
  246. tokenizer_encode_kwargs (`dict`, *optional*):
  247. Additional keyword arguments to pass along to the encoding step of the tokenizer. If the text input is
  248. a chat, it is passed to `apply_chat_template`. Otherwise, it is passed to `__call__`.
  249. generate_kwargs (`dict`, *optional*):
  250. Additional keyword arguments to pass along to the generate method of the model (see the generate method
  251. corresponding to your framework [here](./text_generation)).
  252. Return:
  253. A list or a list of lists of `dict`: Returns one of the following dictionaries (cannot return a combination
  254. of both `generated_text` and `generated_token_ids`):
  255. - **generated_text** (`str`, present when `return_text=True`) -- The generated text.
  256. - **generated_token_ids** (`torch.Tensor` or `tf.Tensor`, present when `return_tensors=True`) -- The token
  257. ids of the generated text.
  258. """
  259. if isinstance(
  260. text_inputs,
  261. (list, tuple, types.GeneratorType, KeyDataset)
  262. if is_torch_available()
  263. else (list, tuple, types.GeneratorType),
  264. ):
  265. if isinstance(text_inputs, types.GeneratorType):
  266. text_inputs, _ = itertools.tee(text_inputs)
  267. text_inputs, first_item = (x for x in text_inputs), next(_)
  268. else:
  269. first_item = text_inputs[0]
  270. if isinstance(first_item, (list, tuple, dict)):
  271. # We have one or more prompts in list-of-dicts format, so this is chat mode
  272. if isinstance(first_item, dict):
  273. return super().__call__(Chat(text_inputs), **kwargs)
  274. else:
  275. chats = (Chat(chat) for chat in text_inputs) # 🐈 🐈 🐈
  276. if isinstance(text_inputs, types.GeneratorType):
  277. return super().__call__(chats, **kwargs)
  278. else:
  279. return super().__call__(list(chats), **kwargs)
  280. return super().__call__(text_inputs, **kwargs)
  281. def preprocess(
  282. self,
  283. prompt_text,
  284. prefix="",
  285. handle_long_generation=None,
  286. add_special_tokens=None,
  287. truncation=None,
  288. padding=None,
  289. max_length=None,
  290. continue_final_message=None,
  291. tokenizer_encode_kwargs=None,
  292. **generate_kwargs,
  293. ):
  294. # Only set non-None tokenizer kwargs, so as to rely on the tokenizer's defaults
  295. tokenizer_kwargs = {
  296. "add_special_tokens": add_special_tokens,
  297. "truncation": truncation,
  298. "padding": padding,
  299. "max_length": max_length, # NOTE: `max_length` is also a `generate` arg. Use `tokenizer_encode_kwargs` to avoid a name clash
  300. }
  301. tokenizer_kwargs = {key: value for key, value in tokenizer_kwargs.items() if value is not None}
  302. tokenizer_kwargs.update(tokenizer_encode_kwargs or {})
  303. if isinstance(prompt_text, Chat):
  304. tokenizer_kwargs.pop("add_special_tokens", None) # ignore add_special_tokens on chats
  305. # If the user passes a chat that ends in an assistant message, we treat it as a prefill by default
  306. # because very few models support multiple separate, consecutive assistant messages
  307. if continue_final_message is None:
  308. continue_final_message = prompt_text.messages[-1]["role"] == "assistant"
  309. inputs = self.tokenizer.apply_chat_template(
  310. prompt_text.messages,
  311. add_generation_prompt=not continue_final_message,
  312. continue_final_message=continue_final_message,
  313. return_dict=True,
  314. return_tensors=self.framework,
  315. **tokenizer_kwargs,
  316. )
  317. else:
  318. inputs = self.tokenizer(prefix + prompt_text, return_tensors=self.framework, **tokenizer_kwargs)
  319. inputs["prompt_text"] = prompt_text
  320. if handle_long_generation == "hole":
  321. cur_len = inputs["input_ids"].shape[-1]
  322. if "max_new_tokens" in generate_kwargs:
  323. new_tokens = generate_kwargs["max_new_tokens"]
  324. else:
  325. new_tokens = generate_kwargs.get("max_length", self.generation_config.max_length) - cur_len
  326. if new_tokens < 0:
  327. raise ValueError("We cannot infer how many new tokens are expected")
  328. if cur_len + new_tokens > self.tokenizer.model_max_length:
  329. keep_length = self.tokenizer.model_max_length - new_tokens
  330. if keep_length <= 0:
  331. raise ValueError(
  332. "We cannot use `hole` to handle this generation the number of desired tokens exceeds the"
  333. " models max length"
  334. )
  335. inputs["input_ids"] = inputs["input_ids"][:, -keep_length:]
  336. if "attention_mask" in inputs:
  337. inputs["attention_mask"] = inputs["attention_mask"][:, -keep_length:]
  338. return inputs
  339. def _forward(self, model_inputs, **generate_kwargs):
  340. input_ids = model_inputs["input_ids"]
  341. attention_mask = model_inputs.get("attention_mask", None)
  342. # Allow empty prompts
  343. if input_ids.shape[1] == 0:
  344. input_ids = None
  345. attention_mask = None
  346. in_b = 1
  347. else:
  348. in_b = input_ids.shape[0]
  349. prompt_text = model_inputs.pop("prompt_text")
  350. # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
  351. # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
  352. prefix_length = generate_kwargs.pop("prefix_length", 0)
  353. if prefix_length > 0:
  354. has_max_new_tokens = "max_new_tokens" in generate_kwargs or (
  355. "generation_config" in generate_kwargs
  356. and generate_kwargs["generation_config"].max_new_tokens is not None
  357. )
  358. if not has_max_new_tokens:
  359. generate_kwargs["max_length"] = generate_kwargs.get("max_length") or self.generation_config.max_length
  360. generate_kwargs["max_length"] += prefix_length
  361. has_min_new_tokens = "min_new_tokens" in generate_kwargs or (
  362. "generation_config" in generate_kwargs
  363. and generate_kwargs["generation_config"].min_new_tokens is not None
  364. )
  365. if not has_min_new_tokens and "min_length" in generate_kwargs:
  366. generate_kwargs["min_length"] += prefix_length
  367. # User-defined `generation_config` passed to the pipeline call take precedence
  368. if "generation_config" not in generate_kwargs:
  369. generate_kwargs["generation_config"] = self.generation_config
  370. output = self.model.generate(input_ids=input_ids, attention_mask=attention_mask, **generate_kwargs)
  371. if isinstance(output, ModelOutput):
  372. generated_sequence = output.sequences
  373. other_outputs = {k: v for k, v in output.items() if k not in {"sequences", "past_key_values"}}
  374. out_b = generated_sequence.shape[0]
  375. if self.framework == "pt":
  376. for key, value in other_outputs.items():
  377. if isinstance(value, torch.Tensor) and value.shape[0] == out_b:
  378. other_outputs[key] = value.reshape(in_b, out_b // in_b, *value.shape[1:])
  379. if isinstance(value, tuple) and len(value[0]) == out_b:
  380. value = torch.stack(value).swapaxes(0, 1)
  381. other_outputs[key] = value
  382. elif self.framework == "tf":
  383. for key, value in other_outputs.items():
  384. if isinstance(value, tf.Tensor) and value.shape[0] == out_b:
  385. other_outputs[key] = tf.reshape(value, (in_b, out_b // in_b, *value.shape[1:]))
  386. if isinstance(value, tuple) and len(value[0]) == out_b:
  387. value = tf.stack(value).swapaxes(0, 1)
  388. other_outputs[key] = value
  389. else:
  390. generated_sequence = output
  391. other_outputs = {}
  392. out_b = generated_sequence.shape[0]
  393. if self.framework == "pt":
  394. generated_sequence = generated_sequence.reshape(in_b, out_b // in_b, *generated_sequence.shape[1:])
  395. elif self.framework == "tf":
  396. generated_sequence = tf.reshape(generated_sequence, (in_b, out_b // in_b, *generated_sequence.shape[1:]))
  397. model_outputs = {
  398. "generated_sequence": generated_sequence,
  399. "input_ids": input_ids,
  400. "prompt_text": prompt_text,
  401. }
  402. if other_outputs:
  403. model_outputs.update({"additional_outputs": other_outputs})
  404. return model_outputs
  405. def postprocess(
  406. self,
  407. model_outputs,
  408. return_type=ReturnType.FULL_TEXT,
  409. clean_up_tokenization_spaces=True,
  410. continue_final_message=None,
  411. skip_special_tokens=None,
  412. ):
  413. generated_sequence = model_outputs["generated_sequence"][0]
  414. input_ids = model_outputs["input_ids"]
  415. prompt_text = model_outputs["prompt_text"]
  416. generated_sequence = generated_sequence.numpy().tolist()
  417. records = []
  418. other_outputs = model_outputs.get("additional_outputs", {})
  419. split_keys = {}
  420. if other_outputs:
  421. if self.framework == "pt":
  422. for k, v in other_outputs.items():
  423. if isinstance(v, torch.Tensor) and v.shape[0] == len(generated_sequence):
  424. split_keys[k] = v.numpy().tolist()
  425. elif self.framework == "tf":
  426. for k, v in other_outputs.items():
  427. if isinstance(v, tf.Tensor) and v.shape[0] == len(generated_sequence):
  428. split_keys[k] = v.numpy().tolist()
  429. skip_special_tokens = skip_special_tokens if skip_special_tokens is not None else True
  430. for idx, sequence in enumerate(generated_sequence):
  431. if return_type == ReturnType.TENSORS:
  432. record = {"generated_token_ids": sequence}
  433. elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
  434. # Decode text
  435. text = self.tokenizer.decode(
  436. sequence,
  437. skip_special_tokens=skip_special_tokens,
  438. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  439. )
  440. # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
  441. if input_ids is None:
  442. prompt_length = 0
  443. else:
  444. prompt_length = len(
  445. self.tokenizer.decode(
  446. input_ids[0],
  447. skip_special_tokens=skip_special_tokens,
  448. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  449. )
  450. )
  451. all_text = text[prompt_length:]
  452. if return_type == ReturnType.FULL_TEXT:
  453. if isinstance(prompt_text, str):
  454. all_text = prompt_text + all_text
  455. elif isinstance(prompt_text, Chat):
  456. if continue_final_message is None:
  457. # If the user passes a chat ending in an assistant message, we treat it as a prefill by
  458. # default because very few models support multiple separate, consecutive assistant messages
  459. continue_final_message = prompt_text.messages[-1]["role"] == "assistant"
  460. if continue_final_message:
  461. # With assistant prefill, concat onto the end of the last message
  462. all_text = list(prompt_text.messages)[:-1] + [
  463. {
  464. "role": prompt_text.messages[-1]["role"],
  465. "content": prompt_text.messages[-1]["content"] + all_text,
  466. }
  467. ]
  468. else:
  469. # When we're not starting from a prefill, the output is a new assistant message
  470. all_text = list(prompt_text.messages) + [{"role": "assistant", "content": all_text}]
  471. record = {"generated_text": all_text}
  472. for key, values in split_keys.items():
  473. record[key] = values[idx]
  474. records.append(record)
  475. return records