



from __future__ import annotations

import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import is_tf_available, is_vision_available

from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_tf_bert import TFBertModelTester
from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester
from ..deit.test_modeling_tf_deit import TFDeiTModelTester
from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester
from ..vit.test_modeling_tf_vit import TFViTModelTester


if is_tf_available():
     from transformers import (
         TFBertModel,
         TFCLIPVisionModel,
         TFDeiTModel,
         TFRobertaModel,
         TFVisionTextDualEncoderModel,
         TFViTModel,
         VisionTextDualEncoderConfig,
     )

if is_vision_available():
     from PIL import Image

     from transformers import VisionTextDualEncoderProcessor





def 					lowerCAmelCase_			(	__a		)					->		Optional[int]:







  """simple docstring"""





  if isinstance(__a     ,   collections.abc.Iterable		):
    return x
  return (x, x)



@require_tf
class        _SCREAMING_SNAKE_CASE						:







 '''simple docstring'''

 def 							SCREAMING_SNAKE_CASE_ (self    :       int	,			UpperCAmelCase_    :       List[Any]	,			UpperCAmelCase_    :       Dict)	->Optional[Any]:



   '''simple docstring'''



   pass

 def 							SCREAMING_SNAKE_CASE_ (self    :       List[Any])	->List[Any]:



   '''simple docstring'''



   pass

 def 							SCREAMING_SNAKE_CASE_ (self    :       Tuple)	->List[Any]:



   '''simple docstring'''



   pass

 def 							SCREAMING_SNAKE_CASE_ (self    :       int	,			UpperCAmelCase_    :       List[Any]	,			UpperCAmelCase_    :       List[Any]	,			UpperCAmelCase_    :       Optional[int]	,			UpperCAmelCase_    :       Any	,			UpperCAmelCase_    :       Any=None	,			**UpperCAmelCase_    :       Optional[int])	->str:



   '''simple docstring'''



   lowerCamelCase__:				Union[str, Any]        =VisionTextDualEncoderConfig.from_vision_text_configs(a__	,			a__)

   lowerCamelCase__:				Optional[Any]        =TFVisionTextDualEncoderModel(a__)

   lowerCamelCase__:				str        =model(input_ids=a__	,			pixel_values=a__	,			attention_mask=a__)

   self.assertEqual(output["text_embeds"].shape	,			(input_ids.shape[0], config.projection_dim))
   self.assertEqual(output["image_embeds"].shape	,			(pixel_values.shape[0], config.projection_dim))

 def 							SCREAMING_SNAKE_CASE_ (self    :       Optional[Any]	,			UpperCAmelCase_    :       Optional[Any]	,			UpperCAmelCase_    :       Tuple	,			UpperCAmelCase_    :       List[Any]	,			UpperCAmelCase_    :       Tuple	,			UpperCAmelCase_    :       str=None	,			**UpperCAmelCase_    :       List[Any])	->str:



   '''simple docstring'''



   lowerCamelCase__  , lowerCamelCase__:				List[str]        =self.get_vision_text_model(a__	,			a__)
   lowerCamelCase__:				Optional[Any]        =TFVisionTextDualEncoderModel(vision_model=a__	,			text_model=a__)

   lowerCamelCase__:				str        =model(input_ids=a__	,			pixel_values=a__	,			attention_mask=a__)

   self.assertEqual(output["text_embeds"].shape	,			(input_ids.shape[0], model.config.projection_dim))
   self.assertEqual(output["image_embeds"].shape	,			(pixel_values.shape[0], model.config.projection_dim))

 def 							SCREAMING_SNAKE_CASE_ (self    :       Tuple	,			UpperCAmelCase_    :       Any	,			UpperCAmelCase_    :       Dict	,			UpperCAmelCase_    :       Union[str, Any]	,			UpperCAmelCase_    :       Optional[Any]	,			UpperCAmelCase_    :       Optional[Any]=None	,			**UpperCAmelCase_    :       List[str])	->int:



   '''simple docstring'''



   lowerCamelCase__  , lowerCamelCase__:				List[Any]        =self.get_vision_text_model(a__	,			a__)
   lowerCamelCase__:				int        ={"vision_model": vision_model, "text_model": text_model}
   lowerCamelCase__:				Any        =TFVisionTextDualEncoderModel.from_vision_text_pretrained(**a__)

   lowerCamelCase__:				List[Any]        =model(input_ids=a__	,			pixel_values=a__	,			attention_mask=a__)

   self.assertEqual(output["text_embeds"].shape	,			(input_ids.shape[0], model.config.projection_dim))
   self.assertEqual(output["image_embeds"].shape	,			(pixel_values.shape[0], model.config.projection_dim))

 def 							SCREAMING_SNAKE_CASE_ (self    :       Any	,			UpperCAmelCase_    :       Optional[int]	,			UpperCAmelCase_    :       List[str]	,			UpperCAmelCase_    :       Tuple	,			UpperCAmelCase_    :       Dict	,			UpperCAmelCase_    :       Dict=None	,			**UpperCAmelCase_    :       Union[str, Any])	->Any:



   '''simple docstring'''



   lowerCamelCase__  , lowerCamelCase__:				int        =self.get_vision_text_model(a__	,			a__)
   lowerCamelCase__:				Any        =TFVisionTextDualEncoderModel(vision_model=a__	,			text_model=a__)

   lowerCamelCase__:				Optional[int]        =model(input_ids=a__	,			pixel_values=a__	,			attention_mask=a__)
   lowerCamelCase__:				int        =output[0].numpy()

   with tempfile.TemporaryDirectory() as tmpdirname:
     model.save_pretrained(a__)
     lowerCamelCase__:				str        =TFVisionTextDualEncoderModel.from_pretrained(a__)

     lowerCamelCase__:				List[str]        =model(input_ids=a__	,			pixel_values=a__	,			attention_mask=a__)
     lowerCamelCase__:				Optional[int]        =after_output[0].numpy()
     lowerCamelCase__:				Any        =np.amax(np.abs(out_a - out_a))
     self.assertLessEqual(a__	,			1E-5)

 def 							SCREAMING_SNAKE_CASE_ (self    :       int	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       List[Any]	,			UpperCAmelCase_    :       Dict	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       Tuple=None	,			**UpperCAmelCase_    :       Dict)	->Dict:



   '''simple docstring'''



   lowerCamelCase__  , lowerCamelCase__:				Union[str, Any]        =self.get_vision_text_model(a__	,			a__)
   lowerCamelCase__:				Union[str, Any]        =TFVisionTextDualEncoderModel(vision_model=a__	,			text_model=a__)

   lowerCamelCase__:				Optional[Any]        =model(
       input_ids=a__	,			pixel_values=a__	,			attention_mask=a__	,			output_attentions=a__)

   lowerCamelCase__:				List[str]        =output.vision_model_output.attentions
   self.assertEqual(len(a__)	,			vision_config.num_hidden_layers)

   # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
   lowerCamelCase__:				Optional[Any]        =to_atuple(vision_model.config.image_size)
   lowerCamelCase__:				Any        =to_atuple(vision_model.config.patch_size)
   lowerCamelCase__:				Optional[Any]        =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
   lowerCamelCase__:				int        =num_patches + 1
   self.assertEqual(vision_attentions[0].shape[-3:]	,			(vision_config.num_attention_heads, seq_len, seq_len))

   lowerCamelCase__:				Dict        =output.text_model_output.attentions
   self.assertEqual(len(a__)	,			text_config.num_hidden_layers)

   self.assertEqual(
       text_attentions[0].shape[-3:]	,			(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])	,			)

 def 							SCREAMING_SNAKE_CASE_ (self    :       Dict	,			UpperCAmelCase_    :       int	,			UpperCAmelCase_    :       Dict	,			UpperCAmelCase_    :       List[Any])	->List[str]:



   '''simple docstring'''



   lowerCamelCase__:				List[str]        =np.abs((a - b)).max()
   self.assertLessEqual(a__	,			a__	,			F"""Difference between torch and flax is {diff} (>= {tol}).""")

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



   '''simple docstring'''



   lowerCamelCase__:				List[str]        =self.prepare_config_and_inputs()
   self.check_vision_text_dual_encoder_model(**a__)

 def 							SCREAMING_SNAKE_CASE_ (self    :       Dict)	->List[str]:



   '''simple docstring'''



   lowerCamelCase__:				str        =self.prepare_config_and_inputs()
   self.check_model_from_pretrained_configs(**a__)

 def 							SCREAMING_SNAKE_CASE_ (self    :       List[Any])	->List[Any]:



   '''simple docstring'''



   lowerCamelCase__:				Optional[Any]        =self.prepare_config_and_inputs()
   self.check_vision_text_dual_encoder_from_pretrained(**a__)

 def 							SCREAMING_SNAKE_CASE_ (self    :       int)	->List[str]:



   '''simple docstring'''



   lowerCamelCase__:				Union[str, Any]        =self.prepare_config_and_inputs()
   self.check_save_load(**a__)

 def 							SCREAMING_SNAKE_CASE_ (self    :       str)	->Optional[int]:



   '''simple docstring'''



   lowerCamelCase__:				Optional[Any]        =self.prepare_config_and_inputs()
   self.check_vision_text_output_attention(**a__)







 @slow
 def 							SCREAMING_SNAKE_CASE_ (self    :       Optional[Any])	->int:



   '''simple docstring'''



   lowerCamelCase__  , lowerCamelCase__:				Dict        =self.get_pretrained_model_and_inputs()

   lowerCamelCase__:				Tuple        =model_a(**a__)
   lowerCamelCase__:				Optional[Any]        =outputs[0].numpy()

   with tempfile.TemporaryDirectory() as tmp_dirname:
     model_a.save_pretrained(a__)
     lowerCamelCase__:				List[str]        =TFVisionTextDualEncoderModel.from_pretrained(a__)

     lowerCamelCase__:				List[str]        =model_a(**a__)
     lowerCamelCase__:				Optional[Any]        =after_outputs[0].numpy()
     lowerCamelCase__:				int        =np.amax(np.abs(out_a - out_a))
     self.assertLessEqual(a__	,			1E-5)



