






"""simple docstring"""






import unittest

from transformers import XLMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import (
      XLMForMultipleChoice,
      XLMForQuestionAnswering,
      XLMForQuestionAnsweringSimple,
      XLMForSequenceClassification,
      XLMForTokenClassification,
      XLMModel,
      XLMWithLMHeadModel,
  )
  from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST




class 							lowerCAmelCase__       :






      '''simple docstring'''

      def __init__(		self  :						Tuple		,			lowercase_  :						Tuple		,			lowercase_  :						Tuple=13		,			lowercase_  :						List[str]=7		,			lowercase_  :						Optional[int]=True		,			lowercase_  :						Dict=True		,			lowercase_  :						List[str]=True		,			lowercase_  :						Union[str, Any]=True		,			lowercase_  :						Any=True		,			lowercase_  :						List[str]=False		,			lowercase_  :						Any=False		,			lowercase_  :						Optional[int]=False		,			lowercase_  :						Optional[Any]=2		,			lowercase_  :						Any=99		,			lowercase_  :						List[str]=0		,			lowercase_  :						Union[str, Any]=32		,			lowercase_  :						List[Any]=5		,			lowercase_  :						List[Any]=4		,			lowercase_  :						int=0.1		,			lowercase_  :						Union[str, Any]=0.1		,			lowercase_  :						Optional[Any]=512		,			lowercase_  :						Tuple=2		,			lowercase_  :						int=0.02		,			lowercase_  :						Tuple=2		,			lowercase_  :						Optional[Any]=4		,			lowercase_  :						Tuple="last"		,			lowercase_  :						Tuple=True		,			lowercase_  :						List[Any]=None		,			lowercase_  :						str=0		,			):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	parent
          SCREAMING_SNAKE_CASE_   :						Tuple							=	batch_size
          SCREAMING_SNAKE_CASE_   :						int							=	seq_length
          SCREAMING_SNAKE_CASE_   :						Dict							=	is_training
          SCREAMING_SNAKE_CASE_   :						List[Any]							=	use_input_lengths
          SCREAMING_SNAKE_CASE_   :						int							=	use_token_type_ids
          SCREAMING_SNAKE_CASE_   :						Any							=	use_labels
          SCREAMING_SNAKE_CASE_   :						List[str]							=	gelu_activation
          SCREAMING_SNAKE_CASE_   :						Tuple							=	sinusoidal_embeddings
          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	causal
          SCREAMING_SNAKE_CASE_   :						str							=	asm
          SCREAMING_SNAKE_CASE_   :						List[str]							=	n_langs
          SCREAMING_SNAKE_CASE_   :						int							=	vocab_size
          SCREAMING_SNAKE_CASE_   :						List[Any]							=	n_special
          SCREAMING_SNAKE_CASE_   :						int							=	hidden_size
          SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	num_hidden_layers
          SCREAMING_SNAKE_CASE_   :						int							=	num_attention_heads
          SCREAMING_SNAKE_CASE_   :						Tuple							=	hidden_dropout_prob
          SCREAMING_SNAKE_CASE_   :						Dict							=	attention_probs_dropout_prob
          SCREAMING_SNAKE_CASE_   :						Dict							=	max_position_embeddings
          SCREAMING_SNAKE_CASE_   :						Any							=	type_sequence_label_size
          SCREAMING_SNAKE_CASE_   :						List[str]							=	initializer_range
          SCREAMING_SNAKE_CASE_   :						Any							=	num_labels
          SCREAMING_SNAKE_CASE_   :						Tuple							=	num_choices
          SCREAMING_SNAKE_CASE_   :						List[Any]							=	summary_type
          SCREAMING_SNAKE_CASE_   :						Tuple							=	use_proj
          SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	scope
          SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	bos_token_id
      def _SCREAMING_SNAKE_CASE				(		self  :						Tuple):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						str							=	ids_tensor([self.batch_size, self.seq_length]		,			self.vocab_size)
          SCREAMING_SNAKE_CASE_   :						List[str]							=	random_attention_mask([self.batch_size, self.seq_length])

          SCREAMING_SNAKE_CASE_   :						Any							=	None
          if self.use_input_lengths:
              SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	(
                  ids_tensor([self.batch_size]		,			vocab_size=2) + self.seq_length - 2
              )  # small variation of seq_length

          SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	None
          if self.use_token_type_ids:
              SCREAMING_SNAKE_CASE_   :						Any							=	ids_tensor([self.batch_size, self.seq_length]		,			self.n_langs)

          SCREAMING_SNAKE_CASE_   :						int							=	None
          SCREAMING_SNAKE_CASE_   :						Tuple							=	None
          SCREAMING_SNAKE_CASE_   :						List[str]							=	None
          if self.use_labels:
              SCREAMING_SNAKE_CASE_   :						str							=	ids_tensor([self.batch_size]		,			self.type_sequence_label_size)
              SCREAMING_SNAKE_CASE_   :						List[str]							=	ids_tensor([self.batch_size, self.seq_length]		,			self.num_labels)
              SCREAMING_SNAKE_CASE_   :						List[str]							=	ids_tensor([self.batch_size]		,			2).float()
              SCREAMING_SNAKE_CASE_   :						Dict							=	ids_tensor([self.batch_size]		,			self.num_choices)

          SCREAMING_SNAKE_CASE_   :						int							=	self.get_config()

          return (
              config,
              input_ids,
              token_type_ids,
              input_lengths,
              sequence_labels,
              token_labels,
              is_impossible_labels,
              choice_labels,
              input_mask,
          )
      def _SCREAMING_SNAKE_CASE				(		self  :						Any):




          '''simple docstring'''


          return XLMConfig(
              vocab_size=self.vocab_size		,			n_special=self.n_special		,			emb_dim=self.hidden_size		,			n_layers=self.num_hidden_layers		,			n_heads=self.num_attention_heads		,			dropout=self.hidden_dropout_prob		,			attention_dropout=self.attention_probs_dropout_prob		,			gelu_activation=self.gelu_activation		,			sinusoidal_embeddings=self.sinusoidal_embeddings		,			asm=self.asm		,			causal=self.causal		,			n_langs=self.n_langs		,			max_position_embeddings=self.max_position_embeddings		,			initializer_range=self.initializer_range		,			summary_type=self.summary_type		,			use_proj=self.use_proj		,			num_labels=self.num_labels		,			bos_token_id=self.bos_token_id		,			)
      def _SCREAMING_SNAKE_CASE				(		self  :						Dict		,			lowercase_  :						Any		,			lowercase_  :						List[str]		,			lowercase_  :						Union[str, Any]		,			lowercase_  :						int		,			lowercase_  :						Optional[Any]		,			lowercase_  :						Tuple		,			lowercase_  :						Optional[int]		,			lowercase_  :						Any		,			lowercase_  :						Optional[int]		,			):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						List[str]							=	XLMModel(config=lowercase_)
          model.to(lowercase_)
          model.eval()
          SCREAMING_SNAKE_CASE_   :						str							=	model(lowercase_		,			lengths=lowercase_		,			langs=lowercase_)
          SCREAMING_SNAKE_CASE_   :						Dict							=	model(lowercase_		,			langs=lowercase_)
          SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	model(lowercase_)
          self.parent.assertEqual(result.last_hidden_state.shape		,			(self.batch_size, self.seq_length, self.hidden_size))
      def _SCREAMING_SNAKE_CASE				(		self  :						List[str]		,			lowercase_  :						int		,			lowercase_  :						int		,			lowercase_  :						Any		,			lowercase_  :						Optional[int]		,			lowercase_  :						Dict		,			lowercase_  :						List[str]		,			lowercase_  :						int		,			lowercase_  :						Optional[int]		,			lowercase_  :						int		,			):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						List[Any]							=	XLMWithLMHeadModel(lowercase_)
          model.to(lowercase_)
          model.eval()

          SCREAMING_SNAKE_CASE_   :						List[Any]							=	model(lowercase_		,			token_type_ids=lowercase_		,			labels=lowercase_)
          self.parent.assertEqual(result.loss.shape		,			())
          self.parent.assertEqual(result.logits.shape		,			(self.batch_size, self.seq_length, self.vocab_size))
      def _SCREAMING_SNAKE_CASE				(		self  :						Optional[Any]		,			lowercase_  :						int		,			lowercase_  :						int		,			lowercase_  :						Optional[int]		,			lowercase_  :						Dict		,			lowercase_  :						str		,			lowercase_  :						Union[str, Any]		,			lowercase_  :						Union[str, Any]		,			lowercase_  :						Dict		,			lowercase_  :						List[str]		,			):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Optional[int]							=	XLMForQuestionAnsweringSimple(lowercase_)
          model.to(lowercase_)
          model.eval()

          SCREAMING_SNAKE_CASE_   :						List[str]							=	model(lowercase_)

          SCREAMING_SNAKE_CASE_   :						Optional[int]							=	model(lowercase_		,			start_positions=lowercase_		,			end_positions=lowercase_)
          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	outputs
          self.parent.assertEqual(result.start_logits.shape		,			(self.batch_size, self.seq_length))
          self.parent.assertEqual(result.end_logits.shape		,			(self.batch_size, self.seq_length))
      def _SCREAMING_SNAKE_CASE				(		self  :						Any		,			lowercase_  :						Optional[Any]		,			lowercase_  :						List[str]		,			lowercase_  :						List[Any]		,			lowercase_  :						Dict		,			lowercase_  :						str		,			lowercase_  :						Optional[int]		,			lowercase_  :						Union[str, Any]		,			lowercase_  :						Any		,			lowercase_  :						List[Any]		,			):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						str							=	XLMForQuestionAnswering(lowercase_)
          model.to(lowercase_)
          model.eval()

          SCREAMING_SNAKE_CASE_   :						Any							=	model(lowercase_)

          SCREAMING_SNAKE_CASE_   :						Optional[int]							=	model(
              lowercase_		,			start_positions=lowercase_		,			end_positions=lowercase_		,			cls_index=lowercase_		,			is_impossible=lowercase_		,			p_mask=lowercase_		,			)

          SCREAMING_SNAKE_CASE_   :						List[Any]							=	model(
              lowercase_		,			start_positions=lowercase_		,			end_positions=lowercase_		,			cls_index=lowercase_		,			is_impossible=lowercase_		,			)

          (SCREAMING_SNAKE_CASE_    )   :						str							=	result_with_labels.to_tuple()

          SCREAMING_SNAKE_CASE_   :						Any							=	model(lowercase_		,			start_positions=lowercase_		,			end_positions=lowercase_)

          (SCREAMING_SNAKE_CASE_    )   :						Dict							=	result_with_labels.to_tuple()

          self.parent.assertEqual(result_with_labels.loss.shape		,			())
          self.parent.assertEqual(result.start_top_log_probs.shape		,			(self.batch_size, model.config.start_n_top))
          self.parent.assertEqual(result.start_top_index.shape		,			(self.batch_size, model.config.start_n_top))
          self.parent.assertEqual(
              result.end_top_log_probs.shape		,			(self.batch_size, model.config.start_n_top * model.config.end_n_top))
          self.parent.assertEqual(
              result.end_top_index.shape		,			(self.batch_size, model.config.start_n_top * model.config.end_n_top))
          self.parent.assertEqual(result.cls_logits.shape		,			(self.batch_size,))
      def _SCREAMING_SNAKE_CASE				(		self  :						Optional[Any]		,			lowercase_  :						Dict		,			lowercase_  :						List[str]		,			lowercase_  :						Union[str, Any]		,			lowercase_  :						Dict		,			lowercase_  :						Union[str, Any]		,			lowercase_  :						Optional[Any]		,			lowercase_  :						Dict		,			lowercase_  :						Tuple		,			lowercase_  :						List[Any]		,			):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Tuple							=	XLMForSequenceClassification(lowercase_)
          model.to(lowercase_)
          model.eval()

          SCREAMING_SNAKE_CASE_   :						str							=	model(lowercase_)
          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	model(lowercase_		,			labels=lowercase_)
          self.parent.assertEqual(result.loss.shape		,			())
          self.parent.assertEqual(result.logits.shape		,			(self.batch_size, self.type_sequence_label_size))
      def _SCREAMING_SNAKE_CASE				(		self  :						str		,			lowercase_  :						Union[str, Any]		,			lowercase_  :						Dict		,			lowercase_  :						Optional[Any]		,			lowercase_  :						Any		,			lowercase_  :						int		,			lowercase_  :						Dict		,			lowercase_  :						List[str]		,			lowercase_  :						Optional[Any]		,			lowercase_  :						int		,			):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Tuple							=	self.num_labels
          SCREAMING_SNAKE_CASE_   :						str							=	XLMForTokenClassification(lowercase_)
          model.to(lowercase_)
          model.eval()

          SCREAMING_SNAKE_CASE_   :						str							=	model(lowercase_		,			attention_mask=lowercase_		,			labels=lowercase_)
          self.parent.assertEqual(result.logits.shape		,			(self.batch_size, self.seq_length, self.num_labels))
      def _SCREAMING_SNAKE_CASE				(		self  :						int		,			lowercase_  :						int		,			lowercase_  :						Union[str, Any]		,			lowercase_  :						List[str]		,			lowercase_  :						str		,			lowercase_  :						str		,			lowercase_  :						Tuple		,			lowercase_  :						Optional[int]		,			lowercase_  :						List[Any]		,			lowercase_  :						Union[str, Any]		,			):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						str							=	self.num_choices
          SCREAMING_SNAKE_CASE_   :						Tuple							=	XLMForMultipleChoice(config=lowercase_)
          model.to(lowercase_)
          model.eval()
          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	input_ids.unsqueeze(1).expand(-1		,			self.num_choices		,			-1).contiguous()
          SCREAMING_SNAKE_CASE_   :						str							=	token_type_ids.unsqueeze(1).expand(-1		,			self.num_choices		,			-1).contiguous()
          SCREAMING_SNAKE_CASE_   :						List[Any]							=	input_mask.unsqueeze(1).expand(-1		,			self.num_choices		,			-1).contiguous()
          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	model(
              lowercase_		,			attention_mask=lowercase_		,			token_type_ids=lowercase_		,			labels=lowercase_		,			)
          self.parent.assertEqual(result.logits.shape		,			(self.batch_size, self.num_choices))



      def _SCREAMING_SNAKE_CASE				(		self  :						Any):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						str							=	self.prepare_config_and_inputs()
          (
              SCREAMING_SNAKE_CASE_    
          )   :						Union[str, Any]							=	config_and_inputs
          SCREAMING_SNAKE_CASE_   :						List[Any]							=	{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''lengths''': input_lengths}
          return config, inputs_dict




@require_torch
class 							lowerCAmelCase__       (    UpperCAmelCase__       ,	UpperCAmelCase__       ,	UpperCAmelCase__       ,	unittest.TestCase				):






      '''simple docstring'''

      __UpperCamelCase							=						(
          (
              XLMModel,
              XLMWithLMHeadModel,
              XLMForQuestionAnswering,
              XLMForSequenceClassification,
              XLMForQuestionAnsweringSimple,
              XLMForTokenClassification,
              XLMForMultipleChoice,
          )
          if is_torch_available()
          else ()
      )
      __UpperCamelCase							=						(
          (XLMWithLMHeadModel,) if is_torch_available() else ()
      )  # TODO (PVP): Check other models whether language generation is also applicable
      __UpperCamelCase							=						(
          {
              "feature-extraction": XLMModel,
              "fill-mask": XLMWithLMHeadModel,
              "question-answering": XLMForQuestionAnsweringSimple,
              "text-classification": XLMForSequenceClassification,
              "text-generation": XLMWithLMHeadModel,
              "token-classification": XLMForTokenClassification,
              "zero-shot": XLMForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      def _SCREAMING_SNAKE_CASE				(		self  :						Optional[Any]		,			lowercase_  :						List[Any]		,			lowercase_  :						Dict		,			lowercase_  :						Dict		,			lowercase_  :						int		,			lowercase_  :						List[str]):




          '''simple docstring'''


          if (
              pipeline_test_casse_name == "QAPipelineTests"
              and tokenizer_name is not None
              and not tokenizer_name.endswith('''Fast''')
          ):
              # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
              # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
              # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
              return True

          return False
      def _SCREAMING_SNAKE_CASE				(		self  :						str		,			lowercase_  :						Union[str, Any]		,			lowercase_  :						Optional[int]		,			lowercase_  :						str=False):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Tuple							=	super()._prepare_for_class(lowercase_		,			lowercase_		,			return_labels=lowercase_)

          if return_labels:
              if model_class.__name__ == "XLMForQuestionAnswering":
                  SCREAMING_SNAKE_CASE_   :						str							=	torch.zeros(
                      self.model_tester.batch_size		,			dtype=torch.long		,			device=lowercase_)
                  SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	torch.zeros(
                      self.model_tester.batch_size		,			dtype=torch.long		,			device=lowercase_)

          return inputs_dict
      def _SCREAMING_SNAKE_CASE				(		self  :						str):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Tuple							=	XLMModelTester(self)
          SCREAMING_SNAKE_CASE_   :						Dict							=	ConfigTester(self		,			config_class=lowercase_		,			emb_dim=37)
      def _SCREAMING_SNAKE_CASE				(		self  :						Dict):




          '''simple docstring'''


          self.config_tester.run_common_tests()
      def _SCREAMING_SNAKE_CASE				(		self  :						int):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						str							=	self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_xlm_model(*lowercase_)
      def _SCREAMING_SNAKE_CASE				(		self  :						Union[str, Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						List[str]							=	self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_xlm_lm_head(*lowercase_)
      def _SCREAMING_SNAKE_CASE				(		self  :						Tuple):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						str							=	self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_xlm_simple_qa(*lowercase_)
      def _SCREAMING_SNAKE_CASE				(		self  :						List[str]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_xlm_qa(*lowercase_)
      def _SCREAMING_SNAKE_CASE				(		self  :						Tuple):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						int							=	self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_xlm_sequence_classif(*lowercase_)
      def _SCREAMING_SNAKE_CASE				(		self  :						Tuple):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_xlm_token_classif(*lowercase_)
      def _SCREAMING_SNAKE_CASE				(		self  :						List[Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						str							=	self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_xlm_for_multiple_choice(*lowercase_)
      def _SCREAMING_SNAKE_CASE				(		self  :						int		,			lowercase_  :						Any		,			lowercase_  :						int		,			lowercase_  :						Any		,			lowercase_  :						Tuple		,			lowercase_  :						Optional[Any]		,			lowercase_  :						List[Any]=False		,			lowercase_  :						List[str]=1):




          '''simple docstring'''


          self.assertIsInstance(lowercase_		,			lowercase_)
          self.assertListEqual(
              [isinstance(lowercase_		,			lowercase_) for iter_attentions in attentions]		,			[True] * len(lowercase_))
          self.assertEqual(len(lowercase_)		,			(max_length - min_length) * num_beam_groups)

          for idx, iter_attentions in enumerate(lowercase_):
              # adds PAD dummy token
              SCREAMING_SNAKE_CASE_   :						str							=	min_length + idx + 1
              SCREAMING_SNAKE_CASE_   :						int							=	min_length + idx + 1

              SCREAMING_SNAKE_CASE_   :						str							=	(
                  batch_size * num_beam_groups,
                  config.num_attention_heads,
                  tgt_len,
                  src_len,
              )
              # check attn size
              self.assertListEqual(
                  [layer_attention.shape for layer_attention in iter_attentions]		,			[expected_shape] * len(lowercase_))
      def _SCREAMING_SNAKE_CASE				(		self  :						Any		,			lowercase_  :						str		,			lowercase_  :						Optional[Any]		,			lowercase_  :						int		,			lowercase_  :						int		,			lowercase_  :						List[Any]		,			lowercase_  :						Union[str, Any]=False		,			lowercase_  :						Tuple=1):




          '''simple docstring'''


          self.assertIsInstance(lowercase_		,			lowercase_)
          self.assertListEqual(
              [isinstance(lowercase_		,			lowercase_) for iter_hidden_states in hidden_states]		,			[True] * len(lowercase_)		,			)
          self.assertEqual(len(lowercase_)		,			(max_length - min_length) * num_beam_groups)

          for idx, iter_hidden_states in enumerate(lowercase_):
              # adds PAD dummy token
              SCREAMING_SNAKE_CASE_   :						List[str]							=	min_length + idx + 1
              SCREAMING_SNAKE_CASE_   :						List[Any]							=	(batch_size * num_beam_groups, seq_len, config.hidden_size)
              # check hidden size
              self.assertListEqual(
                  [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states]		,			[expected_shape] * len(lowercase_)		,			)
          pass



      @slow
      def _SCREAMING_SNAKE_CASE				(		self  :						Union[str, Any]):




          '''simple docstring'''


          for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              SCREAMING_SNAKE_CASE_   :						int							=	XLMModel.from_pretrained(lowercase_)
              self.assertIsNotNone(lowercase_)




@require_torch
class 							lowerCAmelCase__       (    unittest.TestCase				):






      '''simple docstring'''

      @slow
      def _SCREAMING_SNAKE_CASE				(		self  :						Union[str, Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Tuple							=	XLMWithLMHeadModel.from_pretrained('''xlm-mlm-en-2048''')
          model.to(lowercase_)
          SCREAMING_SNAKE_CASE_   :						Dict							=	torch.tensor([[14, 447]]		,			dtype=torch.long		,			device=lowercase_)  # the president
          SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	[
              14,
              447,
              14,
              447,
              14,
              447,
              14,
              447,
              14,
              447,
              14,
              447,
              14,
              447,
              14,
              447,
              14,
              447,
              14,
              447,
          ]  # the president the president the president the president the president the president the president the president the president the president
          # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference
          SCREAMING_SNAKE_CASE_   :						Tuple							=	model.generate(lowercase_		,			do_sample=lowercase_)
          self.assertListEqual(output_ids[0].cpu().numpy().tolist()		,			lowercase_)













"""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


UpperCAmelCase_     :				str         =				logging.getLogger(__name__)



def       _A    (__a					,       __a					,       __a = None					,       __a = None					,       __a = None					,       __a = None					,       __a = None					,       __a = False					,       )				-> Optional[int]:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						List[Any]							=	bnb_quantization_config.load_in_abit
    SCREAMING_SNAKE_CASE_   :						Dict							=	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.'''							)

    SCREAMING_SNAKE_CASE_   :						str							=	[]
    # custom device map
    if isinstance(__a					,       __a							) and len(device_map.keys()							) > 1:
        SCREAMING_SNAKE_CASE_   :						int							=	[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:
        SCREAMING_SNAKE_CASE_   :						str							=	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							)
    SCREAMING_SNAKE_CASE_   :						Any							=	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:
        SCREAMING_SNAKE_CASE_   :						List[str]							=	[]
    SCREAMING_SNAKE_CASE_   :						Dict							=	bnb_quantization_config.keep_in_fpaa_modules
    modules_to_not_convert.extend(__a							)

    # compatibility with peft
    SCREAMING_SNAKE_CASE_   :						Tuple							=	load_in_abit
    SCREAMING_SNAKE_CASE_   :						Any							=	load_in_abit

    SCREAMING_SNAKE_CASE_   :						Dict							=	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.'''							)
        SCREAMING_SNAKE_CASE_   :						int							=	replace_with_bnb_layers(__a					,       __a					,       modules_to_not_convert=__a							)
        # convert param to the right dtype
        SCREAMING_SNAKE_CASE_   :						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:
                    SCREAMING_SNAKE_CASE_   :						Tuple							=	name.replace('''.weight'''					,       ''''''							).replace('''.bias'''					,       ''''''							)
                    SCREAMING_SNAKE_CASE_   :						List[Any]							=	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():
            SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	replace_with_bnb_layers(
                __a					,       __a					,       modules_to_not_convert=__a							)

        SCREAMING_SNAKE_CASE_   :						List[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():
            SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	True

        SCREAMING_SNAKE_CASE_   :						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    (__a					,       __a					,       __a=None					,       __a=None					,       __a=None							)				-> Union[str, Any]:
    """simple docstring"""






    if device_map is None:
        if torch.cuda.is_available():
            SCREAMING_SNAKE_CASE_   :						Union[str, 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\'.'''							)

        SCREAMING_SNAKE_CASE_   :						str							=	{}
        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							)
            }							)

        SCREAMING_SNAKE_CASE_   :						List[Any]							=	{}
        SCREAMING_SNAKE_CASE_   :						List[str]							=	special_dtypes
        SCREAMING_SNAKE_CASE_   :						List[str]							=	no_split_module_classes
        SCREAMING_SNAKE_CASE_   :						Tuple							=	bnb_quantization_config.target_dtype

        # get max_memory for each device.
        if device_map != "sequential":
            SCREAMING_SNAKE_CASE_   :						str							=	get_balanced_memory(
                __a					,       low_zero=(device_map == '''balanced_low_0''')					,       max_memory=__a					,       **__a					,       )

        SCREAMING_SNAKE_CASE_   :						Optional[int]							=	max_memory
        SCREAMING_SNAKE_CASE_   :						Tuple							=	infer_auto_device_map(__a					,       **__a							)

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

        SCREAMING_SNAKE_CASE_   :						List[Any]							=	{
            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(
                        '''
                        Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit
                        the quantized model. If you want to dispatch the model on the CPU or the disk while keeping
                        these modules in `torch_dtype`, you need to pass a custom `device_map` to
                        `load_and_quantize_model`. Check
                        https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk
                        for more details.
                        '''							)
                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    (__a					,       __a					,       __a=None					,       __a=None							)				-> Optional[Any]:
    """simple docstring"""






    if modules_to_not_convert is None:
        SCREAMING_SNAKE_CASE_   :						List[Any]							=	[]

    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_   :						Optional[int]							=	_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    (__a					,       __a					,       __a=None					,       __a=None					,       )				-> List[Any]:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						List[Any]							=	False
    for name, module in model.named_children():
        if current_key_name is None:
            SCREAMING_SNAKE_CASE_   :						Any							=	[]
        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`
            SCREAMING_SNAKE_CASE_   :						Optional[int]							=	'''.'''.join(__a							)
            SCREAMING_SNAKE_CASE_   :						Dict							=	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:
                    SCREAMING_SNAKE_CASE_   :						List[str]							=	False
                    break
            if proceed:
                # Load bnb module with empty weight and replace ``nn.Linear` module
                if bnb_quantization_config.load_in_abit:
                    SCREAMING_SNAKE_CASE_   :						Tuple							=	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:
                    SCREAMING_SNAKE_CASE_   :						Tuple							=	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'''							)
                SCREAMING_SNAKE_CASE_   :						int							=	module.weight.data
                if module.bias is not None:
                    SCREAMING_SNAKE_CASE_   :						str							=	module.bias.data
                bnb_module.requires_grad_(__a							)
                setattr(__a					,       __a					,       __a							)
                SCREAMING_SNAKE_CASE_   :						List[Any]							=	True
        if len(list(module.children()							)							) > 0:
            SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	_replace_with_bnb_layers(
                __a					,       __a					,       __a					,       __a							)
            SCREAMING_SNAKE_CASE_   :						List[Any]							=	has_been_replaced | _has_been_replaced
        # Remove the last key for recursion
        current_key_name.pop(-1							)
    return model, has_been_replaced



def       _A    (__a							)				-> List[str]:
    """simple docstring"""






    with init_empty_weights():
        SCREAMING_SNAKE_CASE_   :						Any							=	deepcopy(__a							)  # this has 0 cost since it is done inside `init_empty_weights` context manager`

    SCREAMING_SNAKE_CASE_   :						List[str]							=	find_tied_parameters(__a							)
    # For compatibility with Accelerate < 0.18
    if isinstance(__a					,       __a							):
        SCREAMING_SNAKE_CASE_   :						Tuple							=	sum(list(tied_params.values()							)					,       []							) + list(tied_params.keys()							)
    else:
        SCREAMING_SNAKE_CASE_   :						Dict							=	sum(__a					,       []							)
    SCREAMING_SNAKE_CASE_   :						int							=	len(__a							) > 0

    # Check if it is a base model
    SCREAMING_SNAKE_CASE_   :						str							=	False
    if hasattr(__a					,       '''base_model_prefix'''							):
        SCREAMING_SNAKE_CASE_   :						str							=	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
    SCREAMING_SNAKE_CASE_   :						int							=	list(model.named_children()							)
    SCREAMING_SNAKE_CASE_   :						List[Any]							=	[list_modules[-1][0]]

    # add last module together with tied weights
    SCREAMING_SNAKE_CASE_   :						str							=	set(__a							) - set(__a							)
    SCREAMING_SNAKE_CASE_   :						List[str]							=	list(set(__a							)							) + list(__a							)

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

    return filtered_module_names



def       _A    (__a							)				-> Union[str, Any]:
    """simple docstring"""






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



def       _A    (__a							)				-> Dict:
    """simple docstring"""






    return next(parameter.parameters()							).device





def       _A    (__a					,       __a					,       __a					,       __a					,       __a					,       __a					,       __a							)				-> Tuple:
    """simple docstring"""






    if fpaa_statistics is None:
        set_module_tensor_to_device(__a					,       __a					,       0					,       dtype=__a					,       value=__a							)
        SCREAMING_SNAKE_CASE_   :						str							=	param_name
        SCREAMING_SNAKE_CASE_   :						List[str]							=	model
        if "." in tensor_name:
            SCREAMING_SNAKE_CASE_   :						str							=	tensor_name.split('''.'''							)
            for split in splits[:-1]:
                SCREAMING_SNAKE_CASE_   :						Any							=	getattr(__a					,       __a							)
                if new_module is None:
                    raise ValueError(f'{module} has no attribute {split}.'							)
                SCREAMING_SNAKE_CASE_   :						Optional[int]							=	new_module
            SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	splits[-1]
        # offload weights
        SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	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()							)							)


