

"""simple docstring"""




import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
      import bitsandbytes as bnb
      import torch
      import torch.nn as nn

      from ..pytorch_utils import ConvaD

if is_accelerate_available():
      from accelerate import init_empty_weights
      from accelerate.utils import find_tied_parameters

__UpperCAmelCase			=					logging.get_logger(__name__)
def 	lowerCAmelCase    (       __UpperCamelCase				,     __UpperCamelCase				,     __UpperCamelCase				,     __UpperCamelCase=None				,     __UpperCamelCase=None   ):
 '''simple docstring'''





 if "." in tensor_name:
  UpperCAmelCase__       :	int        =       tensor_name.split("""."""   )
  for split in splits[:-1]:
   UpperCAmelCase__       :	int        =       getattr(_UpperCamelCase				,     _UpperCamelCase   )
   if new_module is None:
    raise ValueError(F"{module} has no attribute {split}."   )
   UpperCAmelCase__       :	Tuple        =       new_module
  UpperCAmelCase__       :	Tuple        =       splits[-1]

 if tensor_name not in module._parameters and tensor_name not in module._buffers:
  raise ValueError(F"{module} does not have a parameter or a buffer named {tensor_name}."   )
 UpperCAmelCase__       :	List[str]        =       tensor_name in module._buffers
 UpperCAmelCase__       :	Dict        =       getattr(_UpperCamelCase				,     _UpperCamelCase   )

 if old_value.device == torch.device("""meta"""   ) and device not in ["meta", torch.device("""meta"""   )] and value is None:
  raise ValueError(F"{tensor_name} is on the meta device, we need a `value` to put in on {device}."   )

 UpperCAmelCase__       :	Union[str, Any]        =       False
 UpperCAmelCase__       :	Tuple        =       False
 if is_buffer or not is_bitsandbytes_available():
  UpperCAmelCase__       :	Dict        =       False
  UpperCAmelCase__       :	Dict        =       False
 else:
  UpperCAmelCase__       :	str        =       hasattr(bnb.nn				,     """Params4bit"""   ) and isinstance(module._parameters[tensor_name]				,     bnb.nn.Paramsabit   )
  UpperCAmelCase__       :	str        =       isinstance(module._parameters[tensor_name]				,     bnb.nn.IntaParams   )

 if is_abit or is_abit:
  UpperCAmelCase__       :	int        =       module._parameters[tensor_name]
  if param.device.type != "cuda":
   if value is None:
    UpperCAmelCase__       :	Union[str, Any]        =       old_value.to(_UpperCamelCase   )
   elif isinstance(_UpperCamelCase				,     torch.Tensor   ):
    UpperCAmelCase__       :	str        =       value.to("""cpu"""   )
    if value.dtype == torch.inta:
     UpperCAmelCase__       :	Optional[int]        =       version.parse(importlib.metadata.version("""bitsandbytes"""   )   ) > version.parse(
         """0.37.2"""   )
     if not is_abit_serializable:
      raise ValueError(
          """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """
          """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."""   )
   else:
    UpperCAmelCase__       :	int        =       torch.tensor(_UpperCamelCase				,     device="""cpu"""   )

   # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
   # Since weights are saved in the correct "orientation", we skip transposing when loading.
   if issubclass(module.source_cls				,     _UpperCamelCase   ) and fpaa_statistics is None:
    UpperCAmelCase__       :	Tuple        =       new_value.T

   UpperCAmelCase__       :	Dict        =       old_value.__dict__
   if is_abit:
    UpperCAmelCase__       :	Any        =       bnb.nn.IntaParams(_UpperCamelCase				,     requires_grad=_UpperCamelCase				,     **_UpperCamelCase   ).to(_UpperCamelCase   )
   elif is_abit:
    UpperCAmelCase__       :	Any        =       bnb.nn.Paramsabit(_UpperCamelCase				,     requires_grad=_UpperCamelCase				,     **_UpperCamelCase   ).to(_UpperCamelCase   )

   UpperCAmelCase__       :	Any        =       new_value
   if fpaa_statistics is not None:
    setattr(module.weight				,     """SCB"""				,     fpaa_statistics.to(_UpperCamelCase   )   )

 else:
  if value is None:
   UpperCAmelCase__       :	int        =       old_value.to(_UpperCamelCase   )
  elif isinstance(_UpperCamelCase				,     torch.Tensor   ):
   UpperCAmelCase__       :	List[Any]        =       value.to(_UpperCamelCase   )
  else:
   UpperCAmelCase__       :	str        =       torch.tensor(_UpperCamelCase				,     device=_UpperCamelCase   )

  if is_buffer:
   UpperCAmelCase__       :	List[str]        =       new_value
  else:
   UpperCAmelCase__       :	List[Any]        =       nn.Parameter(_UpperCamelCase				,     requires_grad=old_value.requires_grad   )
   UpperCAmelCase__       :	List[Any]        =       new_value
