


import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
__snake_case   							=						pytest.mark.integration


__snake_case   							=						{'''comet'''}
__snake_case   							=						importlib.util.find_spec('''fairseq''') is not None

__snake_case   							=						{'''code_eval'''}
__snake_case   							=						os.name == '''nt'''

__snake_case   							=						{'''bertscore''', '''frugalscore''', '''perplexity'''}
__snake_case   							=						importlib.util.find_spec('''transformers''') is not None






def 		_A		(		_lowercase )					-> Optional[Any]:


     """simple docstring"""


     @wraps(_lowercase )
     def wrapper(self					,  _lowercase ):
          if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
               self.skipTest('"test requires Fairseq"' )
          else:
               test_case(self					,  _lowercase )

     return wrapper






def 		_A		(		_lowercase )					-> List[str]:


     """simple docstring"""


     @wraps(_lowercase )
     def wrapper(self					,  _lowercase ):
          if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
               self.skipTest('"test requires transformers"' )
          else:
               test_case(self					,  _lowercase )

     return wrapper






def 		_A		(		_lowercase )					-> List[str]:


     """simple docstring"""


     @wraps(_lowercase )
     def wrapper(self					,  _lowercase ):
          if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
               self.skipTest('"test not supported on Windows"' )
          else:
               test_case(self					,  _lowercase )

     return wrapper






def 		_A		(		)					-> List[str]:


     """simple docstring"""


     __UpperCamelCase =			[metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('./metrics/*/' )]
     return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished



@parameterized.named_parameters(get_local_metric_names()						)
@for_all_test_methods(
    _a				,      _a				,      _a						)
@local
class 	__lowerCamelCase			(parameterized.TestCase						):
       _lowercase											=     {}
       _lowercase											=     None







       @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning'					)
       @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning'					)
       def 		snake_case_	(			self: int,A_: List[Any]					):






            '''simple docstring'''




            __UpperCamelCase =			'[...]'
            __UpperCamelCase =			importlib.import_module(
                datasets.load.metric_module_factory(os.path.join('metrics',A_					)					).module_path					)
            __UpperCamelCase =			datasets.load.import_main_class(metric_module.__name__,dataset=A_					)
            # check parameters
            __UpperCamelCase =			inspect.signature(metric._compute					).parameters
            self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()					)					)  # no **kwargs
            # run doctest
            with self.patch_intensive_calls(A_,metric_module.__name__					):
                 with self.use_local_metrics():
                      try:
                           __UpperCamelCase =			doctest.testmod(A_,verbose=A_,raise_on_error=A_					)
                      except doctest.UnexpectedException as e:
                           raise e.exc_info[1]  # raise the exception that doctest caught
            self.assertEqual(results.failed,0					)
            self.assertGreater(results.attempted,1					)







       @slow
       def 		snake_case_	(			self: Optional[Any],A_: List[str]					):






            '''simple docstring'''




            __UpperCamelCase =			'[...]'
            __UpperCamelCase =			importlib.import_module(
                datasets.load.metric_module_factory(os.path.join('metrics',A_					)					).module_path					)
            # run doctest
            with self.use_local_metrics():
                 __UpperCamelCase =			doctest.testmod(A_,verbose=A_,raise_on_error=A_					)
            self.assertEqual(results.failed,0					)
            self.assertGreater(results.attempted,1					)







       @contextmanager
       def 		snake_case_	(			self: Dict,A_: Optional[Any],A_: Any					):






            '''simple docstring'''




            if metric_name in self.INTENSIVE_CALLS_PATCHER:
                 with self.INTENSIVE_CALLS_PATCHER[metric_name](A_					):
                      yield
            else:
                 yield







       @contextmanager
       def 		snake_case_	(			self: Tuple					):






            '''simple docstring'''




            def load_local_metric(A_: List[Any],*A_: str,**A_: List[Any]					):
                 return load_metric(os.path.join('metrics',A_					),*A_,**A_					)

            with patch('datasets.load_metric'					) as mock_load_metric:
                 __UpperCamelCase =			load_local_metric
                 yield







       @classmethod
       def 		snake_case_	(			cls: Any,A_: str					):






            '''simple docstring'''




            def wrapper(A_: Optional[Any]					):
                 __UpperCamelCase =			contextmanager(A_					)
                 __UpperCamelCase =			patcher
                 return patcher

            return wrapper






