
import tempfile
import unittest

from diffusers import (
    DDIMScheduler,
    DDPMScheduler,
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    PNDMScheduler,
    logging,
)
from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.utils.testing_utils import CaptureLogger







class 							lowercase						(   SCREAMING_SNAKE_CASE__						):
							lowercase_			:			Any			   ='''config.json'''




							@register_to_config
							def __init__(							self  ,A__=2  ,A__=5  ,A__=(2, 5)  ,A__="for diffusion"  ,A__=[1, 3]  ,):
												pass







class 							lowercase						(   SCREAMING_SNAKE_CASE__						):
							lowercase_			:			Optional[int]			   ='''config.json'''




							@register_to_config
							def __init__(							self  ,A__=2  ,A__=5  ,A__=(2, 5)  ,A__="for diffusion"  ,A__=[1, 3]  ,):
												pass







class 							lowercase						(   SCREAMING_SNAKE_CASE__						):
							lowercase_			:			Dict			   ='''config.json'''




							@register_to_config
							def __init__(							self  ,A__=2  ,A__=5  ,A__=(2, 5)  ,A__="for diffusion"  ,A__=[1, 3]  ,A__=[1, 3]  ,):
												pass







class 							lowercase						(   SCREAMING_SNAKE_CASE__						):
							lowercase_			:			Dict			   ='''config.json'''




							@register_to_config
							def __init__(							self  ,A__=2  ,A__=5  ,A__=(2, 5)  ,A__="for diffusion"  ,A__=[1, 5]  ,A__=[5, 4]  ,):
												pass







