



'''simple docstring'''
import logging
import os
from typing import Dict, List, Optional, Union

import torch
import torch.nn as nn

from accelerate.utils.imports import (
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_bnb_available,
)

from ..big_modeling import dispatch_model, init_empty_weights
from .dataclasses import BnbQuantizationConfig
from .modeling import (
    find_tied_parameters,
    get_balanced_memory,
    infer_auto_device_map,
    load_checkpoint_in_model,
    offload_weight,
    set_module_tensor_to_device,
)


if is_bnb_available():
					import bitsandbytes as bnb

from copy import deepcopy


snake_case_ :	Optional[Any]         =  logging.getLogger(__name__)






def A__    (     UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_ = None  ,  UpperCAmelCase_ = None  ,  UpperCAmelCase_ = None  ,  UpperCAmelCase_ = None  ,  UpperCAmelCase_ = None  ,  UpperCAmelCase_ = False  ,  ):
						_UpperCamelCase					:		Optional[Any] 				=   bnb_quantization_config.load_in_abit
						_UpperCamelCase					:		Union[str, Any] 				=   bnb_quantization_config.load_in_abit

						if load_in_abit and not is_abit_bnb_available():
												raise ImportError(
												    'You have a version of `bitsandbytes` that is not compatible with 8bit quantization,'
												    ' make sure you have the latest version of `bitsandbytes` installed.'							)
						if load_in_abit and not is_abit_bnb_available():
												raise ValueError(
												    'You have a version of `bitsandbytes` that is not compatible with 4bit quantization,'
												    'make sure you have the latest version of `bitsandbytes` installed.'							)

						_UpperCamelCase					:		str 				=   []
						# custom device map
						if isinstance(_A  ,  _A							) and len(device_map.keys()							) > 1:
												_UpperCamelCase					:		Union[str, Any] 				=   [key for key, value in device_map.items() if value in ['disk', 'cpu']]

						# We keep some modules such as the lm_head in their original dtype for numerical stability reasons
						if bnb_quantization_config.skip_modules is None:
												_UpperCamelCase					:		Union[str, Any] 				=   get_keys_to_not_convert(_A							)

						# add cpu modules to skip modules only for 4-bit modules
						if load_in_abit:
												bnb_quantization_config.skip_modules.extend(_A							)
						_UpperCamelCase					:		Dict 				=   bnb_quantization_config.skip_modules

						# We add the modules we want to keep in full precision
						if bnb_quantization_config.keep_in_fpaa_modules is None:
												_UpperCamelCase					:		Dict 				=   []
						_UpperCamelCase					:		int 				=   bnb_quantization_config.keep_in_fpaa_modules
						modules_to_not_convert.extend(_A							)

						# compatibility with peft
						_UpperCamelCase					:		Tuple 				=   load_in_abit
						_UpperCamelCase					:		Optional[Any] 				=   load_in_abit

						_UpperCamelCase					:		int 				=   get_parameter_device(_A							)
						if model_device.type != "meta":
												# quantization of an already loaded model
												logger.warning(
												    'It is not recommended to quantize a loaded model. '
												    'The model should be instantiated under the `init_empty_weights` context manager.'							)
												_UpperCamelCase					:		str 				=   replace_with_bnb_layers(_A  ,  _A  ,  modules_to_not_convert=_A							)
												# convert param to the right dtype
												_UpperCamelCase					:		Dict 				=   bnb_quantization_config.torch_dtype
												for name, param in model.state_dict().items():
																		if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules							):
																								param.to(torch.floataa							)
																								if param.dtype != torch.floataa:
																														_UpperCamelCase					:		List[str] 				=   name.replace('.weight'  ,  ''							).replace('.bias'  ,  ''							)
																														_UpperCamelCase					:		str 				=   getattr(_A  ,  _A  ,  _A							)
																														if param is not None:
																																				param.to(torch.floataa							)
																		elif torch.is_floating_point(_A							):
																								param.to(_A							)
												if model_device.type == "cuda":
																		# move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
																		model.cuda(torch.cuda.current_device()							)
																		torch.cuda.empty_cache()
												elif torch.cuda.is_available():
																		model.to(torch.cuda.current_device()							)
												else:
																		raise RuntimeError('No GPU found. A GPU is needed for quantization.'							)
												logger.info(
												    f'The model device type is {model_device.type}. However, cuda is needed for quantization.'
												    'We move the model to cuda.'							)
												return model

						elif weights_location is None:
												raise RuntimeError(
												    f'`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} '							)

						else:
												with init_empty_weights():
																		_UpperCamelCase					:		List[str] 				=   replace_with_bnb_layers(
																		    _A  ,  _A  ,  modules_to_not_convert=_A							)

												_UpperCamelCase					:		Any 				=   get_quantized_model_device_map(
												    _A  ,  _A  ,  _A  ,  max_memory=_A  ,  no_split_module_classes=_A  ,  )
												if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
																		_UpperCamelCase					:		str 				=   True

												_UpperCamelCase					:		Optional[Any] 				=   any(x in list(device_map.values()							) for x in ['cpu', 'disk']							)

												load_checkpoint_in_model(
												    _A  ,  _A  ,  _A  ,  dtype=bnb_quantization_config.torch_dtype  ,  offload_folder=_A  ,  offload_state_dict=_A  ,  keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules  ,  offload_abit_bnb=load_in_abit and offload  ,  )
												return dispatch_model(_A  ,  device_map=_A  ,  offload_dir=_A							)






