'''simple docstring'''


from typing import Dict, Optional

import numpy as np

import datasets


snake_case__					:      Dict				      =  '''
IoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union
between the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,
the mean IoU of the image is calculated by taking the IoU of each class and averaging them.
'''

snake_case__					:      Union[str, Any]				      =  '''
Args:
    predictions (`List[ndarray]`):
        List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.
    references (`List[ndarray]`):
        List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.
    num_labels (`int`):
        Number of classes (categories).
    ignore_index (`int`):
        Index that will be ignored during evaluation.
    nan_to_num (`int`, *optional*):
        If specified, NaN values will be replaced by the number defined by the user.
    label_map (`dict`, *optional*):
        If specified, dictionary mapping old label indices to new label indices.
    reduce_labels (`bool`, *optional*, defaults to `False`):
        Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,
        and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.

Returns:
    `Dict[str, float | ndarray]` comprising various elements:
    - *mean_iou* (`float`):
        Mean Intersection-over-Union (IoU averaged over all categories).
    - *mean_accuracy* (`float`):
        Mean accuracy (averaged over all categories).
    - *overall_accuracy* (`float`):
        Overall accuracy on all images.
    - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):
        Per category accuracy.
    - *per_category_iou* (`ndarray` of shape `(num_labels,)`):
        Per category IoU.

Examples:

    >>> import numpy as np

    >>> mean_iou = datasets.load_metric("mean_iou")

    >>> # suppose one has 3 different segmentation maps predicted
    >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])
    >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])

    >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])
    >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])

    >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])
    >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])

    >>> predicted = [predicted_1, predicted_2, predicted_3]
    >>> ground_truth = [actual_1, actual_2, actual_3]

    >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)
    >>> print(results) # doctest: +NORMALIZE_WHITESPACE
    {\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0.   , 0.   , 0.375, 0.4  , 0.5  , 0.   , 0.5  , 1.   , 1.   , 1.   ]), \'per_category_accuracy\': array([0.        , 0.        , 0.75      , 0.66666667, 1.        , 0.        , 0.5       , 1.        , 1.        , 1.        ])}
'''

snake_case__					:      Union[str, Any]				      =  '''\
@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,
author = {{MMSegmentation Contributors}},
license = {Apache-2.0},
month = {7},
title = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},
url = {https://github.com/open-mmlab/mmsegmentation},
year = {2020}
}'''


def  _lowerCamelCase   (				lowerCamelCase_ :							Tuple     ,					lowerCamelCase_ :							Any     ,					lowerCamelCase_ :							Optional[Any]     ,					lowerCamelCase_ :							bool     ,					lowerCamelCase_ :							Optional[Dict[int, int]] = None     ,					lowerCamelCase_ :							bool = False     ,					):



     """simple docstring"""





     if label_map is not None:
          for old_id, new_id in label_map.items():
               UpperCAmelCase_							:       List[str]       =				new_id

    # turn into Numpy arrays
     UpperCAmelCase_							:       str       =				np.array(lowerCamelCase_       )
     UpperCAmelCase_							:       int       =				np.array(lowerCamelCase_       )

     if reduce_labels:
          UpperCAmelCase_							:       Optional[Any]       =				255
          UpperCAmelCase_							:       List[str]       =				label - 1
          UpperCAmelCase_							:       Dict       =				255

     UpperCAmelCase_							:       Dict       =				label != ignore_index
     UpperCAmelCase_							:       List[str]       =				np.not_equal(lowerCamelCase_     ,					lowerCamelCase_       )
     UpperCAmelCase_							:       List[str]       =				pred_label[mask]
     UpperCAmelCase_							:       str       =				np.array(lowerCamelCase_       )[mask]

     UpperCAmelCase_							:       Any       =				pred_label[pred_label == label]

     UpperCAmelCase_							:       Any       =				np.histogram(lowerCamelCase_     ,					bins=lowerCamelCase_     ,					range=(0, num_labels - 1)       )[0]
     UpperCAmelCase_							:       Optional[int]       =				np.histogram(lowerCamelCase_     ,					bins=lowerCamelCase_     ,					range=(0, num_labels - 1)       )[0]
     UpperCAmelCase_							:       Optional[int]       =				np.histogram(lowerCamelCase_     ,					bins=lowerCamelCase_     ,					range=(0, num_labels - 1)       )[0]

     UpperCAmelCase_							:       Optional[Any]       =				area_pred_label + area_label - area_intersect

     return area_intersect, area_union, area_pred_label, area_label