def 	lowerCAmelCase    (       __UpperCamelCase				,     __UpperCamelCase=None				,     __UpperCamelCase=None				,     __UpperCamelCase=None				,     __UpperCamelCase=False   ):
 '''simple docstring'''





 for name, module in model.named_children():
  if current_key_name is None:
   UpperCAmelCase__       :	str        =       []
  current_key_name.append(_UpperCamelCase   )

  if (isinstance(_UpperCamelCase				,     nn.Linear   ) or isinstance(_UpperCamelCase				,     _UpperCamelCase   )) and name not in modules_to_not_convert:
   # Check if the current key is not in the `modules_to_not_convert`
   if not any(key in """.""".join(_UpperCamelCase   ) for key in modules_to_not_convert   ):
    with init_empty_weights():
     if isinstance(_UpperCamelCase				,     _UpperCamelCase   ):
      UpperCAmelCase__ ,   UpperCAmelCase__       :	Union[str, Any]        =       module.weight.shape
     else:
      UpperCAmelCase__       :	Optional[int]        =       module.in_features
      UpperCAmelCase__       :	Dict        =       module.out_features

     if quantization_config.quantization_method() == "llm_int8":
      UpperCAmelCase__       :	Tuple        =       bnb.nn.LinearabitLt(
          _UpperCamelCase				,     _UpperCamelCase				,     module.bias is not None				,     has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight				,     threshold=quantization_config.llm_inta_threshold				,     )
      UpperCAmelCase__       :	Any        =       True
     else:
      if (
          quantization_config.llm_inta_skip_modules is not None
          and name in quantization_config.llm_inta_skip_modules
      ):
       pass
      else:
       UpperCAmelCase__       :	List[Any]        =       bnb.nn.Linearabit(
           _UpperCamelCase				,     _UpperCamelCase				,     module.bias is not None				,     quantization_config.bnb_abit_compute_dtype				,     compress_statistics=quantization_config.bnb_abit_use_double_quant				,     quant_type=quantization_config.bnb_abit_quant_type				,     )
       UpperCAmelCase__       :	Optional[Any]        =       True
                    # Store the module class in case we need to transpose the weight later
     UpperCAmelCase__       :	Optional[int]        =       type(_UpperCamelCase   )
     # Force requires grad to False to avoid unexpected errors
     model._modules[name].requires_grad_(_UpperCamelCase   )
  if len(list(module.children()   )   ) > 0:
   UpperCAmelCase__ ,   UpperCAmelCase__       :	Optional[int]        =       _replace_with_bnb_linear(
       _UpperCamelCase				,     _UpperCamelCase				,     _UpperCamelCase				,     _UpperCamelCase				,     has_been_replaced=_UpperCamelCase				,     )
  # Remove the last key for recursion
  current_key_name.pop(-1   )
 return model, has_been_replaced
