




"""simple docstring"""


import unittest

from transformers import BertGenerationConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import BertGenerationDecoder, BertGenerationEncoder






class  lowercase:







	'''simple docstring'''





	def __init__(    self:		str,				a_:		Any,				a_:		Union[str, Any]=13,				a_:		Any=7,				a_:		Optional[Any]=True,				a_:		str=True,				a_:		List[str]=99,				a_:		List[str]=32,				a_:		Tuple=5,				a_:		Any=4,				a_:		Tuple=37,				a_:		Optional[Any]="gelu",				a_:		Union[str, Any]=0.1,				a_:		Dict=0.1,				a_:		Union[str, Any]=50,				a_:		Any=0.02,				a_:		List[Any]=True,				a_:		str=None,				):




			'''simple docstring'''



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


	def 			UpperCamelCase_       (    self:		str		):




			'''simple docstring'''



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

			_snake_case							:		Optional[Any]								=  None
			if self.use_input_mask:
					_snake_case							:		Optional[int]								=  random_attention_mask([self.batch_size, self.seq_length]		)

			if self.use_labels:
					_snake_case							:		int								=  ids_tensor([self.batch_size, self.seq_length],				self.vocab_size		)

			_snake_case							:		List[Any]								=  self.get_config()

			return config, input_ids, input_mask, token_labels


	def 			UpperCamelCase_       (    self:		Any		):




			'''simple docstring'''



			return BertGenerationConfig(
			    vocab_size=self.vocab_size,				hidden_size=self.hidden_size,				num_hidden_layers=self.num_hidden_layers,				num_attention_heads=self.num_attention_heads,				intermediate_size=self.intermediate_size,				hidden_act=self.hidden_act,				hidden_dropout_prob=self.hidden_dropout_prob,				attention_probs_dropout_prob=self.attention_probs_dropout_prob,				max_position_embeddings=self.max_position_embeddings,				is_decoder=a_,				initializer_range=self.initializer_range,				)


	def 			UpperCamelCase_       (    self:		str		):




			'''simple docstring'''



			(
			    _snake_case 
			)							:		Tuple								=  self.prepare_config_and_inputs()

			_snake_case							:		Tuple								=  True
			_snake_case							:		Dict								=  floats_tensor([self.batch_size, self.seq_length, self.hidden_size]		)
			_snake_case							:		List[str]								=  ids_tensor([self.batch_size, self.seq_length],				vocab_size=2		)

			return (
			    config,
			    input_ids,
			    input_mask,
			    token_labels,
			    encoder_hidden_states,
			    encoder_attention_mask,
			)


	def 			UpperCamelCase_       (    self:		Optional[int],				a_:		Tuple,				a_:		Tuple,				a_:		str,				a_:		int,				**a_:		List[str],				):




			'''simple docstring'''



			_snake_case							:		Dict								=  BertGenerationEncoder(config=a_		)
			model.to(a_		)
			model.eval()
			_snake_case							:		Optional[int]								=  model(a_,				attention_mask=a_		)
			_snake_case							:		Dict								=  model(a_		)
			self.parent.assertEqual(result.last_hidden_state.shape,				(self.batch_size, self.seq_length, self.hidden_size)		)


	def 			UpperCamelCase_       (    self:		List[Any],				a_:		Optional[Any],				a_:		Dict,				a_:		Optional[Any],				a_:		str,				a_:		int,				a_:		List[Any],				**a_:		List[Any],				):




			'''simple docstring'''



			_snake_case							:		Tuple								=  True
			_snake_case							:		Any								=  BertGenerationEncoder(config=a_		)
			model.to(a_		)
			model.eval()
			_snake_case							:		str								=  model(
			    a_,				attention_mask=a_,				encoder_hidden_states=a_,				encoder_attention_mask=a_,				)
			_snake_case							:		List[str]								=  model(
			    a_,				attention_mask=a_,				encoder_hidden_states=a_,				)
			self.parent.assertEqual(result.last_hidden_state.shape,				(self.batch_size, self.seq_length, self.hidden_size)		)


	def 			UpperCamelCase_       (    self:		int,				a_:		Optional[int],				a_:		str,				a_:		str,				a_:		Any,				a_:		Optional[Any],				a_:		str,				**a_:		List[Any],				):




			'''simple docstring'''



			_snake_case							:		Any								=  True
			_snake_case							:		Dict								=  True
			_snake_case							:		List[Any]								=  BertGenerationDecoder(config=a_		).to(a_		).eval()

			# first forward pass
			_snake_case							:		Any								=  model(
			    a_,				attention_mask=a_,				encoder_hidden_states=a_,				encoder_attention_mask=a_,				use_cache=a_,				)
			_snake_case							:		Dict								=  outputs.past_key_values

			# create hypothetical multiple next token and extent to next_input_ids
			_snake_case							:		List[str]								=  ids_tensor((self.batch_size, 3),				config.vocab_size		)
			_snake_case							:		Dict								=  ids_tensor((self.batch_size, 3),				vocab_size=2		)

			# append to next input_ids and
			_snake_case							:		int								=  torch.cat([input_ids, next_tokens],				dim=-1		)
			_snake_case							:		List[str]								=  torch.cat([input_mask, next_mask],				dim=-1		)

			_snake_case							:		Any								=  model(
			    a_,				attention_mask=a_,				encoder_hidden_states=a_,				encoder_attention_mask=a_,				output_hidden_states=a_,				)["""hidden_states"""][0]
			_snake_case							:		str								=  model(
			    a_,				attention_mask=a_,				encoder_hidden_states=a_,				encoder_attention_mask=a_,				past_key_values=a_,				output_hidden_states=a_,				)["""hidden_states"""][0]

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

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

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


	def 			UpperCamelCase_       (    self:		Union[str, Any],				a_:		Union[str, Any],				a_:		int,				a_:		List[str],				a_:		str,				*a_:		Optional[int],				):




			'''simple docstring'''



			_snake_case							:		Dict								=  BertGenerationDecoder(a_		)
			model.to(a_		)
			model.eval()
			_snake_case							:		Optional[int]								=  model(a_,				attention_mask=a_,				labels=a_		)
			self.parent.assertEqual(result.logits.shape,				(self.batch_size, self.seq_length, self.vocab_size)		)


	def 			UpperCamelCase_       (    self:		Dict		):




			'''simple docstring'''



			_snake_case							:		List[Any]								=  self.prepare_config_and_inputs()
			_snake_case							:		List[str]								=  {"""input_ids""": input_ids, """attention_mask""": input_mask}
			return config, inputs_dict