def A__    (     UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_=None  ,  UpperCAmelCase_=None  ,  UpperCAmelCase_=None							):


						if device_map is None:
												if torch.cuda.is_available():
																		_UpperCamelCase					:		Optional[Any] 				=   {'': torch.cuda.current_device()}
												else:
																		raise RuntimeError('No GPU found. A GPU is needed for quantization.'							)
												logger.info('The device_map was not initialized.' 'Setting device_map to `{\'\':torch.cuda.current_device()}`.'							)

						if isinstance(_A  ,  _A							):
												if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
																		raise ValueError(
																		    'If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or '
																		    '\'sequential\'.'							)

												_UpperCamelCase					:		Any 				=   {}
												special_dtypes.update(
												    {
												        name: bnb_quantization_config.torch_dtype
												        for name, _ in model.named_parameters()
												        if any(m in name for m in bnb_quantization_config.skip_modules							)
												    }							)
												special_dtypes.update(
												    {
												        name: torch.floataa
												        for name, _ in model.named_parameters()
												        if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules							)
												    }							)

												_UpperCamelCase					:		Union[str, Any] 				=   {}
												_UpperCamelCase					:		Optional[Any] 				=   special_dtypes
												_UpperCamelCase					:		str 				=   no_split_module_classes
												_UpperCamelCase					:		int 				=   bnb_quantization_config.target_dtype

												# get max_memory for each device.
												if device_map != "sequential":
																		_UpperCamelCase					:		Any 				=   get_balanced_memory(
																		    _A  ,  low_zero=(device_map == 'balanced_low_0')  ,  max_memory=_A  ,  **_A  ,  )

												_UpperCamelCase					:		Union[str, Any] 				=   max_memory
												_UpperCamelCase					:		Optional[int] 				=   infer_auto_device_map(_A  ,  **_A							)

						if isinstance(_A  ,  _A							):
												# check if don't have any quantized module on the cpu
												_UpperCamelCase					:		str 				=   bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules

												_UpperCamelCase					:		Tuple 				=   {
												    key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
												}
												for device in ["cpu", "disk"]:
																		if device in device_map_without_some_modules.values():
																								if bnb_quantization_config.load_in_abit:
																														raise ValueError(
																														    '\n                        Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n                        the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n                        these modules in `torch_dtype`, you need to pass a custom `device_map` to\n                        `load_and_quantize_model`. Check\n                        https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n                        for more details.\n                        '							)
																								else:
																														logger.info(
																														    'Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit'							)
												del device_map_without_some_modules
						return device_map