def 	lowerCAmelCase    (       __UpperCamelCase				,     __UpperCamelCase=None				,     __UpperCamelCase=None				,     __UpperCamelCase=None   ):
 '''simple docstring'''





 UpperCAmelCase__       :	Union[str, Any]        =       ["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert
 UpperCAmelCase__ ,   UpperCAmelCase__       :	Union[str, Any]        =       _replace_with_bnb_linear(
     _UpperCamelCase				,     _UpperCamelCase				,     _UpperCamelCase				,     _UpperCamelCase   )

 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."""
      """ Please double check your model architecture, or submit an issue on github if you think this is"""
      """ a bug."""   )

 return model
def 	lowerCAmelCase    (       *__UpperCamelCase				,     **__UpperCamelCase   ):
 '''simple docstring'''





 warnings.warn(
     """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead"""				,     _UpperCamelCase				,     )
 return replace_with_bnb_linear(*_UpperCamelCase				,     **_UpperCamelCase   )
def 	lowerCAmelCase    (       *__UpperCamelCase				,     **__UpperCamelCase   ):
 '''simple docstring'''





 warnings.warn(
     """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead"""				,     _UpperCamelCase				,     )
 return set_module_quantized_tensor_to_device(*_UpperCamelCase				,     **_UpperCamelCase   )




def 	lowerCAmelCase    (       __UpperCamelCase   ):
 '''simple docstring'''





 UpperCAmelCase__       :	str        =       deepcopy(_UpperCamelCase   )  # this has 0 cost since it is done inside `init_empty_weights` context manager`
 tied_model.tie_weights()

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

 # Check if it is a base model
 UpperCAmelCase__       :	int        =       not hasattr(_UpperCamelCase				,     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__       :	Dict        =       list(model.named_children()   )
 UpperCAmelCase__       :	List[str]        =       [list_modules[-1][0]]

 # add last module together with tied weights
 UpperCAmelCase__       :	List[Any]        =       set(_UpperCamelCase   ) - set(_UpperCamelCase   )
 UpperCAmelCase__       :	Tuple        =       list(set(_UpperCamelCase   )   ) + list(_UpperCamelCase   )

 # remove ".weight" from the keys
 UpperCAmelCase__       :	Tuple        =       [""".weight""", """.bias"""]
 UpperCAmelCase__       :	Tuple        =       []
 for name in list_untouched:
  for name_to_remove in names_to_remove:
   if name_to_remove in name:
    UpperCAmelCase__       :	List[str]        =       name.replace(_UpperCamelCase				,     """"""   )
  filtered_module_names.append(_UpperCamelCase   )

 return filtered_module_names













from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments
from transformers.testing_utils import TestCasePlus, require_torch, slow
from transformers.utils import is_datasets_available


if is_datasets_available():
       import datasets





class 					A__     (     __snake_case ):

     '''simple docstring'''






     @slow
     @require_torch
     def   _SCREAMING_SNAKE_CASE     ( self      :    Tuple ):






           """simple docstring"""




           UpperCamelCase					       =  EncoderDecoderModel.from_encoder_decoder_pretrained('prajjwal1/bert-tiny'   ,						'prajjwal1/bert-tiny' )
           UpperCamelCase					       =  BertTokenizer.from_pretrained('bert-base-uncased' )

           UpperCamelCase					       =  bertabert.config.encoder.vocab_size
           UpperCamelCase					       =  tokenizer.sep_token_id
           UpperCamelCase					       =  tokenizer.cls_token_id
           UpperCamelCase					       =  128

           UpperCamelCase					       =  datasets.load_dataset('cnn_dailymail'   ,						'3.0.0'   ,						split='train[:1%]' )
           UpperCamelCase					       =  datasets.load_dataset('cnn_dailymail'   ,						'3.0.0'   ,						split='validation[:1%]' )

           UpperCamelCase					       =  train_dataset.select(range(32 ) )
           UpperCamelCase					       =  val_dataset.select(range(16 ) )

           UpperCamelCase					       =  4

           def _map_to_encoder_decoder_inputs(_SCREAMING_SNAKE_CASE      :    Tuple ):
                 # Tokenizer will automatically set [BOS] <text> [EOS]
                 UpperCamelCase					       =  tokenizer(batch['article']   ,						padding='max_length'   ,						truncation=_SCREAMING_SNAKE_CASE   ,						max_length=512 )
                 UpperCamelCase					       =  tokenizer(batch['highlights']   ,						padding='max_length'   ,						truncation=_SCREAMING_SNAKE_CASE   ,						max_length=128 )
                 UpperCamelCase					       =  inputs.input_ids
                 UpperCamelCase					       =  inputs.attention_mask

                 UpperCamelCase					       =  outputs.input_ids
                 UpperCamelCase					       =  outputs.input_ids.copy()
                 UpperCamelCase					       =  [
                     [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch['labels']
                 ]
                 UpperCamelCase					       =  outputs.attention_mask

                 assert all(len(_SCREAMING_SNAKE_CASE ) == 512 for x in inputs.input_ids )
                 assert all(len(_SCREAMING_SNAKE_CASE ) == 128 for x in outputs.input_ids )

                 return batch

           def _compute_metrics(_SCREAMING_SNAKE_CASE      :    str ):
                 UpperCamelCase					       =  pred.label_ids
                 UpperCamelCase					       =  pred.predictions

                 # all unnecessary tokens are removed
                 UpperCamelCase					       =  tokenizer.batch_decode(_SCREAMING_SNAKE_CASE   ,						skip_special_tokens=_SCREAMING_SNAKE_CASE )
                 UpperCamelCase					       =  tokenizer.batch_decode(_SCREAMING_SNAKE_CASE   ,						skip_special_tokens=_SCREAMING_SNAKE_CASE )

                 UpperCamelCase					       =  sum([int(pred_str[i] == label_str[i] ) for i in range(len(_SCREAMING_SNAKE_CASE ) )] ) / len(_SCREAMING_SNAKE_CASE )

                 return {"accuracy": accuracy}

           # map train dataset
           UpperCamelCase					       =  train_dataset.map(
               _map_to_encoder_decoder_inputs   ,						batched=_SCREAMING_SNAKE_CASE   ,						batch_size=_SCREAMING_SNAKE_CASE   ,						remove_columns=['article', 'highlights']   ,						)
           train_dataset.set_format(
               type='torch'   ,						columns=['input_ids', 'attention_mask', 'decoder_input_ids', 'decoder_attention_mask', 'labels']   ,						)

           # same for validation dataset
           UpperCamelCase					       =  val_dataset.map(
               _map_to_encoder_decoder_inputs   ,						batched=_SCREAMING_SNAKE_CASE   ,						batch_size=_SCREAMING_SNAKE_CASE   ,						remove_columns=['article', 'highlights']   ,						)
           val_dataset.set_format(
               type='torch'   ,						columns=['input_ids', 'attention_mask', 'decoder_input_ids', 'decoder_attention_mask', 'labels']   ,						)

           UpperCamelCase					       =  self.get_auto_remove_tmp_dir()

           UpperCamelCase					       =  SeqaSeqTrainingArguments(
               output_dir=_SCREAMING_SNAKE_CASE   ,						per_device_train_batch_size=_SCREAMING_SNAKE_CASE   ,						per_device_eval_batch_size=_SCREAMING_SNAKE_CASE   ,						predict_with_generate=_SCREAMING_SNAKE_CASE   ,						evaluation_strategy='steps'   ,						do_train=_SCREAMING_SNAKE_CASE   ,						do_eval=_SCREAMING_SNAKE_CASE   ,						warmup_steps=0   ,						eval_steps=2   ,						logging_steps=2   ,						)

           # instantiate trainer
           UpperCamelCase					       =  SeqaSeqTrainer(
               model=_SCREAMING_SNAKE_CASE   ,						args=_SCREAMING_SNAKE_CASE   ,						compute_metrics=_compute_metrics   ,						train_dataset=_SCREAMING_SNAKE_CASE   ,						eval_dataset=_SCREAMING_SNAKE_CASE   ,						tokenizer=_SCREAMING_SNAKE_CASE   ,						)

           # start training
           trainer.train()



