
"""simple docstring"""

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


UpperCamelCase      :							Dict          =					logging.get_logger(__name__)

UpperCamelCase      :							str          =					"MMBTConfig"

class __lowerCAmelCase						( nn.Module     ):





     def __init__(      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase      ,	__UpperCAmelCase ):

      '''simple docstring'''




      super().__init__()
      __UpperCamelCase							    =			config
      __UpperCamelCase							    =			encoder
      __UpperCamelCase							    =			nn.Linear(config.modal_hidden_size      ,	config.hidden_size )
      __UpperCamelCase							    =			embeddings.position_embeddings
      __UpperCamelCase							    =			embeddings.token_type_embeddings
      __UpperCamelCase							    =			embeddings.word_embeddings
      __UpperCamelCase							    =			embeddings.LayerNorm
      __UpperCamelCase							    =			nn.Dropout(p=config.hidden_dropout_prob )







     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None ):

      '''simple docstring'''




      __UpperCamelCase							    =			self.proj_embeddings(self.encoder(A__ ) )
      __UpperCamelCase							    =			token_embeddings.size(1 )

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

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

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

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

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


UpperCamelCase      :							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"

UpperCamelCase      :							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 __lowerCAmelCase						( nn.Module     ,    SCREAMING_SNAKE_CASE__     ):





     def __init__(      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase      ,	__UpperCAmelCase ):

      '''simple docstring'''




      super().__init__()
      __UpperCamelCase							    =			config
      __UpperCamelCase							    =			transformer
      __UpperCamelCase							    =			ModalEmbeddings(A__      ,	A__      ,	transformer.embeddings )





     @add_start_docstrings_to_model_forward(A__ )
     @replace_return_docstrings(output_type=A__      ,	config_class=_CONFIG_FOR_DOC )
     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	):

      '''simple docstring'''




      __UpperCamelCase							    =			output_attentions if output_attentions is not None else self.config.output_attentions
      __UpperCamelCase							    =			(
          output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
      )
      __UpperCamelCase							    =			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:
       __UpperCamelCase							    =			input_ids.size()
      elif inputs_embeds is not None:
       __UpperCamelCase							    =			inputs_embeds.size()[:-1]
      else:
       raise ValueError('You have to specify either input_ids or inputs_embeds' )

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

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

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

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

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

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

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

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

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

      __UpperCamelCase							    =			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__      ,	)

      __UpperCamelCase							    =			encoder_outputs[0]
      __UpperCamelCase							    =			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 		UpperCAmelCase   (      self ):

      '''simple docstring'''




      return self.embeddings.word_embeddings







     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase ):

      '''simple docstring'''




      __UpperCamelCase							    =			value


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





     def __init__(      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase      ,	__UpperCAmelCase ):

      '''simple docstring'''




      super().__init__()
      __UpperCamelCase							    =			config.num_labels

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







     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	__UpperCAmelCase=None      ,	):

      '''simple docstring'''




      __UpperCamelCase							    =			return_dict if return_dict is not None else self.config.use_return_dict

      __UpperCamelCase							    =			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__      ,	)

      __UpperCamelCase							    =			outputs[1]

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

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

      if not return_dict:
       __UpperCamelCase							    =			(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      ,	)





import os
import random
from pathlib import Path
from typing import List

import numpy as np
import torch
from torch.cuda.amp import GradScaler

from .utils import (
    MODEL_NAME,
    OPTIMIZER_NAME,
    RNG_STATE_NAME,
    SCALER_NAME,
    SCHEDULER_NAME,
    get_pretty_name,
    is_tpu_available,
    is_xpu_available,
    save,
)


if is_tpu_available(check_device=False):
							import torch_xla.core.xla_model as xm

from .logging import get_logger
from .state import PartialState