@LocalMetricTest.register_intensive_calls_patcher('bleurt' )
def 		_A		(		_lowercase )					-> Optional[Any]:


     """simple docstring"""


     import tensorflow.compat.va as tf
     from bleurt.score import Predictor

     tf.flags.DEFINE_string('sv'					,  ''					,  '' )  # handle pytest cli flags



     class 	__lowerCamelCase			(_a						):







            def 		snake_case_	(			self: List[str],A_: List[Any]					):






                 '''simple docstring'''




                 assert len(input_dict['input_ids']					) == 2
                 return np.array([1.0_3, 1.0_4]					)

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
     with patch('bleurt.score._create_predictor' ) as mock_create_predictor:
          __UpperCamelCase =			MockedPredictor()
          yield






@LocalMetricTest.register_intensive_calls_patcher('bertscore' )
def 		_A		(		_lowercase )					-> Union[str, Any]:


     """simple docstring"""


     import torch

     def bert_cos_score_idf(_lowercase					,  _lowercase					,  *_lowercase					,  **_lowercase ):
          return torch.tensor([[1.0, 1.0, 1.0]] * len(_lowercase ) )

     # mock get_model which is supposed to do download a bert model
     # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
     with patch('bert_score.scorer.get_model' ), patch(
         'bert_score.scorer.bert_cos_score_idf' ) as mock_bert_cos_score_idf:
          __UpperCamelCase =			bert_cos_score_idf
          yield






@LocalMetricTest.register_intensive_calls_patcher('comet' )
def 		_A		(		_lowercase )					-> Optional[Any]:


     """simple docstring"""


     def load_from_checkpoint(_lowercase ):



          class 	__lowerCamelCase			:







                 def 		snake_case_	(			self: Optional[int],A_: int,*A_: Optional[int],**A_: List[str]					):






                      '''simple docstring'''




                      assert len(A_					) == 2
                      __UpperCamelCase =			[0.1_9, 0.9_2]
                      return scores, sum(A_					) / len(A_					)



          return Model()

     # mock load_from_checkpoint which is supposed to do download a bert model
     # mock load_from_checkpoint which is supposed to do download a bert model
     with patch('comet.download_model' ) as mock_download_model:
          __UpperCamelCase =			None
          with patch('comet.load_from_checkpoint' ) as mock_load_from_checkpoint:
               __UpperCamelCase =			load_from_checkpoint
               yield






def 		_A		(		)					-> Union[str, Any]:


     """simple docstring"""


     __UpperCamelCase =			load_metric(os.path.join('metrics'					,  'seqeval' ) )
     __UpperCamelCase =			'ERROR'
     __UpperCamelCase =			f'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}'''
     with pytest.raises(_lowercase					,  match=re.escape(_lowercase ) ):
          metric.compute(predictions=[]					,  references=[]					,  scheme=_lowercase )



from typing import Any, Dict, Optional

import torch
import torch.nn.functional as F
from torch import nn

from ..utils import maybe_allow_in_graph
from .activations import get_activation
from .attention_processor import Attention
from .embeddings import CombinedTimestepLabelEmbeddings