@require_tf
class        _SCREAMING_SNAKE_CASE						(     lowercase_   ,							unittest.TestCase   ):







 '''simple docstring'''

 def 							SCREAMING_SNAKE_CASE_ (self    :       List[Any])	->List[str]:



   '''simple docstring'''



   lowerCamelCase__:				Any        =TFVisionTextDualEncoderModel.from_vision_text_pretrained(
       "hf-internal-testing/tiny-random-vit"	,			"hf-internal-testing/tiny-random-bert")
   lowerCamelCase__:				Tuple        =13
   lowerCamelCase__:				str        =floats_tensor(
       [
           batch_size,
           model.vision_model.config.num_channels,
           model.vision_model.config.image_size,
           model.vision_model.config.image_size,
       ])
   lowerCamelCase__:				List[str]        =ids_tensor([batch_size, 4]	,			model.text_model.config.vocab_size)
   lowerCamelCase__:				Tuple        =random_attention_mask([batch_size, 4])
   lowerCamelCase__:				List[Any]        ={"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

   return model, inputs

 def 							SCREAMING_SNAKE_CASE_ (self    :       Tuple	,			UpperCAmelCase_    :       List[str]	,			UpperCAmelCase_    :       Union[str, Any])	->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__:				Optional[Any]        =TFViTModel(a__	,			name="vision_model")
   lowerCamelCase__:				Dict        =TFBertModel(a__	,			name="text_model")
   return vision_model, text_model







 def 							SCREAMING_SNAKE_CASE_ (self    :       Dict)	->str:



   '''simple docstring'''



   lowerCamelCase__:				List[str]        =TFViTModelTester(self)
   lowerCamelCase__:				int        =TFBertModelTester(self)
   lowerCamelCase__:				Any        =vit_model_tester.prepare_config_and_inputs()
   lowerCamelCase__:				str        =bert_model_tester.prepare_config_and_inputs()

   lowerCamelCase__  , lowerCamelCase__  , lowerCamelCase__:				Tuple        =vision_config_and_inputs

   (
       (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , 				
   ):				int        =text_config_and_inputs

   return {
       "text_config": text_config,
       "vision_config": vision_config,
       "pixel_values": pixel_values,
       "attention_mask": input_mask,
       "input_ids": input_ids,
       "text_token_type_ids": token_type_ids,
       "text_sequence_labels": sequence_labels,
       "text_token_labels": token_labels,
       "text_choice_labels": choice_labels,
   }



@require_tf
class        _SCREAMING_SNAKE_CASE						(     lowercase_   ,							unittest.TestCase   ):







 '''simple docstring'''

 def 							SCREAMING_SNAKE_CASE_ (self    :       Any)	->List[str]:



   '''simple docstring'''



   lowerCamelCase__:				Union[str, Any]        =TFVisionTextDualEncoderModel.from_vision_text_pretrained(
       "Rocketknight1/tiny-random-deit-tf"	,			"hf-internal-testing/tiny-random-roberta")
   lowerCamelCase__:				Optional[int]        =13
   lowerCamelCase__:				Any        =floats_tensor(
       [
           batch_size,
           model.vision_model.config.num_channels,
           model.vision_model.config.image_size,
           model.vision_model.config.image_size,
       ])
   lowerCamelCase__:				Optional[Any]        =ids_tensor([batch_size, 4]	,			model.text_model.config.vocab_size)
   lowerCamelCase__:				List[Any]        =random_attention_mask([batch_size, 4])
   lowerCamelCase__:				int        ={"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

   return model, inputs

 def 							SCREAMING_SNAKE_CASE_ (self    :       Optional[int]	,			UpperCAmelCase_    :       Tuple	,			UpperCAmelCase_    :       int	,			UpperCAmelCase_    :       Dict	,			UpperCAmelCase_    :       List[str]	,			UpperCAmelCase_    :       int=None	,			**UpperCAmelCase_    :       Any)	->Dict:



   '''simple docstring'''



   lowerCamelCase__  , lowerCamelCase__:				Any        =self.get_vision_text_model(a__	,			a__)
   lowerCamelCase__:				Optional[Any]        =TFVisionTextDualEncoderModel(vision_model=a__	,			text_model=a__)

   lowerCamelCase__:				int        =model(
       input_ids=a__	,			pixel_values=a__	,			attention_mask=a__	,			output_attentions=a__)

   lowerCamelCase__:				Dict        =output.vision_model_output.attentions
   self.assertEqual(len(a__)	,			vision_config.num_hidden_layers)

   # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
   lowerCamelCase__:				Dict        =to_atuple(vision_model.config.image_size)
   lowerCamelCase__:				int        =to_atuple(vision_model.config.patch_size)
   lowerCamelCase__:				List[Any]        =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
   lowerCamelCase__:				str        =num_patches + 2
   self.assertEqual(vision_attentions[0].shape[-3:]	,			(vision_config.num_attention_heads, seq_len, seq_len))

   lowerCamelCase__:				Any        =output.text_model_output.attentions
   self.assertEqual(len(a__)	,			text_config.num_hidden_layers)

   self.assertEqual(
       text_attentions[0].shape[-3:]	,			(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])	,			)

 def 							SCREAMING_SNAKE_CASE_ (self    :       str	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       Optional[Any])	->List[Any]:



   '''simple docstring'''



   lowerCamelCase__:				Union[str, Any]        =TFDeiTModel(a__	,			name="vision_model")
   lowerCamelCase__:				Union[str, Any]        =TFRobertaModel(a__	,			name="text_model")
   return vision_model, text_model







 def 							SCREAMING_SNAKE_CASE_ (self    :       List[Any])	->Dict:



   '''simple docstring'''



   lowerCamelCase__:				Union[str, Any]        =TFDeiTModelTester(self)
   lowerCamelCase__:				Tuple        =TFRobertaModelTester(self)
   lowerCamelCase__:				List[str]        =vit_model_tester.prepare_config_and_inputs()
   lowerCamelCase__:				Union[str, Any]        =bert_model_tester.prepare_config_and_inputs()

   lowerCamelCase__  , lowerCamelCase__  , lowerCamelCase__:				Optional[Any]        =vision_config_and_inputs

   (
       (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , 				
   ):				Dict        =text_config_and_inputs

   return {
       "text_config": text_config,
       "vision_config": vision_config,
       "pixel_values": pixel_values,
       "attention_mask": input_mask,
       "input_ids": input_ids,
       "text_token_type_ids": token_type_ids,
       "text_sequence_labels": sequence_labels,
       "text_token_labels": token_labels,
       "text_choice_labels": choice_labels,
   }



@require_tf
class        _SCREAMING_SNAKE_CASE						(     lowercase_   ,							unittest.TestCase   ):







 '''simple docstring'''

 def 							SCREAMING_SNAKE_CASE_ (self    :       Tuple)	->List[str]:



   '''simple docstring'''



   lowerCamelCase__:				Union[str, Any]        =TFVisionTextDualEncoderModel.from_vision_text_pretrained(
       "Rocketknight1/tiny-random-clip-tf"	,			"hf-internal-testing/tiny-random-bert")
   lowerCamelCase__:				Tuple        =13
   lowerCamelCase__:				int        =floats_tensor(
       [
           batch_size,
           model.vision_model.config.num_channels,
           model.vision_model.config.image_size,
           model.vision_model.config.image_size,
       ])
   lowerCamelCase__:				List[str]        =ids_tensor([batch_size, 4]	,			model.text_model.config.vocab_size)
   lowerCamelCase__:				Tuple        =random_attention_mask([batch_size, 4])
   lowerCamelCase__:				Any        ={"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

   return model, inputs

 def 							SCREAMING_SNAKE_CASE_ (self    :       str	,			UpperCAmelCase_    :       Optional[Any]	,			UpperCAmelCase_    :       Optional[Any])	->Optional[int]:



   '''simple docstring'''



   lowerCamelCase__:				str        =TFCLIPVisionModel(a__	,			name="vision_model")
   lowerCamelCase__:				Any        =TFBertModel(a__	,			name="text_model")
   return vision_model, text_model







 def 							SCREAMING_SNAKE_CASE_ (self    :       List[str])	->Dict:



   '''simple docstring'''



   lowerCamelCase__:				List[str]        =TFCLIPVisionModelTester(self)
   lowerCamelCase__:				Optional[int]        =TFBertModelTester(self)
   lowerCamelCase__:				Tuple        =clip_model_tester.prepare_config_and_inputs()
   lowerCamelCase__:				Any        =bert_model_tester.prepare_config_and_inputs()

   lowerCamelCase__  , lowerCamelCase__:				Dict        =vision_config_and_inputs

   (
       (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , (
       lowerCamelCase__				
   )  , 				
   ):				Union[str, Any]        =text_config_and_inputs

   return {
       "text_config": text_config,
       "vision_config": vision_config,
       "pixel_values": pixel_values,
       "attention_mask": input_mask,
       "input_ids": input_ids,
       "text_token_type_ids": token_type_ids,
       "text_sequence_labels": sequence_labels,
       "text_token_labels": token_labels,
       "text_choice_labels": choice_labels,
   }



@require_vision
@require_tf
class        _SCREAMING_SNAKE_CASE						(     unittest.TestCase   ):







 '''simple docstring'''

 @slow
 def 							SCREAMING_SNAKE_CASE_ (self    :       Dict)	->Tuple:



   '''simple docstring'''



   lowerCamelCase__:				str        =TFVisionTextDualEncoderModel.from_pretrained(
       "clip-italian/clip-italian"	,			logit_scale_init_value=1.0	,			from_pt=a__)
   lowerCamelCase__:				str        =VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian")

   lowerCamelCase__:				Optional[Any]        =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
   lowerCamelCase__:				Optional[int]        =processor(
       text=["una foto di un gatto", "una foto di un cane"]	,			images=a__	,			padding=a__	,			return_tensors="np")

   lowerCamelCase__:				Tuple        =model(**a__)

   # verify the logits
   self.assertEqual(outputs.logits_per_image.shape	,			(inputs.pixel_values.shape[0], inputs.input_ids.shape[0]))
   self.assertEqual(
       outputs.logits_per_text.shape	,			(inputs.input_ids.shape[0], inputs.pixel_values.shape[0])	,			)

   lowerCamelCase__:				Optional[int]        =np.array([[1.228_4727, 0.310_4122]])

   self.assertTrue(np.allclose(outputs.logits_per_image.numpy()	,			a__	,			atol=1E-3))








from typing import Callable, Dict, Optional, Tuple

import torch
from torch import nn
from torch.distributions import (
    AffineTransform,
    Distribution,
    Independent,
    NegativeBinomial,
    Normal,
    StudentT,
    TransformedDistribution,
)



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

 def __init__(self    :       int	,			UpperCAmelCase_    :       Distribution	,			UpperCAmelCase_    :       Dict=None	,			UpperCAmelCase_    :       Tuple=None	,			UpperCAmelCase_    :       Tuple=0)	->Optional[int]:



   '''simple docstring'''



   lowerCamelCase__:				Optional[Any]        =1.0 if scale is None else scale
   lowerCamelCase__:				List[Any]        =0.0 if loc is None else loc

   super().__init__(UpperCAmelCase_	,			[AffineTransform(loc=self.loc	,			scale=self.scale	,			event_dim=UpperCAmelCase_)])

 @property
 def 							SCREAMING_SNAKE_CASE_ (self    :       Union[str, Any])	->int:



   '''simple docstring'''



   return self.base_dist.mean * self.scale + self.loc

 @property
 def 							SCREAMING_SNAKE_CASE_ (self    :       int)	->Dict:



   '''simple docstring'''



   return self.base_dist.variance * self.scale**2







 @property
 def 							SCREAMING_SNAKE_CASE_ (self    :       int)	->Optional[Any]:



   '''simple docstring'''



   return self.variance.sqrt()



class        _SCREAMING_SNAKE_CASE						(     nn.Module   ):







 '''simple docstring'''

 def __init__(self    :       Tuple	,			UpperCAmelCase_    :       int	,			UpperCAmelCase_    :       Dict[str, int]	,			UpperCAmelCase_    :       Callable[..., Tuple[torch.Tensor]]	,			**UpperCAmelCase_    :       Dict)	->None:



   '''simple docstring'''



   super().__init__(**UpperCAmelCase_)
   lowerCamelCase__:				Tuple        =args_dim
   lowerCamelCase__:				Any        =nn.ModuleList([nn.Linear(UpperCAmelCase_	,			UpperCAmelCase_) for dim in args_dim.values()])
   lowerCamelCase__:				Any        =domain_map







 def 							SCREAMING_SNAKE_CASE_ (self    :       Optional[Any]	,			UpperCAmelCase_    :       torch.Tensor)	->Tuple[torch.Tensor]:



   '''simple docstring'''



   lowerCamelCase__:				Any        =[proj(UpperCAmelCase_) for proj in self.proj]

   return self.domain_map(*UpperCAmelCase_)



class        _SCREAMING_SNAKE_CASE						(     nn.Module   ):







 '''simple docstring'''

 def __init__(self    :       str	,			UpperCAmelCase_    :       Optional[Any])	->Optional[int]:



   '''simple docstring'''



   super().__init__()
   lowerCamelCase__:				Any        =function







 def 							SCREAMING_SNAKE_CASE_ (self    :       Dict	,			UpperCAmelCase_    :       Optional[Any]	,			*UpperCAmelCase_    :       Union[str, Any])	->Union[str, Any]:



   '''simple docstring'''



   return self.function(UpperCAmelCase_	,			*UpperCAmelCase_)



class        _SCREAMING_SNAKE_CASE						:







 '''simple docstring'''
 lowercase_		=      42
 lowercase_		=      42
 lowercase_		=      42

 def __init__(self    :       str	,			UpperCAmelCase_    :       int = 1)	->None:



   '''simple docstring'''



   lowerCamelCase__:				List[str]        =dim
   lowerCamelCase__:				int        ={k: dim * self.args_dim[k] for k in self.args_dim}

 def 							SCREAMING_SNAKE_CASE_ (self    :       int	,			UpperCAmelCase_    :       str)	->Optional[Any]:



   '''simple docstring'''



   if self.dim == 1:
     return self.distribution_class(*UpperCAmelCase_)
   else:
     return Independent(self.distribution_class(*UpperCAmelCase_)	,			1)

 def 							SCREAMING_SNAKE_CASE_ (self    :       Any	,			UpperCAmelCase_    :       List[Any]	,			UpperCAmelCase_    :       Optional[torch.Tensor] = None	,			UpperCAmelCase_    :       Optional[torch.Tensor] = None	,			)	->Distribution:



   '''simple docstring'''



   lowerCamelCase__:				Optional[Any]        =self._base_distribution(UpperCAmelCase_)
   if loc is None and scale is None:
     return distr
   else:
     return AffineTransformed(UpperCAmelCase_	,			loc=UpperCAmelCase_	,			scale=UpperCAmelCase_	,			event_dim=self.event_dim)

 @property
 def 							SCREAMING_SNAKE_CASE_ (self    :       int)	->Tuple:



   '''simple docstring'''



   return () if self.dim == 1 else (self.dim,)

 @property
 def 							SCREAMING_SNAKE_CASE_ (self    :       Optional[Any])	->int:



   '''simple docstring'''



   return len(self.event_shape)

 @property
 def 							SCREAMING_SNAKE_CASE_ (self    :       Tuple)	->float:



   '''simple docstring'''



   return 0.0

 def 							SCREAMING_SNAKE_CASE_ (self    :       str	,			UpperCAmelCase_    :       int)	->nn.Module:



   '''simple docstring'''



   return ParameterProjection(
       in_features=UpperCAmelCase_	,			args_dim=self.args_dim	,			domain_map=LambdaLayer(self.domain_map)	,			)

 def 							SCREAMING_SNAKE_CASE_ (self    :       Any	,			*UpperCAmelCase_    :       torch.Tensor)	->Any:



   '''simple docstring'''



   raise NotImplementedError()







 @staticmethod
 def 							SCREAMING_SNAKE_CASE_ (UpperCAmelCase_    :       torch.Tensor)	->torch.Tensor:



   '''simple docstring'''



   return (x + torch.sqrt(torch.square(UpperCAmelCase_) + 4.0)) / 2.0



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''
 lowercase_		=      {"df": 1, "loc": 1, "scale": 1}
 lowercase_		=      StudentT

 @classmethod
 def 							SCREAMING_SNAKE_CASE_ (cls    :       Optional[int]	,			UpperCAmelCase_    :       torch.Tensor	,			UpperCAmelCase_    :       torch.Tensor	,			UpperCAmelCase_    :       torch.Tensor)	->Dict:



   '''simple docstring'''



   lowerCamelCase__:				str        =cls.squareplus(UpperCAmelCase_).clamp_min(torch.finfo(scale.dtype).eps)
   lowerCamelCase__:				Any        =2.0 + cls.squareplus(UpperCAmelCase_)
   return df.squeeze(-1), loc.squeeze(-1), scale.squeeze(-1)



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''
 lowercase_		=      {"loc": 1, "scale": 1}
 lowercase_		=      Normal

 @classmethod
 def 							SCREAMING_SNAKE_CASE_ (cls    :       Optional[Any]	,			UpperCAmelCase_    :       torch.Tensor	,			UpperCAmelCase_    :       torch.Tensor)	->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__:				List[Any]        =cls.squareplus(UpperCAmelCase_).clamp_min(torch.finfo(scale.dtype).eps)
   return loc.squeeze(-1), scale.squeeze(-1)



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''
 lowercase_		=      {"total_count": 1, "logits": 1}
 lowercase_		=      NegativeBinomial

 @classmethod
 def 							SCREAMING_SNAKE_CASE_ (cls    :       Optional[int]	,			UpperCAmelCase_    :       torch.Tensor	,			UpperCAmelCase_    :       torch.Tensor)	->List[str]:



   '''simple docstring'''



   lowerCamelCase__:				Tuple        =cls.squareplus(UpperCAmelCase_)
   return total_count.squeeze(-1), logits.squeeze(-1)

 def 							SCREAMING_SNAKE_CASE_ (self    :       Tuple	,			UpperCAmelCase_    :       Tuple)	->Distribution:



   '''simple docstring'''



   lowerCamelCase__  , lowerCamelCase__:				Any        =distr_args
   if self.dim == 1:
     return self.distribution_class(total_count=UpperCAmelCase_	,			logits=UpperCAmelCase_)
   else:
     return Independent(self.distribution_class(total_count=UpperCAmelCase_	,			logits=UpperCAmelCase_)	,			1)







 def 							SCREAMING_SNAKE_CASE_ (self    :       Union[str, Any]	,			UpperCAmelCase_    :       Optional[Any]	,			UpperCAmelCase_    :       Optional[torch.Tensor] = None	,			UpperCAmelCase_    :       Optional[torch.Tensor] = None)	->Distribution:



   '''simple docstring'''



   lowerCamelCase__  , lowerCamelCase__:				Union[str, Any]        =distr_args

   if scale is not None:
     # See scaling property of Gamma.
     logits += scale.log()

   return self._base_distribution((total_count, logits))