def  _lowerCamelCase   (				lowerCamelCase_ :							Union[str, Any]     ,					lowerCamelCase_ :							Optional[Any]     ,					lowerCamelCase_ :							List[Any]     ,					lowerCamelCase_ :							bool     ,					lowerCamelCase_ :							Optional[Dict[int, int]] = None     ,					lowerCamelCase_ :							bool = False     ,					):



     """simple docstring"""





     UpperCAmelCase_							:       Optional[int]       =				np.zeros((num_labels,)     ,					dtype=np.floataa       )
     UpperCAmelCase_							:       Optional[int]       =				np.zeros((num_labels,)     ,					dtype=np.floataa       )
     UpperCAmelCase_							:       List[str]       =				np.zeros((num_labels,)     ,					dtype=np.floataa       )
     UpperCAmelCase_							:       Union[str, Any]       =				np.zeros((num_labels,)     ,					dtype=np.floataa       )
     for result, gt_seg_map in zip(lowerCamelCase_     ,					lowerCamelCase_       ):
          UpperCAmelCase_       ,      UpperCAmelCase_       ,      UpperCAmelCase_       ,      UpperCAmelCase_							:       int       =				intersect_and_union(
              lowerCamelCase_     ,					lowerCamelCase_     ,					lowerCamelCase_     ,					lowerCamelCase_     ,					lowerCamelCase_     ,					lowerCamelCase_       )
          total_area_intersect += area_intersect
          total_area_union += area_union
          total_area_pred_label += area_pred_label
          total_area_label += area_label
     return total_area_intersect, total_area_union, total_area_pred_label, total_area_label


def  _lowerCamelCase   (				lowerCamelCase_ :							Optional[Any]     ,					lowerCamelCase_ :							Optional[Any]     ,					lowerCamelCase_ :							Tuple     ,					lowerCamelCase_ :							bool     ,					lowerCamelCase_ :							Optional[int] = None     ,					lowerCamelCase_ :							Optional[Dict[int, int]] = None     ,					lowerCamelCase_ :							bool = False     ,					):



     """simple docstring"""





     UpperCAmelCase_       ,      UpperCAmelCase_       ,      UpperCAmelCase_       ,      UpperCAmelCase_							:       Tuple       =				total_intersect_and_union(
         lowerCamelCase_     ,					lowerCamelCase_     ,					lowerCamelCase_     ,					lowerCamelCase_     ,					lowerCamelCase_     ,					lowerCamelCase_       )

     # compute metrics
     UpperCAmelCase_							:       int       =				{}

     UpperCAmelCase_							:       List[Any]       =				total_area_intersect.sum() / total_area_label.sum()
     UpperCAmelCase_							:       int       =				total_area_intersect / total_area_union
     UpperCAmelCase_							:       Tuple       =				total_area_intersect / total_area_label

     UpperCAmelCase_							:       Tuple       =				np.nanmean(lowerCamelCase_       )
     UpperCAmelCase_							:       Dict       =				np.nanmean(lowerCamelCase_       )
     UpperCAmelCase_							:       str       =				all_acc
     UpperCAmelCase_							:       List[str]       =				iou
     UpperCAmelCase_							:       List[Any]       =				acc

     if nan_to_num is not None:
          UpperCAmelCase_							:       int       =				{metric: np.nan_to_num(lowerCamelCase_     ,					nan=lowerCamelCase_       ) for metric, metric_value in metrics.items()}

     return metrics






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,     _KWARGS_DESCRIPTION	)
class 					__SCREAMING_SNAKE_CASE						(	datasets.Metric	):







  '''simple docstring'''






  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       return datasets.MetricInfo(
           description=_DESCRIPTION				,		citation=_CITATION				,		inputs_description=_KWARGS_DESCRIPTION				,		features=datasets.Features(
               # 1st Seq - height dim, 2nd - width dim
               {
                   'predictions': datasets.Sequence(datasets.Sequence(datasets.Value('uint16'						)						)						),
                   'references': datasets.Sequence(datasets.Sequence(datasets.Value('uint16'						)						)						),
               }						)				,		reference_urls=[
               'https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py'
           ]				,		)






  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_ = None				,		snake_case_ = None				,		snake_case_ = False				,		):




       '''simple docstring'''

       UpperCAmelCase_							:       int       =				mean_iou(
           results=snake_case_				,		gt_seg_maps=snake_case_				,		num_labels=snake_case_				,		ignore_index=snake_case_				,		nan_to_num=snake_case_				,		label_map=snake_case_				,		reduce_labels=snake_case_				,		)
       return iou_result