@maybe_allow_in_graph
class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Dict     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     Tuple=0.0     ,  snake_case__     :     Optional[int] = None     ,  snake_case__     :     str = "geglu"     ,  snake_case__     :     Optional[int] = None     ,  snake_case__     :     bool = False     ,  snake_case__     :     bool = False     ,  snake_case__     :     bool = False     ,  snake_case__     :     bool = False     ,  snake_case__     :     bool = True     ,  snake_case__     :     str = "layer_norm"     ,  snake_case__     :     bool = False     ,  )      ->	Dict:
				super().__init__()
				_lowerCamelCase				   =  only_cross_attention

				_lowerCamelCase				   =  (num_embeds_ada_norm is not None) and norm_type == 'ada_norm_zero'
				_lowerCamelCase				   =  (num_embeds_ada_norm is not None) and norm_type == 'ada_norm'

				if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
						raise ValueError(
						    f"""`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"""
						    f""" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."""		)

				# Define 3 blocks. Each block has its own normalization layer.
				# 1. Self-Attn
				if self.use_ada_layer_norm:
						_lowerCamelCase				   =  AdaLayerNorm(snake_case__     ,  snake_case__		)
				elif self.use_ada_layer_norm_zero:
						_lowerCamelCase				   =  AdaLayerNormZero(snake_case__     ,  snake_case__		)
				else:
						_lowerCamelCase				   =  nn.LayerNorm(snake_case__     ,  elementwise_affine=snake_case__		)
				_lowerCamelCase				   =  Attention(
				    query_dim=snake_case__     ,  heads=snake_case__     ,  dim_head=snake_case__     ,  dropout=snake_case__     ,  bias=snake_case__     ,  cross_attention_dim=cross_attention_dim if only_cross_attention else None     ,  upcast_attention=snake_case__     ,  )

				# 2. Cross-Attn
				if cross_attention_dim is not None or double_self_attention:
						# We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
						# I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
						# the second cross attention block.
						_lowerCamelCase				   =  (
						    AdaLayerNorm(snake_case__     ,  snake_case__		)
						    if self.use_ada_layer_norm
						    else nn.LayerNorm(snake_case__     ,  elementwise_affine=snake_case__		)
						)
						_lowerCamelCase				   =  Attention(
						    query_dim=snake_case__     ,  cross_attention_dim=cross_attention_dim if not double_self_attention else None     ,  heads=snake_case__     ,  dim_head=snake_case__     ,  dropout=snake_case__     ,  bias=snake_case__     ,  upcast_attention=snake_case__     ,  )  # is self-attn if encoder_hidden_states is none
				else:
						_lowerCamelCase				   =  None
						_lowerCamelCase				   =  None

				# 3. Feed-forward
				_lowerCamelCase				   =  nn.LayerNorm(snake_case__     ,  elementwise_affine=snake_case__		)
				_lowerCamelCase				   =  FeedForward(snake_case__     ,  dropout=snake_case__     ,  activation_fn=snake_case__     ,  final_dropout=snake_case__		)

				# let chunk size default to None
				_lowerCamelCase				   =  None
				_lowerCamelCase				   =  0
		def   _snake_case       (       self     :     str     ,  snake_case__     :     Optional[int]     ,  snake_case__     :     int		)      ->	Optional[Any]:
				# Sets chunk feed-forward
				_lowerCamelCase				   =  chunk_size
				_lowerCamelCase				   =  dim



		def   _snake_case       (       self     :     Union[str, Any]     ,  snake_case__     :     torch.FloatTensor     ,  snake_case__     :     Optional[torch.FloatTensor] = None     ,  snake_case__     :     Optional[torch.FloatTensor] = None     ,  snake_case__     :     Optional[torch.FloatTensor] = None     ,  snake_case__     :     Optional[torch.LongTensor] = None     ,  snake_case__     :     Dict[str, Any] = None     ,  snake_case__     :     Optional[torch.LongTensor] = None     ,  )      ->	List[Any]:
				# Notice that normalization is always applied before the real computation in the following blocks.
				# 1. Self-Attention
				if self.use_ada_layer_norm:
						_lowerCamelCase				   =  self.norma(snake_case__     ,  snake_case__		)
				elif self.use_ada_layer_norm_zero:
						_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase				   =  self.norma(
						    snake_case__     ,  snake_case__     ,  snake_case__     ,  hidden_dtype=hidden_states.dtype		)
				else:
						_lowerCamelCase				   =  self.norma(snake_case__		)

				_lowerCamelCase				   =  cross_attention_kwargs if cross_attention_kwargs is not None else {}

				_lowerCamelCase				   =  self.attna(
				    snake_case__     ,  encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None     ,  attention_mask=snake_case__     ,  **snake_case__     ,  )
				if self.use_ada_layer_norm_zero:
						_lowerCamelCase				   =  gate_msa.unsqueeze(1		) * attn_output
				_lowerCamelCase				   =  attn_output + hidden_states

				# 2. Cross-Attention
				if self.attna is not None:
						_lowerCamelCase				   =  (
						    self.norma(snake_case__     ,  snake_case__		) if self.use_ada_layer_norm else self.norma(snake_case__		)
						)

						_lowerCamelCase				   =  self.attna(
						    snake_case__     ,  encoder_hidden_states=snake_case__     ,  attention_mask=snake_case__     ,  **snake_case__     ,  )
						_lowerCamelCase				   =  attn_output + hidden_states

				# 3. Feed-forward
				_lowerCamelCase				   =  self.norma(snake_case__		)

				if self.use_ada_layer_norm_zero:
						_lowerCamelCase				   =  norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]

				if self._chunk_size is not None:
						# "feed_forward_chunk_size" can be used to save memory
						if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
								raise ValueError(
								    f"""`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."""		)

						_lowerCamelCase				   =  norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
						_lowerCamelCase				   =  torch.cat(
						    [self.ff(snake_case__		) for hid_slice in norm_hidden_states.chunk(snake_case__     ,  dim=self._chunk_dim		)]     ,  dim=self._chunk_dim     ,  )
				else:
						_lowerCamelCase				   =  self.ff(snake_case__		)

				if self.use_ada_layer_norm_zero:
						_lowerCamelCase				   =  gate_mlp.unsqueeze(1		) * ff_output

				_lowerCamelCase				   =  ff_output + hidden_states

				return hidden_states





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Union[str, Any]     ,  snake_case__     :     int     ,  snake_case__     :     Optional[int] = None     ,  snake_case__     :     int = 4     ,  snake_case__     :     float = 0.0     ,  snake_case__     :     str = "geglu"     ,  snake_case__     :     bool = False     ,  )      ->	Optional[int]:
				super().__init__()
				_lowerCamelCase				   =  int(dim * mult		)
				_lowerCamelCase				   =  dim_out if dim_out is not None else dim

				if activation_fn == "gelu":
						_lowerCamelCase				   =  GELU(snake_case__     ,  snake_case__		)
				if activation_fn == "gelu-approximate":
						_lowerCamelCase				   =  GELU(snake_case__     ,  snake_case__     ,  approximate='tanh'		)
				elif activation_fn == "geglu":
						_lowerCamelCase				   =  GEGLU(snake_case__     ,  snake_case__		)
				elif activation_fn == "geglu-approximate":
						_lowerCamelCase				   =  ApproximateGELU(snake_case__     ,  snake_case__		)

				_lowerCamelCase				   =  nn.ModuleList([]		)
				# project in
				self.net.append(snake_case__		)
				# project dropout
				self.net.append(nn.Dropout(snake_case__		)		)
				# project out
				self.net.append(nn.Linear(snake_case__     ,  snake_case__		)		)
				# FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
				if final_dropout:
						self.net.append(nn.Dropout(snake_case__		)		)



		def   _snake_case       (       self     :     Tuple     ,  snake_case__     :     List[Any]		)      ->	Optional[int]:
				for module in self.net:
						_lowerCamelCase				   =  module(snake_case__		)
				return hidden_states





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     str     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     str = "none"		)      ->	Any:
				super().__init__()
				_lowerCamelCase				   =  nn.Linear(snake_case__     ,  snake_case__		)
				_lowerCamelCase				   =  approximate
		def   _snake_case       (       self     :     List[Any]     ,  snake_case__     :     List[Any]		)      ->	int:
				if gate.device.type != "mps":
						return F.gelu(snake_case__     ,  approximate=self.approximate		)
				# mps: gelu is not implemented for float16
				return F.gelu(gate.to(dtype=torch.floataa		)     ,  approximate=self.approximate		).to(dtype=gate.dtype		)



		def   _snake_case       (       self     :     Optional[int]     ,  snake_case__     :     Union[str, Any]		)      ->	str:
				_lowerCamelCase				   =  self.proj(snake_case__		)
				_lowerCamelCase				   =  self.gelu(snake_case__		)
				return hidden_states





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Dict     ,  snake_case__     :     int     ,  snake_case__     :     int		)      ->	List[Any]:
				super().__init__()
				_lowerCamelCase				   =  nn.Linear(snake_case__     ,  dim_out * 2		)
		def   _snake_case       (       self     :     Optional[Any]     ,  snake_case__     :     Optional[int]		)      ->	Optional[Any]:
				if gate.device.type != "mps":
						return F.gelu(snake_case__		)
				# mps: gelu is not implemented for float16
				return F.gelu(gate.to(dtype=torch.floataa		)		).to(dtype=gate.dtype		)



		def   _snake_case       (       self     :     List[str]     ,  snake_case__     :     Optional[Any]		)      ->	Optional[int]:
				_lowerCamelCase   ,							_lowerCamelCase				   =  self.proj(snake_case__		).chunk(2     ,  dim=-1		)
				return hidden_states * self.gelu(snake_case__		)





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Dict     ,  snake_case__     :     int     ,  snake_case__     :     int		)      ->	Tuple:
				super().__init__()
				_lowerCamelCase				   =  nn.Linear(snake_case__     ,  snake_case__		)



		def   _snake_case       (       self     :     Optional[Any]     ,  snake_case__     :     List[Any]		)      ->	Optional[int]:
				_lowerCamelCase				   =  self.proj(snake_case__		)
				return x * torch.sigmoid(1.702 * x		)





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Optional[Any]     ,  snake_case__     :     Tuple     ,  snake_case__     :     Any		)      ->	Dict:
				super().__init__()
				_lowerCamelCase				   =  nn.Embedding(snake_case__     ,  snake_case__		)
				_lowerCamelCase				   =  nn.SiLU()
				_lowerCamelCase				   =  nn.Linear(snake_case__     ,  embedding_dim * 2		)
				_lowerCamelCase				   =  nn.LayerNorm(snake_case__     ,  elementwise_affine=snake_case__		)



		def   _snake_case       (       self     :     Tuple     ,  snake_case__     :     str     ,  snake_case__     :     Dict		)      ->	Optional[int]:
				_lowerCamelCase				   =  self.linear(self.silu(self.emb(snake_case__		)		)		)
				_lowerCamelCase   ,							_lowerCamelCase				   =  torch.chunk(snake_case__     ,  2		)
				_lowerCamelCase				   =  self.norm(snake_case__		) * (1 + scale) + shift
				return x





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Any     ,  snake_case__     :     Optional[Any]     ,  snake_case__     :     Union[str, Any]		)      ->	Dict:
				super().__init__()

				_lowerCamelCase				   =  CombinedTimestepLabelEmbeddings(snake_case__     ,  snake_case__		)

				_lowerCamelCase				   =  nn.SiLU()
				_lowerCamelCase				   =  nn.Linear(snake_case__     ,  6 * embedding_dim     ,  bias=snake_case__		)
				_lowerCamelCase				   =  nn.LayerNorm(snake_case__     ,  elementwise_affine=snake_case__     ,  eps=1e-6		)



		def   _snake_case       (       self     :     Dict     ,  snake_case__     :     Tuple     ,  snake_case__     :     str     ,  snake_case__     :     str     ,  snake_case__     :     List[Any]=None		)      ->	int:
				_lowerCamelCase				   =  self.linear(self.silu(self.emb(snake_case__     ,  snake_case__     ,  hidden_dtype=snake_case__		)		)		)
				_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase				   =  emb.chunk(6     ,  dim=1		)
				_lowerCamelCase				   =  self.norm(snake_case__		) * (1 + scale_msa[:, None]) + shift_msa[:, None]
				return x, gate_msa, shift_mlp, scale_mlp, gate_mlp





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Tuple     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     Optional[str] = None     ,  snake_case__     :     float = 1e-5		)      ->	int:
				super().__init__()
				_lowerCamelCase				   =  num_groups
				_lowerCamelCase				   =  eps

				if act_fn is None:
						_lowerCamelCase				   =  None
				else:
						_lowerCamelCase				   =  get_activation(snake_case__		)

				_lowerCamelCase				   =  nn.Linear(snake_case__     ,  out_dim * 2		)



		def   _snake_case       (       self     :     Union[str, Any]     ,  snake_case__     :     int     ,  snake_case__     :     Optional[Any]		)      ->	Union[str, Any]:
				if self.act:
						_lowerCamelCase				   =  self.act(snake_case__		)
				_lowerCamelCase				   =  self.linear(snake_case__		)
				_lowerCamelCase				   =  emb[:, :, None, None]
				_lowerCamelCase   ,							_lowerCamelCase				   =  emb.chunk(2     ,  dim=1		)

				_lowerCamelCase				   =  F.group_norm(snake_case__     ,  self.num_groups     ,  eps=self.eps		)
				_lowerCamelCase				   =  x * (1 + scale) + shift
				return x