class 							lowercase						(   unittest.TestCase						):




							def 					A__ (							self):
												with self.assertRaises(A__):
																	ConfigMixin.load_config('''dummy_path''')




							def 					A__ (							self):
												lowercase		      =		SampleObject()
												lowercase		      =		obj.config
												assert config["a"] == 2
												assert config["b"] == 5
												assert config["c"] == (2, 5)
												assert config["d"] == "for diffusion"
												assert config["e"] == [1, 3]

												# init ignore private arguments
												lowercase		      =		SampleObject(_name_or_path='''lalala''')
												lowercase		      =		obj.config
												assert config["a"] == 2
												assert config["b"] == 5
												assert config["c"] == (2, 5)
												assert config["d"] == "for diffusion"
												assert config["e"] == [1, 3]

												# can override default
												lowercase		      =		SampleObject(c=6)
												lowercase		      =		obj.config
												assert config["a"] == 2
												assert config["b"] == 5
												assert config["c"] == 6
												assert config["d"] == "for diffusion"
												assert config["e"] == [1, 3]

												# can use positional arguments.
												lowercase		      =		SampleObject(1  ,c=6)
												lowercase		      =		obj.config
												assert config["a"] == 1
												assert config["b"] == 5
												assert config["c"] == 6
												assert config["d"] == "for diffusion"
												assert config["e"] == [1, 3]




							def 					A__ (							self):
												lowercase		      =		SampleObject()
												lowercase		      =		obj.config

												assert config["a"] == 2
												assert config["b"] == 5
												assert config["c"] == (2, 5)
												assert config["d"] == "for diffusion"
												assert config["e"] == [1, 3]

												with tempfile.TemporaryDirectory() as tmpdirname:
																	obj.save_config(A__)
																	lowercase		      =		SampleObject.from_config(SampleObject.load_config(A__))
																	lowercase		      =		new_obj.config

												# unfreeze configs
												lowercase		      =		dict(A__)
												lowercase		      =		dict(A__)

												assert config.pop('''c''') == (2, 5)  # instantiated as tuple
												assert new_config.pop('''c''') == [2, 5]  # saved & loaded as list because of json
												config.pop('''_use_default_values''')
												assert config == new_config




							def 					A__ (							self):
												lowercase		      =		logging.get_logger('''diffusers.configuration_utils''')
												# 30 for warning
												logger.setLevel(3_0)

												with CaptureLogger(A__) as cap_logger:
																	lowercase		      =		DDIMScheduler.from_pretrained(
																	    '''hf-internal-testing/tiny-stable-diffusion-torch'''  ,subfolder='''scheduler''')

												assert ddim.__class__ == DDIMScheduler
												# no warning should be thrown
												assert cap_logger.out == ""




							def 					A__ (							self):
												lowercase		      =		logging.get_logger('''diffusers.configuration_utils''')
												# 30 for warning
												logger.setLevel(3_0)

												with CaptureLogger(A__) as cap_logger:
																	lowercase		      =		EulerDiscreteScheduler.from_pretrained(
																	    '''hf-internal-testing/tiny-stable-diffusion-torch'''  ,subfolder='''scheduler''')

												assert euler.__class__ == EulerDiscreteScheduler
												# no warning should be thrown
												assert cap_logger.out == ""




							def 					A__ (							self):
												lowercase		      =		logging.get_logger('''diffusers.configuration_utils''')
												# 30 for warning
												logger.setLevel(3_0)

												with CaptureLogger(A__) as cap_logger:
																	lowercase		      =		EulerAncestralDiscreteScheduler.from_pretrained(
																	    '''hf-internal-testing/tiny-stable-diffusion-torch'''  ,subfolder='''scheduler''')

												assert euler.__class__ == EulerAncestralDiscreteScheduler
												# no warning should be thrown
												assert cap_logger.out == ""




							def 					A__ (							self):
												lowercase		      =		logging.get_logger('''diffusers.configuration_utils''')
												# 30 for warning
												logger.setLevel(3_0)

												with CaptureLogger(A__) as cap_logger:
																	lowercase		      =		PNDMScheduler.from_pretrained(
																	    '''hf-internal-testing/tiny-stable-diffusion-torch'''  ,subfolder='''scheduler''')

												assert pndm.__class__ == PNDMScheduler
												# no warning should be thrown
												assert cap_logger.out == ""




							def 					A__ (							self):
												lowercase		      =		logging.get_logger('''diffusers.configuration_utils''')
												# 30 for warning
												logger.setLevel(3_0)

												with CaptureLogger(A__) as cap_logger:
																	lowercase		      =		DDPMScheduler.from_pretrained(
																	    '''hf-internal-testing/tiny-stable-diffusion-torch'''  ,subfolder='''scheduler'''  ,prediction_type='''sample'''  ,beta_end=8  ,)

												with CaptureLogger(A__) as cap_logger_a:
																	lowercase		      =		DDPMScheduler.from_pretrained('''google/ddpm-celebahq-256'''  ,beta_start=8_8)

												assert ddpm.__class__ == DDPMScheduler
												assert ddpm.config.prediction_type == "sample"
												assert ddpm.config.beta_end == 8
												assert ddpm_a.config.beta_start == 8_8

												# no warning should be thrown
												assert cap_logger.out == ""
												assert cap_logger_a.out == ""




							def 					A__ (							self):
												lowercase		      =		logging.get_logger('''diffusers.configuration_utils''')
												# 30 for warning
												logger.setLevel(3_0)

												with CaptureLogger(A__) as cap_logger:
																	lowercase		      =		DPMSolverMultistepScheduler.from_pretrained(
																	    '''hf-internal-testing/tiny-stable-diffusion-torch'''  ,subfolder='''scheduler''')

												assert dpm.__class__ == DPMSolverMultistepScheduler
												# no warning should be thrown
												assert cap_logger.out == ""





							def 					A__ (							self):
												# let's first save a config that should be in the form
												#    a=2,
												#    b=5,
												#    c=(2, 5),
												#    d="for diffusion",
												#    e=[1, 3],

												lowercase		      =		SampleObject()

												lowercase		      =		{k: v for k, v in config.config.items() if not k.startswith('''_''')}

												# make sure that default config has all keys in `_use_default_values`
												assert set(config_dict.keys()) == set(config.config._use_default_values)

												with tempfile.TemporaryDirectory() as tmpdirname:
																	config.save_config(A__)

																	# now loading it with SampleObject2 should put f into `_use_default_values`
																	lowercase		      =		SampleObjecta.from_config(A__)

																	assert "f" in config._use_default_values
																	assert config.f == [1, 3]

												# now loading the config, should **NOT** use [1, 3] for `f`, but the default [1, 4] value
												# **BECAUSE** it is part of `config._use_default_values`
												lowercase		      =		SampleObjecta.from_config(config.config)
												assert new_config.f == [5, 4]

												config.config._use_default_values.pop()
												lowercase		      =		SampleObjecta.from_config(config.config)
												assert new_config_a.f == [1, 3]

												# Nevertheless "e" should still be correctly loaded to [1, 3] from SampleObject2 instead of defaulting to [1, 5]
												assert new_config_a.e == [1, 3]