'''simple docstring'''


import unittest

from parameterized import parameterized

from transformers import OpenLlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, 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 OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel






class 					__SCREAMING_SNAKE_CASE						:







  '''simple docstring'''






  def __init__(			self				,		snake_case_				,		snake_case_=1_3				,		snake_case_=7				,		snake_case_=True				,		snake_case_=True				,		snake_case_=False				,		snake_case_=True				,		snake_case_=9_9				,		snake_case_=3_2				,		snake_case_=5				,		snake_case_=4				,		snake_case_=3_7				,		snake_case_="gelu"				,		snake_case_=0.1				,		snake_case_=0.1				,		snake_case_=5_1_2				,		snake_case_=1_6				,		snake_case_=2				,		snake_case_=0.02				,		snake_case_=3				,		snake_case_=4				,		snake_case_=None				,		):




       '''simple docstring'''

       UpperCAmelCase_							:       Union[str, Any]       =				parent
       UpperCAmelCase_							:       List[str]       =				batch_size
       UpperCAmelCase_							:       Dict       =				seq_length
       UpperCAmelCase_							:       Any       =				is_training
       UpperCAmelCase_							:       List[Any]       =				use_input_mask
       UpperCAmelCase_							:       Tuple       =				use_token_type_ids
       UpperCAmelCase_							:       Tuple       =				use_labels
       UpperCAmelCase_							:       Dict       =				vocab_size
       UpperCAmelCase_							:       Union[str, Any]       =				hidden_size
       UpperCAmelCase_							:       Optional[Any]       =				num_hidden_layers
       UpperCAmelCase_							:       Union[str, Any]       =				num_attention_heads
       UpperCAmelCase_							:       Optional[int]       =				intermediate_size
       UpperCAmelCase_							:       Dict       =				hidden_act
       UpperCAmelCase_							:       Any       =				hidden_dropout_prob
       UpperCAmelCase_							:       Optional[Any]       =				attention_probs_dropout_prob
       UpperCAmelCase_							:       Optional[int]       =				max_position_embeddings
       UpperCAmelCase_							:       List[Any]       =				type_vocab_size
       UpperCAmelCase_							:       Optional[Any]       =				type_sequence_label_size
       UpperCAmelCase_							:       List[Any]       =				initializer_range
       UpperCAmelCase_							:       List[Any]       =				num_labels
       UpperCAmelCase_							:       Any       =				num_choices
       UpperCAmelCase_							:       List[str]       =				scope


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

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

       UpperCAmelCase_							:       List[str]       =				None
       if self.use_input_mask:
            UpperCAmelCase_							:       Optional[int]       =				random_attention_mask([self.batch_size, self.seq_length]						)

       UpperCAmelCase_							:       int       =				None
       if self.use_token_type_ids:
            UpperCAmelCase_							:       Dict       =				ids_tensor([self.batch_size, self.seq_length]				,		self.type_vocab_size						)

       UpperCAmelCase_							:       Tuple       =				None
       UpperCAmelCase_							:       Any       =				None
       UpperCAmelCase_							:       str       =				None
       if self.use_labels:
            UpperCAmelCase_							:       str       =				ids_tensor([self.batch_size]				,		self.type_sequence_label_size						)
            UpperCAmelCase_							:       Optional[int]       =				ids_tensor([self.batch_size, self.seq_length]				,		self.num_labels						)
            UpperCAmelCase_							:       Any       =				ids_tensor([self.batch_size]				,		self.num_choices						)

       UpperCAmelCase_							:       int       =				self.get_config()

       return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       return OpenLlamaConfig(
           vocab_size=self.vocab_size				,		hidden_size=self.hidden_size				,		num_hidden_layers=self.num_hidden_layers				,		num_attention_heads=self.num_attention_heads				,		intermediate_size=self.intermediate_size				,		hidden_act=self.hidden_act				,		hidden_dropout_prob=self.hidden_dropout_prob				,		attention_probs_dropout_prob=self.attention_probs_dropout_prob				,		max_position_embeddings=self.max_position_embeddings				,		type_vocab_size=self.type_vocab_size				,		is_decoder=snake_case_				,		initializer_range=self.initializer_range				,		use_stable_embedding=snake_case_				,		)


  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_						):




       '''simple docstring'''

       UpperCAmelCase_							:       str       =				OpenLlamaModel(config=snake_case_						)
       model.to(snake_case_						)
       model.eval()
       UpperCAmelCase_							:       str       =				model(snake_case_				,		attention_mask=snake_case_						)
       UpperCAmelCase_							:       Dict       =				model(snake_case_						)
       self.parent.assertEqual(result.last_hidden_state.shape				,		(self.batch_size, self.seq_length, self.hidden_size)						)


  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		):




       '''simple docstring'''

       UpperCAmelCase_							:       List[Any]       =				True
       UpperCAmelCase_							:       Dict       =				OpenLlamaModel(snake_case_						)
       model.to(snake_case_						)
       model.eval()
       UpperCAmelCase_							:       Optional[Any]       =				model(
           snake_case_				,		attention_mask=snake_case_				,		encoder_hidden_states=snake_case_				,		encoder_attention_mask=snake_case_				,		)
       UpperCAmelCase_							:       Any       =				model(
           snake_case_				,		attention_mask=snake_case_				,		encoder_hidden_states=snake_case_				,		)
       UpperCAmelCase_							:       Optional[Any]       =				model(snake_case_				,		attention_mask=snake_case_						)
       self.parent.assertEqual(result.last_hidden_state.shape				,		(self.batch_size, self.seq_length, self.hidden_size)						)


  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		):




       '''simple docstring'''

       UpperCAmelCase_							:       Optional[Any]       =				OpenLlamaForCausalLM(config=snake_case_						)
       model.to(snake_case_						)
       model.eval()
       UpperCAmelCase_							:       Union[str, Any]       =				model(snake_case_				,		attention_mask=snake_case_				,		labels=snake_case_						)
       self.parent.assertEqual(result.logits.shape				,		(self.batch_size, self.seq_length, self.vocab_size)						)


  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		):




       '''simple docstring'''

       UpperCAmelCase_							:       Optional[Any]       =				True
       UpperCAmelCase_							:       List[Any]       =				True
       UpperCAmelCase_							:       Tuple       =				OpenLlamaForCausalLM(config=snake_case_						)
       model.to(snake_case_						)
       model.eval()

       # first forward pass
       UpperCAmelCase_							:       Tuple       =				model(
           snake_case_				,		attention_mask=snake_case_				,		encoder_hidden_states=snake_case_				,		encoder_attention_mask=snake_case_				,		use_cache=snake_case_				,		)
       UpperCAmelCase_							:       int       =				outputs.past_key_values

       # create hypothetical multiple next token and extent to next_input_ids
       UpperCAmelCase_							:       Optional[int]       =				ids_tensor((self.batch_size, 3)				,		config.vocab_size						)
       UpperCAmelCase_							:       Optional[int]       =				ids_tensor((self.batch_size, 3)				,		vocab_size=2						)

       # append to next input_ids and
       UpperCAmelCase_							:       Union[str, Any]       =				torch.cat([input_ids, next_tokens]				,		dim=-1						)
       UpperCAmelCase_							:       Tuple       =				torch.cat([input_mask, next_mask]				,		dim=-1						)

       UpperCAmelCase_							:       List[Any]       =				model(
           snake_case_				,		attention_mask=snake_case_				,		encoder_hidden_states=snake_case_				,		encoder_attention_mask=snake_case_				,		output_hidden_states=snake_case_				,		)['hidden_states'][0]
       UpperCAmelCase_							:       List[str]       =				model(
           snake_case_				,		attention_mask=snake_case_				,		encoder_hidden_states=snake_case_				,		encoder_attention_mask=snake_case_				,		past_key_values=snake_case_				,		output_hidden_states=snake_case_				,		)['hidden_states'][0]

       # select random slice
       UpperCAmelCase_							:       Union[str, Any]       =				ids_tensor((1,)				,		output_from_past.shape[-1]						).item()
       UpperCAmelCase_							:       List[Any]       =				output_from_no_past[:, -3:, random_slice_idx].detach()
       UpperCAmelCase_							:       Optional[Any]       =				output_from_past[:, :, random_slice_idx].detach()

       self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]						)

       # test that outputs are equal for slice
       self.parent.assertTrue(torch.allclose(snake_case_				,		snake_case_				,		atol=1E-3						)						)






  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_							:       int       =				self.prepare_config_and_inputs()
       (
           (
           UpperCAmelCase_
       )       ,      (
           UpperCAmelCase_
       )       ,      (
           UpperCAmelCase_
       )       ,      (
           UpperCAmelCase_
       )       ,      (
           UpperCAmelCase_
       )       ,      (
           UpperCAmelCase_
       )       ,      (
           UpperCAmelCase_
       )       ,      
       )							:       Tuple       =				config_and_inputs
       UpperCAmelCase_							:       List[Any]       =				{'input_ids': input_ids, 'attention_mask': input_mask}
       return config, inputs_dict