def A__    (     UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_=None  ,  UpperCAmelCase_=None							):


						if modules_to_not_convert is None:
												_UpperCamelCase					:		str 				=   []

						_UpperCamelCase				,			_UpperCamelCase					:		List[Any] 				=   _replace_with_bnb_layers(
						    _A  ,  _A  ,  _A  ,  _A							)
						if not has_been_replaced:
												logger.warning(
												    'You are loading your model in 8bit or 4bit but no linear modules were found in your model.'
												    ' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.'
												    ' Please double check your model architecture, or submit an issue on github if you think this is'
												    ' a bug.'							)
						return model






def A__    (     UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_=None  ,  UpperCAmelCase_=None  ,  ):
						_UpperCamelCase					:		List[str] 				=   False
						for name, module in model.named_children():
												if current_key_name is None:
																		_UpperCamelCase					:		int 				=   []
												current_key_name.append(_A							)
												if isinstance(_A  ,  nn.Linear							) and name not in modules_to_not_convert:
																		# Check if the current key is not in the `modules_to_not_convert`
																		_UpperCamelCase					:		Any 				=   '.'.join(_A							)
																		_UpperCamelCase					:		List[str] 				=   True
																		for key in modules_to_not_convert:
																								if (
																								    (key in current_key_name_str) and (key + "." in current_key_name_str)
																								) or key == current_key_name_str:
																														_UpperCamelCase					:		List[Any] 				=   False
																														break
																		if proceed:
																								# Load bnb module with empty weight and replace ``nn.Linear` module
																								if bnb_quantization_config.load_in_abit:
																														_UpperCamelCase					:		Optional[int] 				=   bnb.nn.LinearabitLt(
																														    module.in_features  ,  module.out_features  ,  module.bias is not None  ,  has_fpaa_weights=_A  ,  threshold=bnb_quantization_config.llm_inta_threshold  ,  )
																								elif bnb_quantization_config.load_in_abit:
																														_UpperCamelCase					:		List[str] 				=   bnb.nn.Linearabit(
																														    module.in_features  ,  module.out_features  ,  module.bias is not None  ,  bnb_quantization_config.bnb_abit_compute_dtype  ,  compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant  ,  quant_type=bnb_quantization_config.bnb_abit_quant_type  ,  )
																								else:
																														raise ValueError('load_in_8bit and load_in_4bit can\'t be both False'							)
																								_UpperCamelCase					:		Optional[int] 				=   module.weight.data
																								if module.bias is not None:
																														_UpperCamelCase					:		int 				=   module.bias.data
																								bnb_module.requires_grad_(_A							)
																								setattr(_A  ,  _A  ,  _A							)
																								_UpperCamelCase					:		Tuple 				=   True
												if len(list(module.children()							)							) > 0:
																		_UpperCamelCase				,			_UpperCamelCase					:		Optional[int] 				=   _replace_with_bnb_layers(
																		    _A  ,  _A  ,  _A  ,  _A							)
																		_UpperCamelCase					:		List[str] 				=   has_been_replaced | _has_been_replaced
												# Remove the last key for recursion
												current_key_name.pop(-1							)
						return model, has_been_replaced






def A__    (     UpperCAmelCase_							):


						with init_empty_weights():
												_UpperCamelCase					:		List[str] 				=   deepcopy(_A							)  # this has 0 cost since it is done inside `init_empty_weights` context manager`

						_UpperCamelCase					:		int 				=   find_tied_parameters(_A							)
						# For compatibility with Accelerate < 0.18
						if isinstance(_A  ,  _A							):
												_UpperCamelCase					:		Any 				=   sum(list(tied_params.values()							)  ,  []							) + list(tied_params.keys()							)
						else:
												_UpperCamelCase					:		str 				=   sum(_A  ,  []							)
						_UpperCamelCase					:		Union[str, Any] 				=   len(_A							) > 0

						# Check if it is a base model
						_UpperCamelCase					:		int 				=   False
						if hasattr(_A  ,  'base_model_prefix'							):
												_UpperCamelCase					:		Union[str, Any] 				=   not hasattr(_A  ,  model.base_model_prefix							)

						# Ignore this for base models (BertModel, GPT2Model, etc.)
						if (not has_tied_params) and is_base_model:
												return []

						# otherwise they have an attached head
						_UpperCamelCase					:		Tuple 				=   list(model.named_children()							)
						_UpperCamelCase					:		List[str] 				=   [list_modules[-1][0]]

						# add last module together with tied weights
						_UpperCamelCase					:		int 				=   set(_A							) - set(_A							)
						_UpperCamelCase					:		int 				=   list(set(_A							)							) + list(_A							)

						# remove ".weight" from the keys
						_UpperCamelCase					:		Any 				=   ['.weight', '.bias']
						_UpperCamelCase					:		int 				=   []
						for name in list_untouched:
												for name_to_remove in names_to_remove:
																		if name_to_remove in name:
																								_UpperCamelCase					:		Union[str, Any] 				=   name.replace(_A  ,  ''							)
												filtered_module_names.append(_A							)

						return filtered_module_names






