



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


UpperCamelCase_	       =   logging.get_logger(__name__)

UpperCamelCase_	       =   [
    "yjernite/retribert-base-uncased",
    # See all RetriBert models at https://huggingface.co/models?filter=retribert
]







class 							a_  (		_snake_case				):
						UpperCamelCase__      :						Any				       =RetriBertConfig
						UpperCamelCase__      :						List[str]				       =None
						UpperCamelCase__      :						Tuple				       ="retribert"

						def 	__a       (    self	:Any   ,						_lowercase	:Optional[Any])		->					Union[str, Any]:
												if isinstance(_lowercase   ,						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(_lowercase   ,						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(_lowercase   ,						nn.LayerNorm):
																		module.bias.data.zero_()
																		module.weight.data.fill_(1.0)

UpperCamelCase_	       =   r"\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 ([`RetriBertConfig`]): 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. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"







@add_start_docstrings(
    "Bert Based model to embed queries or document for document retrieval."					, _snake_case					, )
class 							a_  (		_snake_case				):

						def __init__(    self	:Tuple   ,						_lowercase	:RetriBertConfig)		->					None:
												super().__init__(_lowercase)
												UpperCAmelCase_     							=     config.projection_dim

												UpperCAmelCase_     							=     BertModel(_lowercase)
												UpperCAmelCase_     							=     None if config.share_encoders else BertModel(_lowercase)
												UpperCAmelCase_     							=     nn.Dropout(config.hidden_dropout_prob)
												UpperCAmelCase_     							=     nn.Linear(config.hidden_size   ,						config.projection_dim   ,						bias=_lowercase)
												UpperCAmelCase_     							=     nn.Linear(config.hidden_size   ,						config.projection_dim   ,						bias=_lowercase)

												UpperCAmelCase_     							=     nn.CrossEntropyLoss(reduction='''mean''')

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

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

																		# define function for checkpointing
																		def partial_encode(*_lowercase	:Dict):
																								UpperCAmelCase_     							=     sent_encoder.encoder(
																								    inputs[0]   ,						attention_mask=inputs[1]   ,						head_mask=_lowercase   ,						)
																								UpperCAmelCase_     							=     encoder_outputs[0]
																								UpperCAmelCase_     							=     sent_encoder.pooler(_lowercase)
																								return pooled_output

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

						def 	__a       (    self	:List[Any]   ,						_lowercase	:Optional[Any]   ,						_lowercase	:Optional[int]=None   ,						_lowercase	:int=-1   ,						)		->					Tuple:
												UpperCAmelCase_     							=     self.embed_sentences_checkpointed(
												    _lowercase   ,						_lowercase   ,						self.bert_query   ,						_lowercase   ,						)
												return self.project_query(_lowercase)

						def 	__a       (    self	:str   ,						_lowercase	:Optional[Any]   ,						_lowercase	:Optional[Any]=None   ,						_lowercase	:Optional[Any]=-1   ,						)		->					List[Any]:
												UpperCAmelCase_     							=     self.embed_sentences_checkpointed(
												    _lowercase   ,						_lowercase   ,						self.bert_query if self.bert_doc is None else self.bert_doc   ,						_lowercase   ,						)
												return self.project_doc(_lowercase)




						def 	__a       (    self	:Optional[int]   ,						_lowercase	:torch.LongTensor   ,						_lowercase	:Optional[torch.FloatTensor]   ,						_lowercase	:torch.LongTensor   ,						_lowercase	:Optional[torch.FloatTensor]   ,						_lowercase	:int = -1   ,						)		->					torch.FloatTensor:
												UpperCAmelCase_     							=     input_ids_query.device
												UpperCAmelCase_     							=     self.embed_questions(_lowercase   ,						_lowercase   ,						_lowercase)
												UpperCAmelCase_     							=     self.embed_answers(_lowercase   ,						_lowercase   ,						_lowercase)
												UpperCAmelCase_     							=     torch.mm(_lowercase   ,						a_reps.t())
												UpperCAmelCase_     							=     self.ce_loss(_lowercase   ,						torch.arange(compare_scores.shape[1]).to(_lowercase))
												UpperCAmelCase_     							=     self.ce_loss(compare_scores.t()   ,						torch.arange(compare_scores.shape[0]).to(_lowercase))
												UpperCAmelCase_     							=     (loss_qa + loss_aq) / 2
												return loss











'''simple docstring'''







from __future__ import annotations

_lowerCamelCase							:						Union[str, Any]								=  {1: 1}






def 		_lowercase		(	lowercase_  ):



		'''simple docstring'''







		if n in COLLATZ_SEQUENCE_LENGTHS:
				return COLLATZ_SEQUENCE_LENGTHS[n]
		_snake_case	       =       n // 2 if n % 2 == 0 else 3 * n + 1
		_snake_case	       =       collatz_sequence_length(lowercase_  ) + 1
		_snake_case	       =       sequence_length
		return sequence_length






def 		_lowercase		(	lowercase_ = 1000000  ):



		'''simple docstring'''







		_snake_case	       =       max((collatz_sequence_length(lowercase_  ), i) for i in range(1						,							lowercase_  )  )
		return result[1]


if __name__ == "__main__":
						print(solution(int(input().strip())))





