text_generation.py 25 KB

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