def A__    (     UpperCAmelCase_							):


						for m in model.modules():
												if isinstance(_A  ,  bnb.nn.Linearabit							):
																		return True
						return False






def A__    (     UpperCAmelCase_							):
						return next(parameter.parameters()							).device






def A__    (     UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_							):


						if fpaa_statistics is None:
												set_module_tensor_to_device(_A  ,  _A  ,  0  ,  dtype=_A  ,  value=_A							)
												_UpperCamelCase					:		Optional[Any] 				=   param_name
												_UpperCamelCase					:		List[Any] 				=   model
												if "." in tensor_name:
																		_UpperCamelCase					:		Union[str, Any] 				=   tensor_name.split('.'							)
																		for split in splits[:-1]:
																								_UpperCamelCase					:		Tuple 				=   getattr(_A  ,  _A							)
																								if new_module is None:
																														raise ValueError(f'{module} has no attribute {split}.'							)
																								_UpperCamelCase					:		str 				=   new_module
																		_UpperCamelCase					:		Optional[int] 				=   splits[-1]
												# offload weights
												_UpperCamelCase					:		str 				=   False
												offload_weight(module._parameters[tensor_name]  ,  _A  ,  _A  ,  index=_A							)
												if hasattr(module._parameters[tensor_name]  ,  'SCB'							):
																		offload_weight(
																		    module._parameters[tensor_name].SCB  ,  param_name.replace('weight'  ,  'SCB'							)  ,  _A  ,  index=_A  ,  )
						else:
												offload_weight(_A  ,  _A  ,  _A  ,  index=_A							)
												offload_weight(_A  ,  param_name.replace('weight'  ,  'SCB'							)  ,  _A  ,  index=_A							)

						set_module_tensor_to_device(_A  ,  _A  ,  'meta'  ,  dtype=_A  ,  value=torch.empty(*param.size()							)							)



'''simple docstring'''




import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
						import tensorflow as tf






class 				a__(					enum.Enum	):


			'''simple docstring'''






			UpperCAmelCase_			:     Dict      =       0
			UpperCAmelCase_			:     Dict      =       1
			UpperCAmelCase_			:     Any      =       2