@require_torch
class 					__SCREAMING_SNAKE_CASE						(	lowerCamelCase_						,     lowerCamelCase_						,     lowerCamelCase_						,     unittest.TestCase	):







  '''simple docstring'''






  lowerCamelCase_		:Tuple						   =		(
      (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
  )
  lowerCamelCase_		:Tuple						   =		(OpenLlamaForCausalLM,) if is_torch_available() else ()
  lowerCamelCase_		:Union[str, Any]						   =		(
      {
          '''feature-extraction''': OpenLlamaModel,
          '''text-classification''': OpenLlamaForSequenceClassification,
          '''text-generation''': OpenLlamaForCausalLM,
          '''zero-shot''': OpenLlamaForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )
  lowerCamelCase_		:str						   =		False
  lowerCamelCase_		:Optional[int]						   =		False


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_							:       List[str]       =				OpenLlamaModelTester(self						)
       UpperCAmelCase_							:       List[Any]       =				ConfigTester(self				,		config_class=snake_case_				,		hidden_size=3_7						)


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       self.config_tester.run_common_tests()


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_							:       Any       =				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*snake_case_						)


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_							:       Optional[int]       =				self.model_tester.prepare_config_and_inputs()
       for type in ["absolute", "relative_key", "relative_key_query"]:
            UpperCAmelCase_							:       int       =				type
            self.model_tester.create_and_check_model(*snake_case_						)


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_       ,      UpperCAmelCase_							:       List[Any]       =				self.model_tester.prepare_config_and_inputs_for_common()
       UpperCAmelCase_							:       Optional[Any]       =				3
       UpperCAmelCase_							:       Union[str, Any]       =				input_dict['input_ids']
       UpperCAmelCase_							:       int       =				input_ids.ne(1						).to(snake_case_						)
       UpperCAmelCase_							:       str       =				ids_tensor([self.model_tester.batch_size]				,		self.model_tester.type_sequence_label_size						)
       UpperCAmelCase_							:       Any       =				OpenLlamaForSequenceClassification(snake_case_						)
       model.to(snake_case_						)
       model.eval()
       UpperCAmelCase_							:       Optional[Any]       =				model(snake_case_				,		attention_mask=snake_case_				,		labels=snake_case_						)
       self.assertEqual(result.logits.shape				,		(self.model_tester.batch_size, self.model_tester.num_labels)						)


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_       ,      UpperCAmelCase_							:       Any       =				self.model_tester.prepare_config_and_inputs_for_common()
       UpperCAmelCase_							:       List[str]       =				3
       UpperCAmelCase_							:       str       =				'single_label_classification'
       UpperCAmelCase_							:       List[str]       =				input_dict['input_ids']
       UpperCAmelCase_							:       Optional[Any]       =				input_ids.ne(1						).to(snake_case_						)
       UpperCAmelCase_							:       List[str]       =				ids_tensor([self.model_tester.batch_size]				,		self.model_tester.type_sequence_label_size						)
       UpperCAmelCase_							:       Optional[int]       =				OpenLlamaForSequenceClassification(snake_case_						)
       model.to(snake_case_						)
       model.eval()
       UpperCAmelCase_							:       List[Any]       =				model(snake_case_				,		attention_mask=snake_case_				,		labels=snake_case_						)
       self.assertEqual(result.logits.shape				,		(self.model_tester.batch_size, self.model_tester.num_labels)						)


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_       ,      UpperCAmelCase_							:       Optional[int]       =				self.model_tester.prepare_config_and_inputs_for_common()
       UpperCAmelCase_							:       List[str]       =				3
       UpperCAmelCase_							:       int       =				'multi_label_classification'
       UpperCAmelCase_							:       Dict       =				input_dict['input_ids']
       UpperCAmelCase_							:       int       =				input_ids.ne(1						).to(snake_case_						)
       UpperCAmelCase_							:       str       =				ids_tensor(
           [self.model_tester.batch_size, config.num_labels]				,		self.model_tester.type_sequence_label_size						).to(torch.float						)
       UpperCAmelCase_							:       Union[str, Any]       =				OpenLlamaForSequenceClassification(snake_case_						)
       model.to(snake_case_						)
       model.eval()
       UpperCAmelCase_							:       Optional[Any]       =				model(snake_case_				,		attention_mask=snake_case_				,		labels=snake_case_						)
       self.assertEqual(result.logits.shape				,		(self.model_tester.batch_size, self.model_tester.num_labels)						)


  @unittest.skip('Open-Llama buffers include complex numbers, which breaks this test'						)
  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       pass






  @parameterized.expand([('linear',), ('dynamic',)]						)
  def _UpperCamelCase					(			self				,		snake_case_						):




       '''simple docstring'''

       UpperCAmelCase_       ,      UpperCAmelCase_							:       Optional[Any]       =				self.model_tester.prepare_config_and_inputs_for_common()
       UpperCAmelCase_							:       int       =				ids_tensor([1, 1_0]				,		config.vocab_size						)
       UpperCAmelCase_							:       Tuple       =				ids_tensor([1, int(config.max_position_embeddings * 1.5						)]				,		config.vocab_size						)

       set_seed(4_2						)  # Fixed seed at init time so the two models get the same random weights
       UpperCAmelCase_							:       Tuple       =				OpenLlamaModel(snake_case_						)
       original_model.to(snake_case_						)
       original_model.eval()
       UpperCAmelCase_							:       List[str]       =				original_model(snake_case_						).last_hidden_state
       UpperCAmelCase_							:       Any       =				original_model(snake_case_						).last_hidden_state

       set_seed(4_2						)  # Fixed seed at init time so the two models get the same random weights
       UpperCAmelCase_							:       Tuple       =				{'type': scaling_type, 'factor': 10.0}
       UpperCAmelCase_							:       List[str]       =				OpenLlamaModel(snake_case_						)
       scaled_model.to(snake_case_						)
       scaled_model.eval()
       UpperCAmelCase_							:       Tuple       =				scaled_model(snake_case_						).last_hidden_state
       UpperCAmelCase_							:       Optional[int]       =				scaled_model(snake_case_						).last_hidden_state

       # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
       # maximum sequence length, so the outputs for the short input should match.
       if scaling_type == "dynamic":
            self.assertTrue(torch.allclose(snake_case_				,		snake_case_				,		atol=1E-5						)						)
       else:
            self.assertFalse(torch.allclose(snake_case_				,		snake_case_				,		atol=1E-5						)						)

       # The output should be different for long inputs
       self.assertFalse(torch.allclose(snake_case_				,		snake_case_				,		atol=1E-5						)						)