import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from ....modeling_outputs import BaseModelOutputWithPooling, SequenceClassifierOutput
from ....modeling_utils import ModuleUtilsMixin
from ....utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings


lowercase__						:Dict					    =       logging.get_logger(__name__)

lowercase__						:str					    =       "MMBTConfig"







class 							lowercase						(   nn.Module						):




							def __init__(							self  ,A__  ,A__  ,A__):
												super().__init__()
												lowercase		      =		config
												lowercase		      =		encoder
												lowercase		      =		nn.Linear(config.modal_hidden_size  ,config.hidden_size)
												lowercase		      =		embeddings.position_embeddings
												lowercase		      =		embeddings.token_type_embeddings
												lowercase		      =		embeddings.word_embeddings
												lowercase		      =		embeddings.LayerNorm
												lowercase		      =		nn.Dropout(p=config.hidden_dropout_prob)





							def 					A__ (							self  ,A__  ,A__=None  ,A__=None  ,A__=None  ,A__=None):
												lowercase		      =		self.proj_embeddings(self.encoder(A__))
												lowercase		      =		token_embeddings.size(1)

												if start_token is not None:
																	lowercase		      =		self.word_embeddings(A__)
																	seq_length += 1
																	lowercase		      =		torch.cat([start_token_embeds.unsqueeze(1), token_embeddings]  ,dim=1)

												if end_token is not None:
																	lowercase		      =		self.word_embeddings(A__)
																	seq_length += 1
																	lowercase		      =		torch.cat([token_embeddings, end_token_embeds.unsqueeze(1)]  ,dim=1)

												if position_ids is None:
																	lowercase		      =		torch.arange(A__  ,dtype=torch.long  ,device=input_modal.device)
																	lowercase		      =		position_ids.unsqueeze(0).expand(input_modal.size(0)  ,A__)

												if token_type_ids is None:
																	lowercase		      =		torch.zeros(
																	    (input_modal.size(0), seq_length)  ,dtype=torch.long  ,device=input_modal.device)

												lowercase		      =		self.position_embeddings(A__)
												lowercase		      =		self.token_type_embeddings(A__)
												lowercase		      =		token_embeddings + position_embeddings + token_type_embeddings
												lowercase		      =		self.LayerNorm(A__)
												lowercase		      =		self.dropout(A__)
												return embeddings


lowercase__						:Union[str, Any]					    =       r"\n    MMBT model was proposed in [Supervised Multimodal Bitransformers for Classifying Images and\n    Text](https://github.com/facebookresearch/mmbt) by Douwe Kiela, Suvrat Bhooshan, Hamed Firooz, Davide Testuggine.\n    It's a supervised multimodal bitransformer model that fuses information from text and other image encoders, and\n    obtain state-of-the-art performance on various multimodal classification benchmark tasks.\n\n    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the\n    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads\n    etc.)\n\n    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.\n    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage\n    and behavior.\n\n    Parameters:\n        config ([`MMBTConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration.\n        transformer (`nn.Module`): A text transformer that is used by MMBT.\n            It should have embeddings, encoder, and pooler attributes.\n        encoder (`nn.Module`): Encoder for the second modality.\n            It should take in a batch of modal inputs and return k, n dimension embeddings.\n"

