
from __future__ import annotations

import math
from itertools import permutations


def       UpperCamelCase(  __UpperCamelCase							:		Dict			):




		if 1 < number < 4:
				# 2 and 3 are primes
				return True
		elif number < 2 or number % 2 == 0 or number % 3 == 0:
				# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
				return False

		# All primes number are in format of 6k +/- 1
		for i in range(5					,int(math.sqrt(_UpperCamelCase			) + 1			)					,6			):
				if number % i == 0 or number % (i + 2) == 0:
						return False
		return True


def       UpperCamelCase(  __UpperCamelCase							:		List[str] = 7			):
		lowerCAmelCase_      :					int     =			"".join(str(_UpperCamelCase			) for i in range(1					,n + 1			)			)
		lowerCAmelCase_      :					List[str]     =			[int(''''''.join(_UpperCamelCase			)			) for i in permutations(_UpperCamelCase					,_UpperCamelCase			)]
		lowerCAmelCase_      :					Dict     =			[num for num in perm_list if is_prime(_UpperCamelCase			)]
		return max(_UpperCamelCase			) if pandigitals else 0


if __name__ == "__main__":
						print(F'''{solution() = }''')










import math
from typing import Optional

import torch
import torch.utils.checkpoint as checkpoint
from torch import nn

from ....modeling_utils import PreTrainedModel
from ....utils import add_start_docstrings, logging
from ...bert.modeling_bert import BertModel
from .configuration_retribert import RetriBertConfig


A__  :  Tuple       = logging.get_logger(__name__)

A__  :  List[str]       = [
    '''yjernite/retribert-base-uncased''',
    # See all RetriBert models at https://huggingface.co/models?filter=retribert
]



class     __snake_case						(					UpperCamelCase_						):
							_a      				=			RetriBertConfig
							_a      				=			None
							_a      				=			'''retribert'''




							def        UpperCAmelCase__      (	self					:	Optional[int]    ,    A_					:	Union[str, Any]):
									if isinstance(A_    ,    nn.Linear):
											module.weight.data.normal_(mean=0.0    ,    std=self.config.initializer_range)
											if module.bias is not None:
													module.bias.data.zero_()
									elif isinstance(A_    ,    nn.Embedding):
											module.weight.data.normal_(mean=0.0    ,    std=self.config.initializer_range)
											if module.padding_idx is not None:
													module.weight.data[module.padding_idx].zero_()
									elif isinstance(A_    ,    nn.LayerNorm):
											module.bias.data.zero_()
											module.weight.data.fill_(1.0)





A__  :  str       = R'''

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`RetriBertConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''



@add_start_docstrings(
    '''Bert Based model to embed queries or document for document retrieval.'''						,UpperCamelCase_						,)
class     __snake_case						(					UpperCamelCase_						):




							def __init__(	self					:	Optional[int]    ,    A_					:	RetriBertConfig):
									super().__init__(A_)
									lowerCAmelCase_      :					Optional[int]     =			config.projection_dim

									lowerCAmelCase_      :					int     =			BertModel(A_)
									lowerCAmelCase_      :					int     =			None if config.share_encoders else BertModel(A_)
									lowerCAmelCase_      :					str     =			nn.Dropout(config.hidden_dropout_prob)
									lowerCAmelCase_      :					Dict     =			nn.Linear(config.hidden_size    ,    config.projection_dim    ,    bias=A_)
									lowerCAmelCase_      :					Any     =			nn.Linear(config.hidden_size    ,    config.projection_dim    ,    bias=A_)

									lowerCAmelCase_      :					int     =			nn.CrossEntropyLoss(reduction='''mean''')

									# Initialize weights and apply final processing
									self.post_init()




							def        UpperCAmelCase__      (	self					:	str    ,    A_					:	Any    ,    A_					:	Optional[int]    ,    A_					:	Optional[int]    ,    A_					:	Optional[Any]=-1    ,    ):
									# reproduces BERT forward pass with checkpointing
									if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
											return sent_encoder(A_    ,    attention_mask=A_)[1]
									else:
											# prepare implicit variables
											lowerCAmelCase_      :					Any     =			input_ids.device
											lowerCAmelCase_      :					str     =			input_ids.size()
											lowerCAmelCase_      :					Dict     =			torch.zeros(A_    ,    dtype=torch.long    ,    device=A_)
											lowerCAmelCase_      :					List[str]     =			[None] * sent_encoder.config.num_hidden_layers
											lowerCAmelCase_      :					torch.Tensor     =			sent_encoder.get_extended_attention_mask(
											    A_    ,    A_)

											# define function for checkpointing
											def partial_encode(*A_					:	List[Any]):
													lowerCAmelCase_      :					Optional[Any]     =			sent_encoder.encoder(
													    inputs[0]    ,    attention_mask=inputs[1]    ,    head_mask=A_    ,    )
													lowerCAmelCase_      :					Any     =			encoder_outputs[0]
													lowerCAmelCase_      :					Optional[Any]     =			sent_encoder.pooler(A_)
													return pooled_output

											# run embedding layer on everything at once
											lowerCAmelCase_      :					str     =			sent_encoder.embeddings(
											    input_ids=A_    ,    position_ids=A_    ,    token_type_ids=A_    ,    inputs_embeds=A_)
											# run encoding and pooling on one mini-batch at a time
											lowerCAmelCase_      :					str     =			[]
											for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size)):
													lowerCAmelCase_      :					Optional[Any]     =			embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
													lowerCAmelCase_      :					int     =			extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
													lowerCAmelCase_      :					str     =			checkpoint.checkpoint(A_    ,    A_    ,    A_)
													pooled_output_list.append(A_)
											return torch.cat(A_    ,    dim=0)




							def        UpperCAmelCase__      (	self					:	List[str]    ,    A_					:	List[Any]    ,    A_					:	Union[str, Any]=None    ,    A_					:	Dict=-1    ,    ):
									lowerCAmelCase_      :					Optional[int]     =			self.embed_sentences_checkpointed(
									    A_    ,    A_    ,    self.bert_query    ,    A_    ,    )
									return self.project_query(A_)




							def        UpperCAmelCase__      (	self					:	Optional[Any]    ,    A_					:	str    ,    A_					:	int=None    ,    A_					:	Any=-1    ,    ):
									lowerCAmelCase_      :					Union[str, Any]     =			self.embed_sentences_checkpointed(
									    A_    ,    A_    ,    self.bert_query if self.bert_doc is None else self.bert_doc    ,    A_    ,    )
									return self.project_doc(A_)







							def        UpperCAmelCase__      (	self					:	List[Any]    ,    A_					:	torch.LongTensor    ,    A_					:	Optional[torch.FloatTensor]    ,    A_					:	torch.LongTensor    ,    A_					:	Optional[torch.FloatTensor]    ,    A_					:	int = -1    ,    ):
									lowerCAmelCase_      :					List[Any]     =			input_ids_query.device
									lowerCAmelCase_      :					List[str]     =			self.embed_questions(A_    ,    A_    ,    A_)
									lowerCAmelCase_      :					Union[str, Any]     =			self.embed_answers(A_    ,    A_    ,    A_)
									lowerCAmelCase_      :					Any     =			torch.mm(A_    ,    a_reps.t())
									lowerCAmelCase_      :					int     =			self.ce_loss(A_    ,    torch.arange(compare_scores.shape[1]).to(A_))
									lowerCAmelCase_      :					str     =			self.ce_loss(compare_scores.t()    ,    torch.arange(compare_scores.shape[0]).to(A_))
									lowerCAmelCase_      :					List[Any]     =			(loss_qa + loss_aq) / 2
									return loss