@add_end_docstrings(lowerCAmelCase__	)
class 				a__(					lowerCAmelCase__	):


			'''simple docstring'''






			UpperCAmelCase_			:     int      =       '''
    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The
    voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western
    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision
    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an
    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,
    begging for his blessing. <eod> </s> <eos>
    '''



			def __init__(   self       ,    *__lowerCAmelCase       ,    **__lowerCAmelCase):




					"""simple docstring"""


					super().__init__(*__lowerCAmelCase       ,    **__lowerCAmelCase)
					self.check_model_type(
					    TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING)
					if "prefix" not in self._preprocess_params:
							# This is very specific. The logic is quite complex and needs to be done
							# as a "default".
							# It also defines both some preprocess_kwargs and generate_kwargs
							# which is why we cannot put them in their respective methods.
							lowerCAmelCase   					=  None
							if self.model.config.prefix is not None:
									lowerCAmelCase   					=  self.model.config.prefix
							if prefix is None and self.model.__class__.__name__ in [
							    "XLNetLMHeadModel",
							    "TransfoXLLMHeadModel",
							    "TFXLNetLMHeadModel",
							    "TFTransfoXLLMHeadModel",
							]:
									# For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
									lowerCAmelCase   					=  self.XL_PREFIX
							if prefix is not None:
									# Recalculate some generate_kwargs linked to prefix.
									lowerCAmelCase					,     lowerCAmelCase					,     lowerCAmelCase   					=  self._sanitize_parameters(prefix=__lowerCAmelCase       ,    **self._forward_params)
									lowerCAmelCase   					=  {**self._preprocess_params, **preprocess_params}
									lowerCAmelCase   					=  {**self._forward_params, **forward_params}



			def 							a_       (   self       ,    __lowerCAmelCase=None       ,    __lowerCAmelCase=None       ,    __lowerCAmelCase=None       ,    __lowerCAmelCase=None       ,    __lowerCAmelCase=None       ,    __lowerCAmelCase=None       ,    __lowerCAmelCase=None       ,    __lowerCAmelCase=None       ,    **__lowerCAmelCase       ,    ):




					"""simple docstring"""


					lowerCAmelCase   					=  {}
					if prefix is not None:
							lowerCAmelCase   					=  prefix
					if prefix:
							lowerCAmelCase   					=  self.tokenizer(
							    __lowerCAmelCase       ,    padding=__lowerCAmelCase       ,    add_special_tokens=__lowerCAmelCase       ,    return_tensors=self.framework)
							lowerCAmelCase   					=  prefix_inputs["""input_ids"""].shape[-1]

					if handle_long_generation is not None:
							if handle_long_generation not in {"hole"}:
									raise ValueError(
									    f"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected"
									    """ [None, 'hole']""")
							lowerCAmelCase   					=  handle_long_generation

					preprocess_params.update(__lowerCAmelCase)
					lowerCAmelCase   					=  generate_kwargs

					lowerCAmelCase   					=  {}
					if return_full_text is not None and return_type is None:
							if return_text is not None:
									raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""")
							if return_tensors is not None:
									raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""")
							lowerCAmelCase   					=  ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
					if return_tensors is not None and return_type is None:
							if return_text is not None:
									raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""")
							lowerCAmelCase   					=  ReturnType.TENSORS
					if return_type is not None:
							lowerCAmelCase   					=  return_type
					if clean_up_tokenization_spaces is not None:
							lowerCAmelCase   					=  clean_up_tokenization_spaces

					if stop_sequence is not None:
							lowerCAmelCase   					=  self.tokenizer.encode(__lowerCAmelCase       ,    add_special_tokens=__lowerCAmelCase)
							if len(__lowerCAmelCase) > 1:
									warnings.warn(
									    """Stopping on a multiple token sequence is not yet supported on transformers. The first token of"""
									    """ the stop sequence will be used as the stop sequence string in the interim.""")
							lowerCAmelCase   					=  stop_sequence_ids[0]

					return preprocess_params, forward_params, postprocess_params



			def 							a_       (   self       ,    *__lowerCAmelCase       ,    **__lowerCAmelCase):




					"""simple docstring"""


					if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
							kwargs.update({"""add_space_before_punct_symbol""": True})

					return super()._parse_and_tokenize(*__lowerCAmelCase       ,    **__lowerCAmelCase)



			def __call__(   self       ,    __lowerCAmelCase       ,    **__lowerCAmelCase):




					"""simple docstring"""


					return super().__call__(__lowerCAmelCase       ,    **__lowerCAmelCase)



			def 							a_       (   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase=""       ,    __lowerCAmelCase=None       ,    **__lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase   					=  self.tokenizer(
					    prefix + prompt_text       ,    padding=__lowerCAmelCase       ,    add_special_tokens=__lowerCAmelCase       ,    return_tensors=self.framework)
					lowerCAmelCase   					=  prompt_text

					if handle_long_generation == "hole":
							lowerCAmelCase   					=  inputs["""input_ids"""].shape[-1]
							if "max_new_tokens" in generate_kwargs:
									lowerCAmelCase   					=  generate_kwargs["""max_new_tokens"""]
							else:
									lowerCAmelCase   					=  generate_kwargs.get("""max_length"""       ,    self.model.config.max_length) - cur_len
									if new_tokens < 0:
											raise ValueError("""We cannot infer how many new tokens are expected""")
							if cur_len + new_tokens > self.tokenizer.model_max_length:
									lowerCAmelCase   					=  self.tokenizer.model_max_length - new_tokens
									if keep_length <= 0:
											raise ValueError(
											    """We cannot use `hole` to handle this generation the number of desired tokens exceeds the"""
											    """ models max length""")

									lowerCAmelCase   					=  inputs["""input_ids"""][:, -keep_length:]
									if "attention_mask" in inputs:
											lowerCAmelCase   					=  inputs["""attention_mask"""][:, -keep_length:]

					return inputs



			def 							a_       (   self       ,    __lowerCAmelCase       ,    **__lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase   					=  model_inputs["""input_ids"""]
					lowerCAmelCase   					=  model_inputs.get("""attention_mask"""       ,    __lowerCAmelCase)
					# Allow empty prompts
					if input_ids.shape[1] == 0:
							lowerCAmelCase   					=  None
							lowerCAmelCase   					=  None
							lowerCAmelCase   					=  1
					else:
							lowerCAmelCase   					=  input_ids.shape[0]
					lowerCAmelCase   					=  model_inputs.pop("""prompt_text""")

					# If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
					# generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
					lowerCAmelCase   					=  generate_kwargs.pop("""prefix_length"""       ,    0)
					if prefix_length > 0:
							lowerCAmelCase   					=  """max_new_tokens""" in generate_kwargs or (
							    """generation_config""" in generate_kwargs
							    and generate_kwargs["""generation_config"""].max_new_tokens is not None
							)
							if not has_max_new_tokens:
									lowerCAmelCase   					=  generate_kwargs.get("""max_length""") or self.model.config.max_length
									generate_kwargs["max_length"] += prefix_length
							lowerCAmelCase   					=  """min_new_tokens""" in generate_kwargs or (
							    """generation_config""" in generate_kwargs
							    and generate_kwargs["""generation_config"""].min_new_tokens is not None
							)
							if not has_min_new_tokens and "min_length" in generate_kwargs:
									generate_kwargs["min_length"] += prefix_length

        # BS x SL
					lowerCAmelCase   					=  self.model.generate(input_ids=__lowerCAmelCase       ,    attention_mask=__lowerCAmelCase       ,    **__lowerCAmelCase)
					lowerCAmelCase   					=  generated_sequence.shape[0]
					if self.framework == "pt":
							lowerCAmelCase   					=  generated_sequence.reshape(__lowerCAmelCase       ,    out_b // in_b       ,    *generated_sequence.shape[1:])
					elif self.framework == "tf":
							lowerCAmelCase   					=  tf.reshape(__lowerCAmelCase       ,    (in_b, out_b // in_b, *generated_sequence.shape[1:]))
					return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}







			def 							a_       (   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase=ReturnType.FULL_TEXT       ,    __lowerCAmelCase=True):




					"""simple docstring"""


					lowerCAmelCase   					=  model_outputs["""generated_sequence"""][0]
					lowerCAmelCase   					=  model_outputs["""input_ids"""]
					lowerCAmelCase   					=  model_outputs["""prompt_text"""]
					lowerCAmelCase   					=  generated_sequence.numpy().tolist()
					lowerCAmelCase   					=  []
					for sequence in generated_sequence:
							if return_type == ReturnType.TENSORS:
									lowerCAmelCase   					=  {"""generated_token_ids""": sequence}
							elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
									# Decode text
									lowerCAmelCase   					=  self.tokenizer.decode(
									    __lowerCAmelCase       ,    skip_special_tokens=__lowerCAmelCase       ,    clean_up_tokenization_spaces=__lowerCAmelCase       ,    )

									# Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
									if input_ids is None:
											lowerCAmelCase   					=  0
									else:
											lowerCAmelCase   					=  len(
											    self.tokenizer.decode(
											        input_ids[0]       ,    skip_special_tokens=__lowerCAmelCase       ,    clean_up_tokenization_spaces=__lowerCAmelCase       ,    ))

									if return_type == ReturnType.FULL_TEXT:
											lowerCAmelCase   					=  prompt_text + text[prompt_length:]
									else:
											lowerCAmelCase   					=  text[prompt_length:]

									lowerCAmelCase   					=  {"""generated_text""": all_text}
							records.append(__lowerCAmelCase)

					return records