lowercase__						:Optional[Any]					    =       r"\n    Args:\n        input_modal (`torch.FloatTensor` of shape `(batch_size, ***)`):\n            The other modality data. It will be the shape that the encoder for that type expects. e.g. With an Image\n            Encoder, the shape would be (batch_size, channels, height, width)\n        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n            Indices of input sequence tokens in the vocabulary. It does not expect [CLS] token to be added as it's\n            appended to the end of other modality embeddings. Indices can be obtained using [`AutoTokenizer`]. See\n            [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.\n\n            [What are input IDs?](../glossary#input-ids)\n        modal_start_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n            Optional start token to be added to Other Modality Embedding. [CLS] Most commonly used for classification\n            tasks.\n        modal_end_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n            Optional end token to be added to Other Modality Embedding. [SEP] Most commonly used.\n        attention_mask (*optional*) `torch.FloatTensor` of shape `(batch_size, sequence_length)`:\n            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n            - 1 for tokens that are **not masked**,\n            - 0 for tokens that are **masked**.\n\n            [What are attention masks?](../glossary#attention-mask)\n        token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, sequence_length)`:\n            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,\n            1]`:\n\n            - 0 corresponds to a *sentence A* token,\n            - 1 corresponds to a *sentence B* token.\n\n            [What are token type IDs?](../glossary#token-type-ids)\n        modal_token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, modal_sequence_length)`:\n            Segment token indices to indicate different portions of the non-text modality. The embeddings from these\n            tokens will be summed with the respective token embeddings for the non-text modality.\n        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,\n            config.max_position_embeddings - 1]`.\n\n            [What are position IDs?](../glossary#position-ids)\n        modal_position_ids (`torch.LongTensor` of shape `(batch_size, modal_sequence_length)`, *optional*):\n            Indices of positions of each input sequence tokens in the position embeddings for the non-text modality.\n            Selected in the range `[0, config.max_position_embeddings - 1]`.\n\n            [What are position IDs?](../glossary#position-ids)\n        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):\n            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:\n\n            - 1 indicates the head is **not masked**,\n            - 0 indicates the head is **masked**.\n\n        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, embedding_dim)`, *optional*):\n            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This\n            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the\n            model's internal embedding lookup matrix.\n        encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n            the model is configured as a decoder.\n        encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):\n            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n            - 1 for tokens that are **not masked**,\n            - 0 for tokens that are **masked**.\n\n        output_attentions (`bool`, *optional*):\n            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n            tensors for more detail.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n"







@add_start_docstrings(
    '''The bare MMBT Model outputting raw hidden-states without any specific head on top.'''			,    SCREAMING_SNAKE_CASE__			,    )
