
from typing import Any, Dict, List, Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_vision_available():
     from PIL import Image

     from ..image_utils import load_image

if is_torch_available():
     import torch

     from transformers.modeling_outputs import BaseModelOutput

     from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

lowerCamelCase__     :		Optional[Any]        = logging.get_logger(__name__)



@add_end_docstrings(UpperCAmelCase_				)
class    _snake_case (						UpperCAmelCase_				):


 def __init__(       self       ,	**SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   super().__init__(**SCREAMING_SNAKE_CASE_)

   if self.framework == "tf":
     raise ValueError(f'The {self.__class__} is only available in PyTorch.')

   requires_backends(self       ,	"""vision""")
   self.check_model_type(SCREAMING_SNAKE_CASE_)


 def __call__(       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_ = None       ,	**SCREAMING_SNAKE_CASE_       ,	):


   '''simple docstring'''




   if "text_queries" in kwargs:
     lowercase__	: Any     		=   kwargs.pop("""text_queries""")

   if isinstance(SCREAMING_SNAKE_CASE_       ,	(str, Image.Image)):
     lowercase__	: Optional[Any]     		=   {"""image""": image, """candidate_labels""": candidate_labels}
   else:
     lowercase__	: int     		=   image
   lowercase__	: List[str]     		=   super().__call__(SCREAMING_SNAKE_CASE_       ,	**SCREAMING_SNAKE_CASE_)
   return results


 def   lowercase__  (       self       ,	**SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: Tuple     		=   {}
   if "threshold" in kwargs:
     lowercase__	: List[Any]     		=   kwargs["""threshold"""]
   if "top_k" in kwargs:
     lowercase__	: int     		=   kwargs["""top_k"""]
   return {}, {}, postprocess_params


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: str     		=   load_image(inputs["""image"""])
   lowercase__	: Any     		=   inputs["""candidate_labels"""]
   if isinstance(SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_):
     lowercase__	: List[str]     		=   candidate_labels.split(""",""")

   lowercase__	: Tuple     		=   torch.tensor([[image.height, image.width]]       ,	dtype=torch.intaa)
   for i, candidate_label in enumerate(SCREAMING_SNAKE_CASE_):
     lowercase__	: Optional[Any]     		=   self.tokenizer(SCREAMING_SNAKE_CASE_       ,	return_tensors=self.framework)
     lowercase__	: Union[str, Any]     		=   self.image_processor(SCREAMING_SNAKE_CASE_       ,	return_tensors=self.framework)
     yield {
         "is_last": i == len(SCREAMING_SNAKE_CASE_) - 1,
         "target_size": target_size,
         "candidate_label": candidate_label,
         **text_inputs,
         **image_features,
     }


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: str     		=   model_inputs.pop("""target_size""")
   lowercase__	: Optional[int]     		=   model_inputs.pop("""candidate_label""")
   lowercase__	: Dict     		=   model_inputs.pop("""is_last""")

   lowercase__	: Union[str, Any]     		=   self.model(**SCREAMING_SNAKE_CASE_)

   lowercase__	: Union[str, Any]     		=   {"""target_size""": target_size, """candidate_label""": candidate_label, """is_last""": is_last, **outputs}
   return model_outputs


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_=0.1       ,	SCREAMING_SNAKE_CASE_=None):


   '''simple docstring'''




   lowercase__	: Union[str, Any]     		=   []
   for model_output in model_outputs:
     lowercase__	: Optional[int]     		=   model_output["""candidate_label"""]
     lowercase__	: Tuple     		=   BaseModelOutput(SCREAMING_SNAKE_CASE_)
     lowercase__	: List[str]     		=   self.image_processor.post_process_object_detection(
         outputs=SCREAMING_SNAKE_CASE_       ,	threshold=SCREAMING_SNAKE_CASE_       ,	target_sizes=model_output["""target_size"""])[0]

     for index in outputs["scores"].nonzero():
       lowercase__	: Optional[Any]     		=   outputs["""scores"""][index].item()
       lowercase__	: Optional[Any]     		=   self._get_bounding_box(outputs["""boxes"""][index][0])

       lowercase__	: Tuple     		=   {"""score""": score, """label""": label, """box""": box}
       results.append(SCREAMING_SNAKE_CASE_)

   lowercase__	: int     		=   sorted(SCREAMING_SNAKE_CASE_       ,	key=lambda SCREAMING_SNAKE_CASE_: x["score"]       ,	reverse=SCREAMING_SNAKE_CASE_)
   if top_k:
     lowercase__	: Any     		=   results[:top_k]

   return results



 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   if self.framework != "pt":
     raise ValueError("""The ZeroShotObjectDetectionPipeline is only available in PyTorch.""")
   lowercase__		,     lowercase__		,     lowercase__		,     lowercase__	: List[Any]     		=   box.int().tolist()
   lowercase__	: Optional[int]     		=   {
       """xmin""": xmin,
       """ymin""": ymin,
       """xmax""": xmax,
       """ymax""": ymax,
   }
   return bbox










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:
       def __init__(   self, lowerCamelCase, lowerCamelCase=13, lowerCamelCase=7, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=False, lowerCamelCase=False, lowerCamelCase=False, lowerCamelCase=2, lowerCamelCase=99, lowerCamelCase=0, lowerCamelCase=32, lowerCamelCase=5, lowerCamelCase=4, lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=5_12, lowerCamelCase=2, lowerCamelCase=0.0_2, lowerCamelCase=2, lowerCamelCase=4, lowerCamelCase="last", lowerCamelCase=True, lowerCamelCase=None, lowerCamelCase=0, )			->  str:




           """simple docstring"""

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




           """simple docstring"""

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

           _lowercase			:				int 						=						None
           if self.use_input_lengths:
               _lowercase			:				Dict 						=						(
                   ids_tensor([self.batch_size], vocab_size=2) + self.seq_length - 2
               )  # small variation of seq_length

           _lowercase			:				Tuple 						=						None
           if self.use_token_type_ids:
               _lowercase			:				Optional[Any] 						=						ids_tensor([self.batch_size, self.seq_length], self.n_langs)

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

           _lowercase			:				Dict 						=						self.get_config()

           return (
               config,
               input_ids,
               token_type_ids,
               input_lengths,
               sequence_labels,
               token_labels,
               is_impossible_labels,
               choice_labels,
               input_mask,
           )
       def      UpperCamelCase	(   self)			->  Union[str, 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      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  Tuple:




           """simple docstring"""

           _lowercase			:				List[Any] 						=						XLMModel(config=lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase			:				str 						=						model(lowerCamelCase, lengths=lowerCamelCase, langs=lowerCamelCase)
           _lowercase			:				int 						=						model(lowerCamelCase, langs=lowerCamelCase)
           _lowercase			:				Any 						=						model(lowerCamelCase)
           self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  List[Any]:




           """simple docstring"""

           _lowercase			:				Dict 						=						XLMWithLMHeadModel(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()

           _lowercase			:				int 						=						model(lowerCamelCase, token_type_ids=lowerCamelCase, labels=lowerCamelCase)
           self.parent.assertEqual(result.loss.shape, ())
           self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  str:




           """simple docstring"""

           _lowercase			:				Tuple 						=						XLMForQuestionAnsweringSimple(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()

           _lowercase			:				Dict 						=						model(lowerCamelCase)

           _lowercase			:				List[str] 						=						model(lowerCamelCase, start_positions=lowerCamelCase, end_positions=lowerCamelCase)
           _lowercase			:				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      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  Union[str, Any]:




           """simple docstring"""

           _lowercase			:				Tuple 						=						XLMForQuestionAnswering(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()

           _lowercase			:				Optional[Any] 						=						model(lowerCamelCase)

           _lowercase			:				List[Any] 						=						model(
               lowerCamelCase, start_positions=lowerCamelCase, end_positions=lowerCamelCase, cls_index=lowerCamelCase, is_impossible=lowerCamelCase, p_mask=lowerCamelCase, )

           _lowercase			:				List[str] 						=						model(
               lowerCamelCase, start_positions=lowerCamelCase, end_positions=lowerCamelCase, cls_index=lowerCamelCase, is_impossible=lowerCamelCase, )

           ((_lowercase)						,							)			:				Optional[Any] 						=						result_with_labels.to_tuple()

           _lowercase			:				List[str] 						=						model(lowerCamelCase, start_positions=lowerCamelCase, end_positions=lowerCamelCase)

           ((_lowercase)						,							)			:				Any 						=						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      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  int:




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						XLMForSequenceClassification(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()

           _lowercase			:				Optional[int] 						=						model(lowerCamelCase)
           _lowercase			:				Optional[int] 						=						model(lowerCamelCase, labels=lowerCamelCase)
           self.parent.assertEqual(result.loss.shape, ())
           self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  List[str]:




           """simple docstring"""

           _lowercase			:				Any 						=						self.num_labels
           _lowercase			:				str 						=						XLMForTokenClassification(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()

           _lowercase			:				int 						=						model(lowerCamelCase, attention_mask=lowerCamelCase, labels=lowerCamelCase)
           self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, )			->  Dict:




           """simple docstring"""

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




       def      UpperCamelCase	(   self)			->  Tuple:




           """simple docstring"""

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






@require_torch
class _lowerCamelCase(		_a,					_a,					_a,					unittest.TestCase  ):
       lowercase_					:      Any       					=     (
           (
               XLMModel,
               XLMWithLMHeadModel,
               XLMForQuestionAnswering,
               XLMForSequenceClassification,
               XLMForQuestionAnsweringSimple,
               XLMForTokenClassification,
               XLMForMultipleChoice,
           )
           if is_torch_available()
           else ()
       )
       lowercase_					:      Optional[int]       					=     (
           (XLMWithLMHeadModel,) if is_torch_available() else ()
       )  # TODO (PVP): Check other models whether language generation is also applicable
       lowercase_					:      Union[str, Any]       					=     (
           {
               """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      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  Optional[int]:




           """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      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase=False)			->  Optional[int]:




           """simple docstring"""

           _lowercase			:				Any 						=						super()._prepare_for_class(lowerCamelCase, lowerCamelCase, return_labels=lowerCamelCase)

           if return_labels:
               if model_class.__name__ == "XLMForQuestionAnswering":
                   _lowercase			:				Any 						=						torch.zeros(
                       self.model_tester.batch_size, dtype=torch.long, device=lowerCamelCase)
                   _lowercase			:				Dict 						=						torch.zeros(
                       self.model_tester.batch_size, dtype=torch.long, device=lowerCamelCase)

           return inputs_dict
       def      UpperCamelCase	(   self)			->  int:




           """simple docstring"""

           _lowercase			:				Union[str, Any] 						=						XLMModelTester(self)
           _lowercase			:				List[str] 						=						ConfigTester(self, config_class=lowerCamelCase, emb_dim=37)
       def      UpperCamelCase	(   self)			->  Tuple:




           """simple docstring"""

           self.config_tester.run_common_tests()
       def      UpperCamelCase	(   self)			->  List[Any]:




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_model(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  List[str]:




           """simple docstring"""

           _lowercase			:				str 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_lm_head(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Optional[Any]:




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_simple_qa(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  int:




           """simple docstring"""

           _lowercase			:				str 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_qa(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  List[str]:




           """simple docstring"""

           _lowercase			:				Dict 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_sequence_classif(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Dict:




           """simple docstring"""

           _lowercase			:				Union[str, Any] 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_token_classif(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Any:




           """simple docstring"""

           _lowercase			:				str 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_xlm_for_multiple_choice(*lowerCamelCase)
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=False, lowerCamelCase=1)			->  int:




           """simple docstring"""

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

           for idx, iter_attentions in enumerate(lowerCamelCase):
               # adds PAD dummy token
               _lowercase			:				Dict 						=						min_length + idx + 1
               _lowercase			:				int 						=						min_length + idx + 1

               _lowercase			:				Dict 						=						(
                   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(lowerCamelCase))
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=False, lowerCamelCase=1)			->  List[Any]:




           """simple docstring"""

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

           for idx, iter_hidden_states in enumerate(lowerCamelCase):
               # adds PAD dummy token
               _lowercase			:				int 						=						min_length + idx + 1
               _lowercase			:				int 						=						(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(lowerCamelCase), )
           pass




       @slow
       def      UpperCamelCase	(   self)			->  int:




           """simple docstring"""

           for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _lowercase			:				Dict 						=						XLMModel.from_pretrained(lowerCamelCase)
               self.assertIsNotNone(lowerCamelCase)






@require_torch
class _lowerCamelCase(		unittest.TestCase  ):
       @slow
       def      UpperCamelCase	(   self)			->  Union[str, Any]:




           """simple docstring"""

           _lowercase			:				Tuple 						=						XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048')
           model.to(lowerCamelCase)
           _lowercase			:				Union[str, Any] 						=						torch.tensor([[14, 4_47]], dtype=torch.long, device=lowerCamelCase)  # the president
           _lowercase			:				Any 						=						[
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
               14,
               4_47,
           ]  # 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
           _lowercase			:				str 						=						model.generate(lowerCamelCase, do_sample=lowerCamelCase)
           self.assertListEqual(output_ids[0].cpu().numpy().tolist(), lowerCamelCase)