@require_torch
class  lowercase(					__a	,      __a	,      __a	,      unittest.TestCase			):







	'''simple docstring'''





	lowercase__			 = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else ()
	lowercase__			 = (BertGenerationDecoder,) if is_torch_available() else ()
	lowercase__			 = (
	    {"feature-extraction": BertGenerationEncoder, "text-generation": BertGenerationDecoder}
	    if is_torch_available()
	    else {}
	)


	def 			UpperCamelCase_       (    self:		int		):




			'''simple docstring'''



			_snake_case							:		Any								=  BertGenerationEncoderTester(self		)
			_snake_case							:		Any								=  ConfigTester(self,				config_class=a_,				hidden_size=37		)


	def 			UpperCamelCase_       (    self:		Optional[int]		):




			'''simple docstring'''



			self.config_tester.run_common_tests()


	def 			UpperCamelCase_       (    self:		int		):




			'''simple docstring'''



			_snake_case							:		Dict								=  self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*a_		)


	def 			UpperCamelCase_       (    self:		Union[str, Any]		):




			'''simple docstring'''



			_snake_case							:		Tuple								=  self.model_tester.prepare_config_and_inputs()
			_snake_case							:		Optional[int]								=  """bert"""
			self.model_tester.create_and_check_model(a_,				a_,				a_,				a_		)


	def 			UpperCamelCase_       (    self:		int		):




			'''simple docstring'''



			_snake_case							:		Any								=  self.model_tester.prepare_config_and_inputs_for_decoder()
			self.model_tester.create_and_check_model_as_decoder(*a_		)


	def 			UpperCamelCase_       (    self:		Any		):




			'''simple docstring'''



			_snake_case							:		Tuple								=  self.model_tester.prepare_config_and_inputs_for_decoder()
			self.model_tester.create_and_check_decoder_model_past_large_inputs(*a_		)


	def 			UpperCamelCase_       (    self:		Dict		):




			'''simple docstring'''



			(
			    _snake_case 
			)							:		Union[str, Any]								=  self.model_tester.prepare_config_and_inputs_for_decoder()

			_snake_case							:		str								=  None

			self.model_tester.create_and_check_model_as_decoder(
			    a_,				a_,				a_,				a_,				a_,				a_,				)


	def 			UpperCamelCase_       (    self:		int		):




			'''simple docstring'''



			_snake_case							:		Any								=  self.model_tester.prepare_config_and_inputs_for_decoder()
			self.model_tester.create_and_check_for_causal_lm(*a_		)


	@slow
	def 			UpperCamelCase_       (    self:		List[Any]		):




			'''simple docstring'''



			_snake_case							:		Any								=  BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder"""		)
			self.assertIsNotNone(a_		)







@require_torch
class  lowercase(					unittest.TestCase			):







	'''simple docstring'''





	@slow
	def 			UpperCamelCase_       (    self:		List[str]		):




			'''simple docstring'''



			_snake_case							:		Tuple								=  BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder"""		)
			_snake_case							:		List[Any]								=  torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]]		)
			with torch.no_grad():
					_snake_case							:		int								=  model(a_		)[0]
			_snake_case							:		Union[str, Any]								=  torch.Size([1, 8, 1_024]		)
			self.assertEqual(output.shape,				a_		)
			_snake_case							:		Optional[int]								=  torch.tensor(
			    [[[0.1_775, 0.0_083, -0.0_321], [1.6_002, 0.1_287, 0.3_912], [2.1_473, 0.5_791, 0.6_066]]]		)
			self.assertTrue(torch.allclose(output[:, :3, :3],				a_,				atol=1E-4		)		)