lowercase__						:Optional[Any]					    =       get_logger(__name__)



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__ = None					,     ):
					'''simple docstring'''
					# Model states
					for i, state in enumerate(lowerCAmelCase__						):
										lowercase		      =		f'{MODEL_NAME}.bin' if i == 0 else f'{MODEL_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										save(lowerCAmelCase__					,     lowerCAmelCase__						)
										logger.info(f'Model weights saved in {output_model_file}'						)
					# Optimizer states
					for i, opt in enumerate(lowerCAmelCase__						):
										lowercase		      =		opt.state_dict()
										lowercase		      =		f'{OPTIMIZER_NAME}.bin' if i == 0 else f'{OPTIMIZER_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										save(lowerCAmelCase__					,     lowerCAmelCase__						)
										logger.info(f'Optimizer state saved in {output_optimizer_file}'						)
					# Scheduler states
					for i, scheduler in enumerate(lowerCAmelCase__						):
										lowercase		      =		scheduler.state_dict()
										lowercase		      =		f'{SCHEDULER_NAME}.bin' if i == 0 else f'{SCHEDULER_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										save(lowerCAmelCase__					,     lowerCAmelCase__						)
										logger.info(f'Scheduler state saved in {output_scheduler_file}'						)
					# GradScaler state
					if scaler is not None:
										lowercase		      =		scaler.state_dict()
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										torch.save(lowerCAmelCase__					,     lowerCAmelCase__						)
										logger.info(f'Gradient scaler state saved in {output_scaler_file}'						)
					# Random number generator states
					lowercase		      =		{}
					lowercase		      =		f'{RNG_STATE_NAME}_{process_index}.pkl'
					lowercase		      =		random.getstate()
					lowercase		      =		np.random.get_state()
					lowercase		      =		torch.get_rng_state()
					if is_xpu_available():
										lowercase		      =		torch.xpu.get_rng_state_all()
					else:
										lowercase		      =		torch.cuda.get_rng_state_all()
					if is_tpu_available():
										lowercase		      =		xm.get_rng_state()
					lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
					torch.save(lowerCAmelCase__					,     lowerCAmelCase__						)
					logger.info(f'Random states saved in {output_states_file}'						)
					return output_dir



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__=None					,     lowerCAmelCase__=None					,     **lowerCAmelCase__					,     ):
					'''simple docstring'''
					if map_location not in [None, "cpu", "on_device"]:
										raise TypeError(
										    '''Unsupported optimizer map location passed, please choose one of `None`, `\'cpu\'`, or `\'on_device\'`'''						)
					if map_location is None:
										lowercase		      =		'''cpu'''
					elif map_location == "on_device":
										lowercase		      =		PartialState().device
					# Model states
					for i, model in enumerate(lowerCAmelCase__						):
										lowercase		      =		f'{MODEL_NAME}.bin' if i == 0 else f'{MODEL_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										models[i].load_state_dict(torch.load(lowerCAmelCase__					,     map_location=lowerCAmelCase__						)					,     **lowerCAmelCase__						)
					logger.info('''All model weights loaded successfully'''						)

					# Optimizer states
					for i, opt in enumerate(lowerCAmelCase__						):
										lowercase		      =		f'{OPTIMIZER_NAME}.bin' if i == 0 else f'{OPTIMIZER_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										lowercase		      =		torch.load(lowerCAmelCase__					,     map_location=lowerCAmelCase__						)
										optimizers[i].load_state_dict(lowerCAmelCase__						)
					logger.info('''All optimizer states loaded successfully'''						)

					# Scheduler states
					for i, scheduler in enumerate(lowerCAmelCase__						):
										lowercase		      =		f'{SCHEDULER_NAME}.bin' if i == 0 else f'{SCHEDULER_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										scheduler.load_state_dict(torch.load(lowerCAmelCase__						)						)
					logger.info('''All scheduler states loaded successfully'''						)

					# GradScaler state
					if scaler is not None:
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										scaler.load_state_dict(torch.load(lowerCAmelCase__						)						)
										logger.info('''GradScaler state loaded successfully'''						)

					# Random states
					try:
										lowercase		      =		torch.load(os.path.join(lowerCAmelCase__					,     f'{RNG_STATE_NAME}_{process_index}.pkl'						)						)
										random.setstate(states['''random_state''']						)
										np.random.set_state(states['''numpy_random_seed''']						)
										torch.set_rng_state(states['''torch_manual_seed''']						)
										if is_xpu_available():
															torch.xpu.set_rng_state_all(states['''torch_xpu_manual_seed''']						)
										else:
															torch.cuda.set_rng_state_all(states['''torch_cuda_manual_seed''']						)
										if is_tpu_available():
															xm.set_rng_state(states['''xm_seed''']						)
										logger.info('''All random states loaded successfully'''						)
					except Exception:
										logger.info('''Could not load random states'''						)



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__ = 0						):
					'''simple docstring'''
					lowercase		      =		Path(lowerCAmelCase__						) / f'custom_checkpoint_{index}.pkl'
					logger.info(f'Saving the state of {get_pretty_name(lowerCAmelCase__						)} to {save_location}'						)
					torch.save(obj.state_dict()					,     lowerCAmelCase__						)



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__ = 0						):
					'''simple docstring'''
					lowercase		      =		f'{path}/custom_checkpoint_{index}.pkl'
					logger.info(f'Loading the state of {get_pretty_name(lowerCAmelCase__						)} from {load_location}'						)
					obj.load_state_dict(torch.load(lowerCAmelCase__					,     map_location='''cpu'''						)						)