class 							lowercase						(   nn.Module			,    SCREAMING_SNAKE_CASE__						):




							def __init__(							self  ,A__  ,A__  ,A__):
												super().__init__()
												lowercase		      =		config
												lowercase		      =		transformer
												lowercase		      =		ModalEmbeddings(A__  ,A__  ,transformer.embeddings)




							@add_start_docstrings_to_model_forward(A__)
							@replace_return_docstrings(output_type=A__  ,config_class=_CONFIG_FOR_DOC)
							def 					A__ (							self  ,A__  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,):
												lowercase		      =		output_attentions if output_attentions is not None else self.config.output_attentions
												lowercase		      =		(
												    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
												)
												lowercase		      =		return_dict if return_dict is not None else self.config.use_return_dict

												if input_ids is not None and inputs_embeds is not None:
																	raise ValueError('''You cannot specify both input_ids and inputs_embeds at the same time''')
												elif input_ids is not None:
																	lowercase		      =		input_ids.size()
												elif inputs_embeds is not None:
																	lowercase		      =		inputs_embeds.size()[:-1]
												else:
																	raise ValueError('''You have to specify either input_ids or inputs_embeds''')

												lowercase		      =		input_ids.device if input_ids is not None else inputs_embeds.device

												lowercase		      =		self.modal_encoder(
												    A__  ,start_token=A__  ,end_token=A__  ,position_ids=A__  ,token_type_ids=A__  ,)

												lowercase		      =		modal_embeddings.size()[:-1]

												if token_type_ids is None:
																	lowercase		      =		torch.ones(A__  ,dtype=torch.long  ,device=A__)

												lowercase		      =		self.transformer.embeddings(
												    input_ids=A__  ,position_ids=A__  ,token_type_ids=A__  ,inputs_embeds=A__)

												lowercase		      =		torch.cat([modal_embeddings, txt_embeddings]  ,1)

												lowercase		      =		embedding_output.size()[:-1]

												if attention_mask is None:
																	lowercase		      =		torch.ones(A__  ,device=A__)
												else:
																	lowercase		      =		torch.cat(
																	    [torch.ones(A__  ,device=A__  ,dtype=torch.long), attention_mask]  ,dim=1)
												if encoder_attention_mask is None:
																	lowercase		      =		torch.ones(A__  ,device=A__)
												else:
																	lowercase		      =		torch.cat(
																	    [torch.ones(A__  ,device=A__), encoder_attention_mask]  ,dim=1)

												lowercase		      =		self.get_extended_attention_mask(A__  ,A__)
												lowercase		      =		self.invert_attention_mask(A__)
												lowercase		      =		self.get_head_mask(A__  ,self.config.num_hidden_layers)

												lowercase		      =		self.transformer.encoder(
												    A__  ,attention_mask=A__  ,head_mask=A__  ,encoder_hidden_states=A__  ,encoder_attention_mask=A__  ,output_attentions=A__  ,output_hidden_states=A__  ,return_dict=A__  ,)

												lowercase		      =		encoder_outputs[0]
												lowercase		      =		self.transformer.pooler(A__)

												if not return_dict:
																	return (sequence_output, pooled_output) + encoder_outputs[1:]

												return BaseModelOutputWithPooling(
												    last_hidden_state=A__  ,pooler_output=A__  ,hidden_states=encoder_outputs.hidden_states  ,attentions=encoder_outputs.attentions  ,)




							def 					A__ (							self):
												return self.embeddings.word_embeddings





							def 					A__ (							self  ,A__):
												lowercase		      =		value







@add_start_docstrings(
    '''
    MMBT Model with a sequence classification/regression head on top (a linear layer on top of the pooled output)
    '''			,    SCREAMING_SNAKE_CASE__			,    SCREAMING_SNAKE_CASE__			,    )
class 							lowercase						(   nn.Module						):




							def __init__(							self  ,A__  ,A__  ,A__):
												super().__init__()
												lowercase		      =		config.num_labels

												lowercase		      =		MMBTModel(A__  ,A__  ,A__)
												lowercase		      =		nn.Dropout(config.hidden_dropout_prob)
												lowercase		      =		nn.Linear(config.hidden_size  ,config.num_labels)





							def 					A__ (							self  ,A__  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,A__=None  ,):
												lowercase		      =		return_dict if return_dict is not None else self.config.use_return_dict

												lowercase		      =		self.mmbt(
												    input_modal=A__  ,input_ids=A__  ,modal_start_tokens=A__  ,modal_end_tokens=A__  ,attention_mask=A__  ,token_type_ids=A__  ,modal_token_type_ids=A__  ,position_ids=A__  ,modal_position_ids=A__  ,head_mask=A__  ,inputs_embeds=A__  ,return_dict=A__  ,)

												lowercase		      =		outputs[1]

												lowercase		      =		self.dropout(A__)
												lowercase		      =		self.classifier(A__)

												lowercase		      =		None
												if labels is not None:
																	if self.num_labels == 1:
																						#  We are doing regression
																						lowercase		      =		MSELoss()
																						lowercase		      =		loss_fct(logits.view(-1)  ,labels.view(-1))
																	else:
																						lowercase		      =		CrossEntropyLoss()
																						lowercase		      =		loss_fct(logits.view(-1  ,self.num_labels)  ,labels.view(-1))

												if not return_dict:
																	lowercase		      =		(logits,) + outputs[2:]
																	return ((loss,) + output) if loss is not None else output

												return SequenceClassifierOutput(
												    loss=A__  ,logits=A__  ,hidden_states=outputs.hidden_states  ,attentions=outputs.attentions  ,)