@require_torch
class  lowercase(					unittest.TestCase			):







	'''simple docstring'''





	@slow
	def 			UpperCamelCase_       (    self:		Optional[Any]		):




			'''simple docstring'''



			_snake_case							:		Union[str, Any]								=  BertGenerationDecoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder"""		)
			_snake_case							:		Optional[int]								=  torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]]		)
			with torch.no_grad():
					_snake_case							:		List[Any]								=  model(a_		)[0]
			_snake_case							:		Tuple								=  torch.Size([1, 8, 50_358]		)
			self.assertEqual(output.shape,				a_		)
			_snake_case							:		Optional[Any]								=  torch.tensor(
			    [[[-0.5_788, -2.5_994, -3.7_054], [0.0_438, 4.7_997, 1.8_795], [1.5_862, 6.6_409, 4.4_638]]]		)
			self.assertTrue(torch.allclose(output[:, :3, :3],				a_,				atol=1E-4		)		)








"""simple docstring"""


import torch
from torch import nn






class  lowercase(					nn.Module			):







 '''simple docstring'''





 def __init__(    self:		Any,				a_:		List[str],				a_:		Union[str, Any],				a_:		int,				a_:		int,				a_:		List[Any]=1,				a_:		Union[str, Any]=False		):




   '''simple docstring'''



   super().__init__()

   _snake_case							:		int								=  n_token
   _snake_case							:		Tuple								=  d_embed
   _snake_case							:		List[str]								=  d_proj

   _snake_case							:		Optional[int]								=  cutoffs + [n_token]
   _snake_case							:		Any								=  [0] + self.cutoffs
   _snake_case							:		Tuple								=  div_val

   _snake_case							:		Optional[int]								=  self.cutoffs[0]
   _snake_case							:		Union[str, Any]								=  len(self.cutoffs		) - 1
   _snake_case							:		Union[str, Any]								=  self.shortlist_size + self.n_clusters

   if self.n_clusters > 0:
     _snake_case							:		List[Any]								=  nn.Parameter(torch.zeros(self.n_clusters,				self.d_embed		)		)
     _snake_case							:		Tuple								=  nn.Parameter(torch.zeros(self.n_clusters		)		)

   _snake_case							:		Any								=  nn.ModuleList()
   _snake_case							:		Optional[Any]								=  nn.ParameterList()

   if div_val == 1:
     for i in range(len(self.cutoffs		)		):
       if d_proj != d_embed:
         self.out_projs.append(nn.Parameter(torch.FloatTensor(a_,				a_		)		)		)
       else:
         self.out_projs.append(a_		)

     self.out_layers.append(nn.Linear(a_,				a_		)		)
   else:
     for i in range(len(self.cutoffs		)		):
       _snake_case		, _snake_case							:		List[Any]								=  self.cutoff_ends[i], self.cutoff_ends[i + 1]
       _snake_case							:		Union[str, Any]								=  d_embed // (div_val**i)

       self.out_projs.append(nn.Parameter(torch.FloatTensor(a_,				a_		)		)		)

       self.out_layers.append(nn.Linear(a_,				r_idx - l_idx		)		)

   _snake_case							:		Optional[int]								=  keep_order


 def 			UpperCamelCase_       (    self:		str,				a_:		Union[str, Any],				a_:		Dict,				a_:		int,				a_:		Tuple		):




   '''simple docstring'''



   if proj is None:
     _snake_case							:		List[Any]								=  nn.functional.linear(a_,				a_,				bias=a_		)
   else:
     # if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1:
     _snake_case							:		List[Any]								=  nn.functional.linear(a_,				proj.t().contiguous()		)
     _snake_case							:		Tuple								=  nn.functional.linear(a_,				a_,				bias=a_		)
     # else:
     #     logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t()))
     #     if bias is not None:
     #         logit = logit + bias

   return logit


 def 			UpperCamelCase_       (    self:		Dict,				a_:		Dict,				a_:		str=None,				a_:		Union[str, Any]=False		):




   '''simple docstring'''



   if labels is not None:
     # Shift so that tokens < n predict n
     _snake_case							:		int								=  hidden[..., :-1, :].contiguous()
     _snake_case							:		List[Any]								=  labels[..., 1:].contiguous()
     _snake_case							:		str								=  hidden.view(-1,				hidden.size(-1		)		)
     _snake_case							:		Dict								=  labels.view(-1		)
     if hidden.size(0		) != labels.size(0		):
       raise RuntimeError("""Input and labels should have the same size in the batch dimension."""		)
   else:
     _snake_case							:		int								=  hidden.view(-1,				hidden.size(-1		)		)

   if self.n_clusters == 0:
     _snake_case							:		Tuple								=  self._compute_logit(a_,				self.out_layers[0].weight,				self.out_layers[0].bias,				self.out_projs[0]		)
     if labels is not None:
       _snake_case							:		Dict								=  labels != -100
       _snake_case							:		str								=  torch.zeros_like(a_,				dtype=hidden.dtype,				device=hidden.device		)
       _snake_case							:		str								=  (
           -nn.functional.log_softmax(a_,				dim=-1		)[mask].gather(1,				labels[mask].unsqueeze(1		)		).squeeze(1		)
       )
     else:
       _snake_case							:		Optional[int]								=  nn.functional.log_softmax(a_,				dim=-1		)
   else:
     # construct weights and biases
     _snake_case		, _snake_case							:		Optional[int]								=  [], []
     for i in range(len(self.cutoffs		)		):
       if self.div_val == 1:
         _snake_case		, _snake_case							:		Optional[int]								=  self.cutoff_ends[i], self.cutoff_ends[i + 1]
         _snake_case							:		List[Any]								=  self.out_layers[0].weight[l_idx:r_idx]
         _snake_case							:		Tuple								=  self.out_layers[0].bias[l_idx:r_idx]
       else:
         _snake_case							:		Optional[int]								=  self.out_layers[i].weight
         _snake_case							:		int								=  self.out_layers[i].bias

       if i == 0:
         _snake_case							:		List[str]								=  torch.cat([weight_i, self.cluster_weight],				dim=0		)
         _snake_case							:		int								=  torch.cat([bias_i, self.cluster_bias],				dim=0		)

       weights.append(a_		)
       biases.append(a_		)

     _snake_case		, _snake_case		, _snake_case							:		Any								=  weights[0], biases[0], self.out_projs[0]

     _snake_case							:		List[str]								=  self._compute_logit(a_,				a_,				a_,				a_		)
     _snake_case							:		Union[str, Any]								=  nn.functional.log_softmax(a_,				dim=1		)

     if labels is None:
       _snake_case							:		Tuple								=  hidden.new_empty((head_logit.size(0		), self.n_token)		)
     else:
       _snake_case							:		Dict								=  torch.zeros_like(a_,				dtype=hidden.dtype,				device=hidden.device		)

     _snake_case							:		Union[str, Any]								=  0
     _snake_case							:		Optional[Any]								=  [0] + self.cutoffs
     for i in range(len(a_		) - 1		):
       _snake_case		, _snake_case							:		Dict								=  cutoff_values[i], cutoff_values[i + 1]

       if labels is not None:
         _snake_case							:		Dict								=  (labels >= l_idx) & (labels < r_idx)
         _snake_case							:		int								=  mask_i.nonzero().squeeze()

         if indices_i.numel() == 0:
           continue

         _snake_case							:		List[str]								=  labels.index_select(0,				a_		) - l_idx
         _snake_case							:		List[str]								=  head_logprob.index_select(0,				a_		)
         _snake_case							:		List[str]								=  hidden.index_select(0,				a_		)
       else:
         _snake_case							:		List[str]								=  hidden

       if i == 0:
         if labels is not None:
           _snake_case							:		Dict								=  head_logprob_i.gather(1,				target_i[:, None]		).squeeze(1		)
         else:
           _snake_case							:		Optional[Any]								=  head_logprob[:, : self.cutoffs[0]]
       else:
         _snake_case		, _snake_case		, _snake_case							:		Dict								=  weights[i], biases[i], self.out_projs[i]

         _snake_case							:		int								=  self._compute_logit(a_,				a_,				a_,				a_		)
         _snake_case							:		int								=  nn.functional.log_softmax(a_,				dim=1		)
         _snake_case							:		Dict								=  self.cutoffs[0] + i - 1  # No probability for the head cluster
         if labels is not None:
           _snake_case							:		Dict								=  head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather(
               1,				target_i[:, None]		).squeeze(1		)
         else:
           _snake_case							:		Optional[Any]								=  head_logprob[:, cluster_prob_idx, None] + tail_logprob_i
           _snake_case							:		Any								=  logprob_i

       if labels is not None:
         if (hasattr(self,				"""keep_order"""		) and self.keep_order) or keep_order:
           out.index_copy_(0,				a_,				-logprob_i		)
         else:
           out[offset : offset + logprob_i.size(0		)].copy_(-logprob_i		)
         offset += logprob_i.size(0		)

   return out


 def 			UpperCamelCase_       (    self:		Union[str, Any],				a_:		Optional[int]		):




   '''simple docstring'''



   if self.n_clusters == 0:
     _snake_case							:		Optional[int]								=  self._compute_logit(a_,				self.out_layers[0].weight,				self.out_layers[0].bias,				self.out_projs[0]		)
     return nn.functional.log_softmax(a_,				dim=-1		)
   else:
     # construct weights and biases
     _snake_case		, _snake_case							:		List[Any]								=  [], []
     for i in range(len(self.cutoffs		)		):
       if self.div_val == 1:
         _snake_case		, _snake_case							:		Optional[Any]								=  self.cutoff_ends[i], self.cutoff_ends[i + 1]
         _snake_case							:		Optional[int]								=  self.out_layers[0].weight[l_idx:r_idx]
         _snake_case							:		str								=  self.out_layers[0].bias[l_idx:r_idx]
       else:
         _snake_case							:		List[Any]								=  self.out_layers[i].weight
         _snake_case							:		Union[str, Any]								=  self.out_layers[i].bias

       if i == 0:
         _snake_case							:		int								=  torch.cat([weight_i, self.cluster_weight],				dim=0		)
         _snake_case							:		Dict								=  torch.cat([bias_i, self.cluster_bias],				dim=0		)

       weights.append(a_		)
       biases.append(a_		)

     _snake_case		, _snake_case		, _snake_case							:		int								=  weights[0], biases[0], self.out_projs[0]
     _snake_case							:		List[Any]								=  self._compute_logit(a_,				a_,				a_,				a_		)

     _snake_case							:		List[Any]								=  hidden.new_empty((head_logit.size(0		), self.n_token)		)
     _snake_case							:		int								=  nn.functional.log_softmax(a_,				dim=1		)

     _snake_case							:		List[Any]								=  [0] + self.cutoffs
     for i in range(len(a_		) - 1		):
       _snake_case		, _snake_case							:		List[str]								=  cutoff_values[i], cutoff_values[i + 1]

       if i == 0:
         _snake_case							:		List[str]								=  head_logprob[:, : self.cutoffs[0]]
       else:
         _snake_case		, _snake_case		, _snake_case							:		List[Any]								=  weights[i], biases[i], self.out_projs[i]

         _snake_case							:		Optional[int]								=  self._compute_logit(a_,				a_,				a_,				a_		)
         _snake_case							:		Any								=  nn.functional.log_softmax(a_,				dim=1		)

         _snake_case							:		Dict								=  head_logprob[:, -i] + tail_logprob_i
         _snake_case							:		Any								=  logprob_i

     return out


